Syntax and symantics
Type Conversion and Datatypes
Datatypes
- Intergers
- Floating Point numbers
- Strings
- Boolean
- List
- Tuples
- Sets
- Dictionaries
age = 25
age_str = str(age)
age_float = float(age_str)
Operators
//
floor division11//5
will give you2.0
(when divided whatever the lower value is it will give you equivalent to php floor function)**
Exponential10**5
(10 to the power of 5) will give you1000000
- Use
and
instead of&&
, Useor
instead of||
, usenot
instead of!
Conditions
age = 10
if age >= 8:
print('Hey')
elif age < 11:
print('Ho')
else
print('coo')
Loops
Range
for i in rage(1,6):
print(i)
# step size of 2 means jump 2 ahead i.e 1, 3, 5, 7, 9
for i in rage(1,10,2):
print(i)
# reverse with -1 i.e 10,9,8....,2
for i in rage(1,10,-1):
print(i)
Besides break
and continue
there is something called pass
. pass
is a null operation, it does nothing. Usually used in empty function or condition.
for i in range(5):
if i == 3:
pass
print(i)
# The above will print 0, 1, 2, 3, 4
List
names = ['Ram','Shyam', 1.2, 100, True, 1,2,3]
fruits = ['ap', 'ba', 'ch', 'ki', 'gua']
print(fruits[1:]) # escape first and print everything after that
print(fruits[1:3]) # escape one and go up to 3rd index
print(fruits[-1:]) # first index from the last
List Method
append
to add item at the endfruits.insert(1, 'Watermelon')
Add item to the first index and shift all the items by 1fruits.remove('banana')
remove the first occurance based on value.fruits.pop()
remove the last item and return it.fruits.index('cherry')
get the index of a valuefruits.count('banana')
count the number of items in array by value (how many banana)fruits.sort()
sort by name or numberfruits.clear()
remove all items
numbers = [1,2,3,4,5,6,7,8,9]
Slicing
::
double column means all the value number[::]
will print [1,2,3,4,5,6,7,8,9]
numbers[2:5]
numbers[:5]
numbers[5:]
numbers[::2]
2 here is the step size to jump output would be[1, 3, 5, 7, 9]
numbers[::-1]
from previous value output[9, 8, 7, 6, 5, 4, 3, 2, 1]
numbers[::-2]
from previous value output[9, 7, 5, 3, 1]
Iterations
for number in numbers
print(number)
# also access the index
for index, number in enumerators(numbers)
print(number)
List comprehensions
Basic syntax [expression for item in iterables] Using list comprehensions you can basically shortify syntax. for eg: this
vaLong = []
for i in range(10):
vaLong.append(i**2)
can be converted to
vaShort = [x**2 for x in range(10)]
Condition logic can also be implemented by placing it at the end
eg: list comprehensions to find out the square of a number but ony if its everything
numSquare = [num** 2 for num in range(10) if num%2==0]
print(numSquare)
Nested list comprehensions is to iterate through two or more list to create a pair of use the value of both of list item in the comprehension.
list1 = [1, 2, 3, 4]
list2 = ['a', 'b', 'c', 'd']
numSquare = [[i,j] for i in list1 for j in list2]
print(numSquare)
# [[1, 'a'], [1, 'b'], [1, 'c'], [1, 'd'], [2, 'a'], [2, 'b'], [2, 'c'], [2, 'd'], [3, 'a'], [3, 'b'], [3, 'c'], [3, 'd'], [4, 'a'], [4, 'b'], [4, 'c'], [4, 'd']]
List comprehension with function call
words = ['apple', 'ball', 'cat', 'dog', 'elephant']
count = [len(word) for word in words]
print(count) # [5, 4, 3, 3, 8]
Tuples
They are similar to list but they are immutable (elements cannot be changed once assigned) and are denoted by small paranthesis ()
# create tuble
a = ()
b = tuple()
c = list() # create list
d = tuple([1,2]) # convert list to tuple.
e = list((1,2)) # convert tuple to list .
f = 1,2,3,5,"hello" # By default this becomes a tuple.
Accessing Tuple
Access it just like array using the index print(numbers[1])
, print(numbers[-1])
, print(numbers[0:4])
etc the return type will be tuple.
Tuple operations
- Combine tuples with
+
i.econcat = (1,2) + ('a', 'b')
outputs(1, 2, 'a', 'b')
- Multiple tuples
('a', 'b') * 3
repeats the tuple 3 times.
Tuple methods.
concat.count('b')
count the number of occurance ofb
in the tuple variablecount
concat.index(3)
find the index of3
in the tuple variablecount
- unpack a tuple
a,b,c = (1,2,3)
or you can also unpack it using * example blow.
numbers = (1,2,3,4,5)
first, middle, *last = numbers
print(first) # 1
print(middle) # 2
print(last) # [3, 4, 5]
Iterate
Iterate over the tuple just like list or array.
Sets
Used to store collection of unique items. They do not allow duplicate elements and helpful for performing mathmatical set of operations like union, intersection, difference and symmetric differences.
mySet = {1,2,3,4,4}
print(mySet) # 1,2,3,4
mySet = set([1,2,3,4,4])
Set operations
mySet = {1,2,3,4,4}
mySet.add(7)
mySet.remove(3) # will give you error if no item found
mySet.discard(3) # will not give error if no item found, if found will remove it.
mySet.pop() # Remove first element and return it
mySet.clear() # will clear all the element.
#-----
3 in mySet # check whether a element is in set.
# -----
setOne = {'a', 'b', 'c', 'd', 'e'}
setTwo = {1, 2, 3, 4, 5, 6, 7}
setOne.union(setTwo) # combine both set
setTwo.intersection(setOne) # get only common between two sets
setOne.intersection_update(setTwo) # update setOne variable with common between setOne and setTwo
setOne.difference(setTwo) # gives you only the difference element in setOne that does not exist in setTwo.
setOne.symmetric_difference (setTwo) # all the difference in both setOne and setTwo
Set Methods.
setOne.issubset(setTwo)
Does all the element insetOne
exists insetTwo
setOne.issuperset(setTwo)
Dictionaries
Are mutable unordered collection of items. They store in key value pairst. Key must be unique and immutable (strings,numbers or tuples ), while values can be anything.
a = {} # empty dictionary.
b = dict() # empty dictionary.
# Accessing dictionary
a = {"name": "jobn"}
a['name']
a.get("name")
a.get("lname", "Not available")
# wring (add/update) to dict
a['lname'] = 'doe'
del a['lname']
Methods
dictionary.values()
get all the valuesdictionary.keys()
get all the keysdictionary.items()
get all pairs outputs i.e a list of tuples[(name, john), (lname, doe)]
Shallow copy
a = {"name": "jobn"}
a2 = a # values changed for a will also change for a2
a['name'] = 'jack'
print(a2) # will print `jack`
To allowcate a different memory and bypass shallow copy
a = {"name": "jobn"}
a2 = a.copy();
a['name'] = 'jack'
print(a2) # name will by john
Iterations
for keys in dict.keys()
iterate of the keysfor keys in dict.values()
iterate over the values.for key,value in dict.items()
iterate over both key and value
Dictionary comprehensions
# {key: value, for loop or functions, and finally condition}
squares = {x: x**2 for x in range(5)}
# with a condition
squares = {x: x**2 for x in range(10) if x % 2 == 0}
Merge Dictionaries
a = {'name': 'Ram'}
b = {'age': 'Shyam'}
c = {**a, **b}
print(c)
Functions
def function_name(parameters = 'default parameter'):
"""Documentations string for function"""
# Your code goes here
return value
Accept Multiple x
number of arguments
def new_function_name(*parameters):
"""Documentations string for function"""
# Your code goes here
return value
new_function_name(1,2,3,4,5)
Non positional named parameters
def new_function_name(**kwargs):
"""Documentations string for function"""
# Here kwargs is a key value paired dictionary.
return value
new_function_name(name='John', age = 20)
Function can accept both kwargs
and param collection
def new_function_name(**kwargs, *a):
"""The function will auto detect and assign variable 1,2,3,4 will be
assigned to *a while name='john' will be assigned to ***kwargs"""
new_function_name(1, 2, 3, 4, name='John', age = 20)
Lambda function (Anonymous function)
def add(a,b)
return a + b
# Can be converted to
add = lambda a , b : a + b
Power of lambda
numbers = [1,2,3,4,5,6]
square = list(map(lambda x:x**2, numbers)) # first parameter in map is function second is iterables.
Map function
This function applies a given function to all the items in an input.
def square (a)
return a**2
number = [1,2,3,4,5]
converted = list(map(square,numbers))
Lambda function with Map
number = [1,2,3,4,5]
list(map(lambda x: x**2,numbers))
Map multiple iterations
number1 = [1,2,3,4,5]
number2 = [6,7,8,9,10]
added_numbers = list(map(lambda x,y:x+y,numbers1,numbers2))
Type cast withing a map
integerList = [1,2,3,4,5]
stringList = list(map(str, interList))
lst = ['apple','ball']
upper = list(map(str.upper, lst))
Filter Function
To filter out a item from a list based on the condition
numbers = [1,2,3,4,5,6]
even = list(filter(lambda x: x%2==0, numbers))
print(even)