01 - Start Python
01 - Start 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("729")
729
Notice that when we inclose the content inside the parenthesis within inverted commas, it shall
act as a String Data Type.
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!
When I wanted to use single qoutes as a content, I used double qoutes as String Generator! Vice
Versa can be done as well.
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".
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('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
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!
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
2.0
x %= 2 #Remainder
print(x)
0.0
x = True
print(x)
True
y = False
print(y)
False
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
else Statement
else Statement is used when condition of if statement is False.
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!
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 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.
If you want to reverse the evaluation from True to False and False to True, then use Logical NOT.
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
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
i = 0
while True:
i += 1
if i==2:
continue
if i==5:
break
print(i)
1
3
4
"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.
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)
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)
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.
~ 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)
sum(first_num,second_num,third_num)
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')
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
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))
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
introduction = {'Name':'Ahmed',
'Age':16,
'Gender':'Male'}
print(introduction)
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)
words = ('eggs','bread','curd')
print(words)
Tuples are used instead of Lists where we want the data to be protected!
x = 1,[1,2,3],(3,'Yes')
print(x)
alphanumerics = {'a',1,'b',2,10,4,5}
alphanumerics
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
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.
[0, 3, 6, 9, 15]
Variable Scope
A variable created inside a function is available inside that function and has limited Scope.
def myfunc():
jets = 300
print(jets)
myfunc()
300
A variable created outside of a function is global and enjoys Global Scope.
def myfunc():
print(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.
import random
17
0.6394267984578837
26.067389566073444
import math
5.0
3.141592653589793
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))
dir() is used to find out what methods are available to be applied on the data stored in a Variable.
Want to know what the use of a method is, you may use help()
print(help(set.difference))
Help on method_descriptor:
(i.e. all elements that are in this set but not the others.)
None
print(help(str.capitalize))
Help on method_descriptor:
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.