Basic information for python

5 minute read

Recently, python users have been increased rapidly. Python’s various libraries, such as tensor flow, and machine learning will attract many users in the future.

Pythons Tutorials (w3schools.com)

Useful tips

Check parameters

File handling

Basic functions

  • map, reduce, filter, append, lambda, range, substring, zfill

Basic grammars

Variables

  • Variables : int, float
  • Golbal variable
      global str
      del str # Delete a variable
    

Data types

Python has an in-built function type() to ascertain the data type of a certain value.

1. Numeric : Integer, Float, Complex number

2. Boolean : True/False

  • ‘T’ and ‘F’ are capital

3. String

  • The triple quoted string is useful when a multi-line text is to be defined as a string literal.
  • The escape character is used to invoke an alternative implementation of the subsequent character in a sequence.
  • String Operators : +, *, [], [:], in, not in
  • format() method
  • Built-in String Methods : capitalize(), upper(), lower(), title(), find(), count(), isalpha(), isdigit(), islower(), isupper()
# String
myString='hello'
myString[0]
# 'h'

# Converting to string (cf. int(), float() and complex())
str(1.11)
# '1.11'

# String formatting
name="Bond"
age=30
"My name is %s and age is %d years." % (name, age)
# 'My name is Bond and age is 30 years.'

Link : String tutorial

4. List

  • In Python, the list is a collection of items of different data types.
  • List Operators : +, *, [], [:], in, not in
  • Built-in Tuple Methods : len(), max(), min(), append(), insert(), remove(), pop, reverse(), sort(), list(), tuple()
items=[1, "Jeff", "Computer", 75.50, True]
items[3]="Laptop"
items
# [1, 'Jeff', 'Computer', 'Laptop', True]
items[-2]
 75.5

Link : List tutorial

5. Tuple

  • Tuple is a collection of items of any Python data type, same as the list type. Unlike the list, tuple is immutable.
  • Tuple Operators : +, *, [], [:], in, not in
  • Built-in Tuple Methods : len(), max(), min()
names=("Jeff", "Bill", "Steve", "Mohan")
names="Jeff", "Bill", "Steve", "Mohan"
type(names)
# <class 'tuple'>

items=(1, "Jeff", "Computer", 75.50, True)
items[-1]
# True

Link : Tuple tutorial

6. Set

  • A set is a collection of data types in Python, same as the list and tuple.
  • However, it is not an ordered collection of objects.
  • A set doesn’t store duplicate objects.
  • set() function
  • set() operations : , union(), &, intersection(), difference(), ^, Symmetric_difference()
  • Built-in Set Methods : add(), update(), clear(), copy(), discard(), remove()
S1={1, 2, 2, 3, 4, 4, 5, 5}
S1
# {1, 2, 3, 4, 5}

7. Dictionary

  • A number, string or tuple can be used as key.
  • Built-in Dictionary Methods : len(), max(), min(), pop(), clear(), items():, keys(), values():, update()
staff={"Krishna":"Officer", "Steve":"Manager", "John":"officer", "Anil":"Clerk", "John":"Manager"}
staff
# {'Krishna': 'Officer', 'Steve': 'Manager', 'John': 'Manager', 'Anil': 'Clerk'}

capitals={"USA":"Washington, D.C.", "France":"Paris", "India":"New Delhi"}
capitals.get("USA")
# 'Washington, D.C.'

for key in capitals:
    print("Key = " + key + ", Value = " + capitals[key]) 
# Key = USA, Value = Washington, D.C.
# Key = France, Value = Paris
# Key = India, Value = New Delhi

# Update
capitals['USA'] = "America"
capitals
# {'USA': 'America', 'France': 'Paris', 'India': 'New Delhi'}

# Delete
del capitals['USA']
capitals
# {'France': 'Paris', 'India': 'New Delhi'}

Link : Dictionary tutorial

String format

## String format
a = 1
b = 1.2
print("%.2f" % (a)) # 1.00
print(a , b)

b = "i am a {0}".format("bbb")
print(b)

# string length
len(str)

str='ABC'
print(str[1])
# B

Link : Set tutorial

Type Convertion

  • int(), float(), str(), list(), tuple(), set()

Operators

  • Arithmetic Operators : +, -, *, /, **, //, %
    • The pow() function returns the value of x to the power of y (x^y)
  • Logical Operators : and, or, not
  • Comparison Operators : <, >, >=, <=, ==, !=

Number system

  • binary : print(0b10001) -> 17, bin(17) -> ‘0b10001’
  • octet : print(0o21) -> 17, oct(17) -> ‘0o21’
  • hex : print(0x11) -> 17, hex(17) -> ‘0x11’

Condition and Loop : if, while, switch

# if statement
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

# while statement
i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  else
    continue
  i += 1

# for statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Datetime

1. Datetime format

import time
import datetime

print(time.strftime("%Y-%m-%d %H:%M:%S"))
print(datetime.datetime.now())
print("Time in seconds since the epoch: %s" %time.time())
print("Current date and time: " , datetime.datetime.now())
print("Or like this: " , datetime.datetime.now().strftime("%y-%m-%d-%H-%M"))
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftime("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%w"))
print("Day of year: ", datetime.date.today().strftime("%j"))
print("Day of the month : ", datetime.date.today().strftime("%d"))
print("Day of week: ", datetime.date.today().strftime("%A"))
<Output>
2019-10-29 16:35:50
2019-10-29 16:35:50.710548
Time in seconds since the epoch: 1572334550.7105482
Current date and time:  2019-10-29 16:35:50.710548
Or like this:  19-10-29-16-35
Current year:  2019
Month of year:  October
Week number of the year:  43
Weekday of the week:  2
Day of year:  302
Day of the month :  29
Day of week:  Tuesday
%a  Locale's abbreviated weekday name.
%A  Locale's full weekday name.      
%b  Locale's abbreviated month name.     
%B  Locale's full month name.
%c  Locale's appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].      
%p  Locale's equivalent of either AM or PM.
%S  Second as a decimal number [00,61].
%U  Week number of the year (Sunday as the first day of the week)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week)
%x  Locale's appropriate date representation.    
%X  Locale's appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.  

2. Elapsed time

import time
import datetime

start_time = datetime.datetime.now() # 2019-03-11 10:44:18.246000
print("START...")
print(start_time)

# your script
time.sleep(5)

end_time = datetime.datetime.now()

elapsed = end_time - start_time

print(end_time)
print("END")

print(elapsed)
print("ELAPSED:", elapsed.seconds,":",elapsed.microseconds)
<Result>
START...
2019-10-29 16:43:34.427298
2019-10-29 16:43:39.428597
END
0:00:05.001299
ELAPSED: 5 : 1299

Tags:

Categories:

Updated:

Leave a comment