Initiate Python
Defination
Python is a Hybrid High Level Programming Language with easy syntax and dynamic sementics.
Output
print() command is the easiest way to output a specified message on Screen.
print(60)
60
print(729)
729
print(65.10)
65.1
The above data types inside the parenthesis are Numeric in nature. They are Integers and Floats
in principle.
print("Coding is your New Superpower")
Coding is your New Superpower
print("729")
729
Notice that when we inclose the content inside the parenthesis within inverted commas, it shall
act as a String Data Type.
Numeric Data Types
All Arthmatic Operations can be performed on Numeric Data Types.
print(1+72)
73
print(23-12)
11
print(17*2)
34
print(8/2)
4.0
Did you notice that division has caused the output to be a Float even when the Input were both
Integers.
print(23.0+7)
30.0
print(20.0-5)
15.0
print(2*3.0)
6.0
Even if one of the Numeric value in the system is a float, the output shall be a float only!
String Data Type
Single or Double Inverted Commas can be used and both shall help convert the dtype inside the
parenthesis into a String.
print("Well it's your Fault")
Well it's your Fault
print('He said to me,"Why are you acting like this?"')
He said to me,"Why are you acting like this?"
When I wanted to use single qoutes as a content, I used double qoutes as String Generator! Vice
Versa can be done as well.
Two Strings can be Concatenated!
print('Water'+"Park")
WaterPark
print("United"+"States")
UnitedStates
Mixing Strings, Integers and Floats
Now we know that a whole number is "Integer" Data Type, a Number with Decimal Point is a
"Float" Data Type and a piece of content within inverted commas is a "String".
We may use multiple print command multiple times.
print("Name:"+" Mary")
print("Surname:"+" Jane")
Name: Mary
Surname: Jane
A Line of code is called Statement. There is no limit to Statement Counts in a Program Code.
Statements are executed line by line.
Concatenation is only used for Strings. Comma can be used as a seperator when printing
multiple data types.
print('I need',700,'Dollars immediately as I need to
give',205.5,'Dollars in Credit Card Payments.')
I need 700 Dollars immediately as I need to give 205.5 Dollars in
Credit Card Payments.
We may even customize the Seperator.
print('Iron','Man',sep='-')
Iron-Man
Variables
Variables are containers for storing data values!
x = 2
y = "Good"
z = 3.5
print('x+z:',x+z)
print('x*y:',x*y)
print('z-x',z-x)
x+z: 5.5
x*y: GoodGood
z-x 1.5
Rules of Variable making:
1. Only Use alphabets, numbers and underscore.
2. Numbers not allowed in beginning
3. Python Keywords can not be used as variable names.
Taking User Input
We may require user input in our program. For example we may need to ask the user his age and
assign a variable to that Memory Address.
age = input("Please Enter Your Age here: >>>>")
print('You are',age,'Years old')
Please Enter Your Age here: >>>>23
You are 23 Years old
Whatever the user inputs is considered to be a String, if you need to convert it into another data
type like Integers or Floats. We can do so!
age = int(input("Please enter your age here: >>>>"))
age = age + 2
print("You will be",age,"Years old after 2 Years.")
Please enter your age here: >>>>8
You will be 10 Years old after 2 Years.
height = float(input("Please enter your height in inches: >>>>"))
difference = 8 - height
print("You are",difference,"inches shorter than Undertaker.")
Please enter your height in inches: >>>>6
You are 2.0 inches shorter than Undertaker.
Similarly, a Numeric Data Type can also be converted into a String Data Type.
x = 5
y = 9
a = str(x)
b = str(y)
print(a+b)
59
In-Place Operators
In-Place Operators lets you write Code in a more efficient manner!
x = 2
x += 5 # x = x + 5
print(x)
7
x -= 4
print(x)
x *= 2
print(x)
x /= 3
print(x)
2.0
x **= 3 #Exponent
print(x)
8.0
x //= 3 #Floor Qoutient
print(x)
2.0
x %= 2 #Remainder
print(x)
0.0
Booleans Data Type
Another Data Type other than Strings, Integers and Floats. Another Data Type is Boolean which
is simply True and False. This is not a String Data Type and thus does not require qoutes.
x = True
print(x)
True
y = False
print(y)
False
Booleans can be converted into Strings, Integers and Floats!
a = str(x)
a
'True'
b = int(x)
b
c = float(y)
c
0.0
Comparision Operators
Booleans generally result due to Comparision Operators.
a = 10
b = 5
print(a==b)
print(a>b)
print(a>=b)
print(a<b)
print(a<=b)
print(a!=b)
False
True
True
False
False
True
We may store the value of Boolean resulting due to Comparision in a Variable and convert the
dtype of that variable to another data type.
f = int(a>b)
print(f)
g = float(a!=b)
print(g)
1.0
print(f+g)
2.0
if Statement
Whatever we have learnt uptill now can be used to build logic and run certain lines of code if
other statement results in Boolean True. The Structure of the Code shall be as follows:
if True:
Statement
x = 42
if x>5:
print('Great')
Great
y = 30
if y%2==0:
print('Even Number')
Even Number
s = 5
t = 7
if s>t:
print(s,'is greater than',t)
if s<t:
print(s,'is less than',t)
5 is less than 7
x = 'a'
if x<'c':
x+='b'
if x>'z':
x+='c'
print(x)
ab
num = int(input('Enter a Number between 0 and 10: >>>>'))
if num>0:
print("Greater than 0")
if num<10:
print("Less than 10")
if num==10:
print("Its 10")
Enter a Number between 0 and 10: >>>>9
Greater than 0
Less than 10
else Statement
else Statement is used when condition of if statement is False.
num = int(input('Enter a Positive Number: >>>>'))
if num>0:
print('You have entered a Positive Number indeed!')
else:
print('You have either entered 0 or Negative Number.')
Enter a Positive Number: >>>>5
You have entered a Positive Number indeed!
elif Statement
Using if and else can only give you two conditions! Using elif between if and else can increase the
evaluation conditions to infinitly more!
num = int(input('Enter a Number: >>>>'))
if num > 0:
print('You have entered a Positive Number')
elif num == 0:
print('You have entered 0')
else:
print('You have entered a Negative Number')
Enter a Number: >>>>2
You have entered a Positive Number
x = int(input('Enter 1st Number: >>>>'))
y = int(input('Enter 2nd Number: >>>>'))
if x>y:
print(x-y)
elif x<y:
print(y-x)
else:
print('Both are Equal')
Enter 1st Number: >>>>2
Enter 2nd Number: >>>>4
2
Logical Operators
If we want to evaluate Multiple Conditions and execute the Indented Code only when all the
Conditions are evaluate to True than we use Logical AND.
x = 10
if x>5 and x<20 and x!=30:
print('All Conditions are True')
else:
print('One or All of the conditions are False.')
All Conditions are True
country = 'US'
age = 40
if country=='USA' and age==40:
print('He is a 40 Year Old US Citizen.')
elif country!='USA' and age==40:
print('He is not a 40 Year Old UK Citizen.')
He is not a 40 Year Old UK Citizen.
If we want to evaluate Multiple Conditions and execute the Indented Code even if only one
Condition are evaluates to True than we use Logical OR.
continent_name = input('Enter Your Continent Name: >>>>')
age = int(input('Enter Your Age: >>>>'))
if (continent_name=='Asia' or continent_name=='Africa') and (age>18
and age<50):
print('You are Eligible for the Visa Program')
elif (continent_name=='Europe' or continent_name=='South America') and
(age>18 and age<50):
print("You don't need visa to Travel to US")
else:
print("You are not eligible for Visa Program.")
Enter Your Continent Name: >>>>Asia
Enter Your Age: >>>>23
You are Eligible for the Visa Program
If you want to reverse the evaluation from True to False and False to True, then use Logical NOT.
a = int(input('Enter Your Number: >>>>'))
if not (a>10):
print('Cool')
else:
print('Hot')
Enter Your Number: >>>>23
Hot
while Loop
Loop allows you to repeat a Block of Code multiple times! While loops are used till the condition
attached to it evaluates to True.
i = 5
while i<=10:
print('Wow')
i += 1
print('Finish')
Wow
Wow
Wow
Wow
Wow
Wow
Finish
i = 1
while i<=10:
if i%2==0:
print(i,'is even')
else:
print(i,'is odd')
i += 1
print('Program is Finished')
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
Program is Finished
break and continue in Loops
break Statement is used when you would like to prematurely end the loop!
i = 5
while i<=5:
print(i)
i -= 1
if i==2:
break
5
4
3
i = 0
while True:
print(i)
i += 1
if i==3:
break
0
1
2
continue Statement is used when you would like to go back to the first line in the Block of Code
in Iteration without executing the Code beneath the continue Statement.
i = 0
while i<5:
i += 1
if i==2:
continue
print(i)
1
3
4
5
We may even use break and continue in the same loop!
i = 0
while True:
i += 1
if i==2:
continue
if i==5:
break
print(i)
1
3
4
List Data Type
Time to introduce another build-in Data Type or Object in Python!
"Lists" are mutable data type that store different other data types inside of it. It is created using
Square Brackets!
alpha = ['a','b','c','d']
nums = [1,2,3,4]
lists = [alpha, nums, 23.05, True]
print(alpha)
print(nums)
print(lists)
['a', 'b', 'c', 'd']
[1, 2, 3, 4]
[['a', 'b', 'c', 'd'], [1, 2, 3, 4], 23.05, True]
Notice that above list stored in variable 'lists' contain 2 List Data Types inside of it.
Range Data Type
Amoung many data types in Python. Range is one of them. A Range simply is a Immutable
Sequence of Numbers!
If a range function has a single numeric argument than it means that range starts from 0 and
ends at number just before the numeric argument number!
x = range(5)
print(x)
range(0, 5)
A Range can be converted into a list for better use!
y = list(x)
print(y)
[0, 1, 2, 3, 4]
When range function has 2 numeric arguments seperated by a Comma, the first argument is the
starting point and second argument is end point which is excluded!
x = range(5,10)
x = list(x)
print(x)
[5, 6, 7, 8, 9]
When range function has 3 numeric arguments seperated by a Comma, the first argument is the
starting point and second argument is end point which is excluded! The third point is the step
size. By default, the step size is 1.
a = range(2,19,2)
a = list(a)
print(a)
[2, 4, 6, 8, 10, 12, 14, 16, 18]
for Loops
The for Loop is used to iterate over a sequence like list, range or string!
sentence = "London"
for character in sentence:
print(character)
L
o
n
d
o
n
numbers = [5,6,7]
for i in numbers:
print(i)
5
6
7
gig = range(2,13,3)
for i in gig:
print(i)
2
5
8
11
nums = [1,2,3,4]
res = 0
for i in nums:
if i%2==0:
continue
else:
res += 1
print(res)
Functions
The Build-in Python Function include the likes of:
~ print('Hello World') where print() is the function and 'Hello World' is the Argument.
~ str(12) where str() is the function and 12 is the Argument.
~ range(2,13,2) where range() is the function and 2,13,2 are the Arguments.
One can make his own function using the def statement!
def hello():
print('Hello')
hello()
Hello
def hello(name):
print('Hello',name)
hello('Kim')
hello('Jack')
hello('Abdullah')
Hello Kim
Hello Jack
Hello Abdullah
def add_two(y):
print(y+2)
add_two(5)
def sum(a,b,c):
print(a+b+c)
first_num = int(input('Enter 1st Number: >>>>'))
second_num = int(input('Enter 2nd Number: >>>>'))
third_num = int(input('Enter 3rd Number: >>>>'))
sum(first_num,second_num,third_num)
Enter 1st Number: >>>>1
Enter 2nd Number: >>>>2
Enter 3rd Number: >>>>3
6
def even_or_odd(number):
if number==0:
print('You entered 0 which is even')
elif number%2==1:
print(number,'is odd')
else:
print(number,'is even')
x = int(input('Enter a Number: >>>>'))
even_or_odd(x)
Enter a Number: >>>>23
23 is odd
Uptill now, we have been using the def statement to create a function that is giving output on
screen. But what is we just want to assign the result into a variable!
def square(x):
return x**2
sqaured_value = square(3)
sqaured_value
def max(x,y):
if x>y:
return x
if x<y:
return y
if x==y:
return x
if max(6,7) > 10:
print('Great')
else:
print('Small')
Small
Note that once we type return statement in the block of code under the def statement, the
function will return the value and any statement written beneath the return statement within
the block shall be ignored!
def subtract(x,y):
if x>=y:
return(x-y)
print('Hi')
else:
return(y-x)
print('Hello')
subtract(5,4)
def print_numbers():
print(1)
return
print(2)
print_numbers()
You might have noticed by now that a function can only return one value. We can return multiple
values using Lists!
def squared(x,y):
return [x**2,y**2]
a = squared(2,3)
print(a)
[4, 9]
def summation(x):
res = 0
for i in range(x):
res += i
return res
print(summation(4))
Comments & Docstrings
Comments and Docstrings are ignored by Interpretor! Comments are generally used to explain a
line of code while Docstrings are generally used at start of Code or Function to explain what it
does!
inode = 7 #assigning a variable to int 7
print(inode) #printing the variable
def multiply(x,y):
"""
Function Name: multiply
Arguments: takes 2 arguments, converts them into Int data type,
multiply them and return the resultant.
For example:
[input] print(multiply(2,3))
[output] 6
"""
x = int(x)
y = int(y)
return x*y
print(multiply(4,5))
20
Dictionary Data Type
The Immutable Data Types we have understood so far are Strings, Integers, Floats and Booleans
while List was Mutable i.e. we understood that it can be changed.
Meet another data type that is Mutable like lists.
introduction = {'Name':'Ahmed',
'Age':16,
'Gender':'Male'}
print(introduction)
{'Name': 'Ahmed', 'Age': 16, 'Gender': 'Male'}
Dictionary maps Keys to Values. In above example, 'Name','Age' and 'Gender' are keys while
'Ahmed', 16 and 'Male' are Values.
ages = {'Wasim':59,
'Waqar':57,
'Shoaib':52}
print(ages)
{'Wasim': 59, 'Waqar': 57, 'Shoaib': 52}
Note that only Immutable Data Types can be Keys!
Tuple Data Type
Tuples are just like Lists except that Tuples are Immutable unlike Lists!
words = ('eggs','bread','curd')
print(words)
('eggs', 'bread', 'curd')
Tuples can also be created with out the Paranthesis!
Tuples are used instead of Lists where we want the data to be protected!
x = 1,[1,2,3],(3,'Yes')
print(x)
(1, [1, 2, 3], (3, 'Yes'))
Set Data Type
Sets are mutable data type. They are like dictionaries since they use curly braces but without key
value pairs.
alphanumerics = {'a',1,'b',2,10,4,5}
alphanumerics
{1, 10, 2, 4, 5, 'a', 'b'}
Even if two same elements inside a set are deployed, the output shall result in only one.
ages = {11,12,13,11,14,13}
ages
{11, 12, 13, 14}
List Comprehensions
We have seen that List can be made manually or by converting a range into a list as we have seen
before. Another way to create a list is via List Comprehension.
Let us create a quick list that contain Multiples of 3 from 3 to 15 but not 12.
list_3_multiple = [i for i in range(0,16) if (i%3==0) and (i!=12)]
list_3_multiple
[0, 3, 6, 9, 15]
Let us create cubes of numbers from 6 to 10 but not the cube of 8.
list_cubes = [i**3 for i in range(6,11) if i!=8]
list_cubes
[216, 343, 729, 1000]
Variable Scope
A variable created inside a function is available inside that function and has limited Scope.
def myfunc():
jets = 300
print(jets)
myfunc()
#print(jets) <--- Executing this Line shall result in NameError as we
have defined variable within Local Scope of a Function.
300
A variable created outside of a function is global and enjoys Global Scope.
x = 300 # x defined as Global Scope Variable
def myfunc():
print(x)
myfunc() #Using the Global x
print(x) #Using the Global x
300
300
If you use the global keyword, the variable belongs to the global scope now.
def myfunc():
global x # Declare x as Global Variable inside the Function.
x = 300
myfunc()
print(x)
300
To change the value of a global variable inside a function, refer to the variable by using the
global keyword.
x = 300
print(x)
def myfunc():
global x
x = 200
print(x)
def myfunc2():
global x
x = 500
print(x)
myfunc()
myfunc2()
print(x)
300
200
500
500
Python Module
A Module is a Code that contains functions that can be called in when required.
Python Random Module
Some important functions in Random Module are as below:
import random
random.seed(42) #ensure that random number generated is always the
same
print(random.randrange(12,19)) #returns a random number from a range
17
random.seed(42) #ensure that random number generated is always the
same
print(random.random()) #returns a random float number between 0 and 1
0.6394267984578837
random.seed(42) #ensure that random number generated is always the
same
print(random.uniform(12,34)) #returns a random float number between
two given arguments
26.067389566073444
Python Math Module
The Math Module allows you to perform Mathematical tasks.
import math
print(math.sqrt(25)) #print the sqaure root of the Argument
5.0
print(math.pi) #print the value of pi
3.141592653589793
Data Type and Methods
It is impossible to navigate the sea of python via Human Memory. One must know the data type
and method that can be applied to it.
a = 'Hello'
b = 1
c = 15.5
d = True
e = ['Alpha',1,15.5,True]
f = range(1,15)
g = (1,5,7)
h = {'Name':'Abdullah','Age':21,'Profession':'Data Scientist'}
i = {1,1,2,3,4}
type() is used to find the Data Type of any data stored in a variable!
print('~',a,'is',type(a))
print('~',b,'is',type(b))
print('~',c,'is',type(c))
print('~',d,'is',type(d))
print('~',e,'is',type(e))
print('~',f,'is',type(f))
print('~',g,'is',type(g))
print('~',h,'is',type(h))
print('~',i,'is',type(i))
~ Hello is <class 'str'>
~ 1 is <class 'int'>
~ 15.5 is <class 'float'>
~ True is <class 'bool'>
~ ['Alpha', 1, 15.5, True] is <class 'list'>
~ range(1, 15) is <class 'range'>
~ (1, 5, 7) is <class 'tuple'>
~ {'Name': 'Abdullah', 'Age': 21, 'Profession': 'Data Scientist'} is
<class 'dict'>
~ {1, 2, 3, 4} is <class 'set'>
dir() is used to find out what methods are available to be applied on the data stored in a Variable.
print(dir(a)) #method applicable on a String
['__add__', '__class__', '__contains__', '__delattr__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__iter__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold',
'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii',
'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix',
'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(i)) #method applicable on a Set
['__and__', '__class__', '__class_getitem__', '__contains__',
'__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getstate__', '__gt__', '__hash__', '__iand__',
'__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__',
'__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__',
'__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__',
'__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__',
'__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear',
'copy', 'difference', 'difference_update', 'discard', 'intersection',
'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop',
'remove', 'symmetric_difference', 'symmetric_difference_update',
'union', 'update']
Want to know what the use of a method is, you may use help()
print(help(set.difference))
Help on method_descriptor:
difference(...) unbound builtins.set method
Return the difference of two or more sets as a new set.
(i.e. all elements that are in this set but not the others.)
None
print(help(str.capitalize))
Help on method_descriptor:
capitalize(self, /) unbound builtins.str method
Return a capitalized version of the string.
More specifically, make the first character have upper case and
the rest lower
case.
None
The number of characters in String or number of elements inside Collection Data Types can be
counted via len() function.
print(len(a),len(e),len(f),len(g),len(h),len(i)) #length of the data
type
5 4 14 3 3 4