1.
Flow controls
# python program to illustrate If else statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
While Loop
m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")
Output
0 1 2 3 4 End
Calling a Function in Python
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
greet() # call the function
print('Outside function')
Output
Hello World!
Outside function
String Manupulation
string_1 = "Hello"
string_2 = " World!"
print(string_1 + string_2)
string = 'Recursion...' * 5
print(string)
string = "I think I'm stuck in a " + "loop... " * 5
print(string)
print(len("It's been 84 years..."))
text = "Writing Python is quite fun."
print(text.find("quite"))
text = "The flower that blooms in adversity is the most rare and beautiful of all –
Mulan."
text_count = text.count('i')
print("The count of 'i' is", text_count)
text = "Hello, World!"
print(text[6:12])
text = ' a short break '
text.strip()
text.rstrip()
text.lstrip()
text = "When life gets you down you know what you've gotta do? Just keep swimming!
– Finding Nemo"
print(text.upper()) # Uppercases all characters
print(text.lower()) # Lowercases all characters
print(text.title()) # Title-case
print(text.capitalize()) # Capitalizes the first character
print(text.swapcase()) # Swaps whatever case for each character
Output
Hello World!
Recursion...Recursion...Recursion...Recursion...Recursion...
I think I'm stuck in a loop... loop... loop... loop... loop...
21
18
The count of 'i' is 4
World
'a short break'
' a short break'
'a short break '
WHEN LIFE GETS YOU DOWN YOU KNOW WHAT YOU'VE GOTTA DO? JUST
KEEP SWIMMING! – FINDING NEMO
when life gets you down you know what you've gotta do? just keep swimming! –
finding nemo
When Life Gets You Down You Know What You'Ve Gotta Do? Just Keep Swimming! –
Finding Nemo
When life gets you down you know what you've gotta do? just keep swimming! –
finding nemo
wHEN LIFE GETS YOU DOWN YOU KNOW WHAT YOU'VE GOTTA DO? jUST
KEEP SWIMMING! – fINDING nEMO
2. Tuples and Lists
# Creating a List with
# the use of Numbers
# (Having duplicate values)
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("\nList with the use of Numbers: ")
print(List)
# Creating a List with
# mixed type of values
# (Having numbers and strings)
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
print("\nList with the use of Mixed Values: ")
print(List)
print(List[0])
print(List[2])
# input the list as string
string = input("Enter elements (Space-Separated): ")
# split the strings and store it to a list
lst = string.split()
print('The list is:', lst) # printing the list
List = [1,2,3,4]
print("Initial List: ")
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
List.remove(2)
mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']
mylist.reverse()
print(mylist)
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
List with the use of Mixed Values:
[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
Geeks
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['Geeks', 1, 2, 3, 12, 4]
['Geeks', 1, 3, 12, 4]
['Python', 'Geek', 5, 4, 3, 2, 1]
Tuples
# Different types of tuples
# Empty tuple
my_tuple = ()
print(my_tuple)
# Tuple having integers
my_tuple = (1, 2, 3)
print(my_tuple)
# tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
Output
()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))
3. Operation on sets
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday
"}
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
Months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
print("\nlooping through the set elements ... ")
for i in Months:
print(i)
Output:
{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}
<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
printing the original set ...
{'February', 'May', 'April', 'March', 'June', 'January'}
Adding other months to the set...
Printing the modified set...
{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}
looping through the set elements ...
February
July
May
April
March
August
June
January
4. Operations on Dictionary
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"^TCS"}
print(type(Employee))
print("printing Employee data ....... ")
print(Employee)
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data ....... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])
Output
<class 'dict'>
printing Employee data ....
{'Name': 'Johnny', 'Age': 32, 'salary': 26000, 'Company': TCS}
ee["Company"])
<class 'dict'>
printing Employee data ....
Name : Dev
Age : 20
Salary : 45000
Company : WIPRO
5. Constructors
Simple OOP– Constructors – create a class for representing a car
class Car:
# class attribute
wheels = 4
# initializer / instance attributes
def init (self, color, style):
self.color = color
self.style = style
# method 1
def showDescription(self):
print("This car is a", self.color, self.style)
# method 2
def changeColor(self, color):
self.color = color
c = Car('Black', 'Sedan')
# call method 1
c.showDescription()
# Prints This car is a Black Sedan
# call method 2 and set color
c.changeColor('White')
c.showDescription()
# Prints This car is a White Sedan
Output
This car is a Black Sedan
This car is a White Sedan
6. Method Overloading
By Using Multiple Dispatch Decorator
Multiple Dispatch Decorator Can be installed by:
pip3 install multipledispatch
from multipledispatch import dispatch
# passing one parameter
@dispatch(int, int)
def product(first, second):
result = first*second
print(result)
# passing two parameters
@dispatch(int, int, int)
def product(first, second, third):
result = first * second * third
print(result)
# you can also pass data type of any value as per requirement
@dispatch(float, float, float)
def product(first, second, third):
result = first * second * third
print(result)
# calling product method with 2 arguments
product(2, 3) # this will give output of 6
# calling product method with 3 arguments but all int
product(2, 3, 2) # this will give output of 12
# calling product method with 3 arguments but all float
product(2.2, 3.4, 2.3) # this will give output of 17.985999999999997
Output:
6
12
17.985999999999997
7. Files – Reading and Writing
# Program to show various ways to read and
# write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
8. Regular Expressions
A Regular Expressions (RegEx) is a special sequence of characters that uses a search
pattern to find a string or set of strings.
import re
s = 'GeeksforGeeks: A computer science portal for geeks'
match = re.search(r'portal', s)
print('Start Index:', match.start())
print('End Index:', match.end())
string = "The quick brown fox jumps over the lazy dog."
pattern = r"brown.fox"
match = re.search(pattern, string)
if match:
print("Match found!")
else:
print("Match not found.")
Output
Start Index: 34
End Index: 40
Match found!
9. Modules
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print(math.sqrt(25))
# using pi function contained in math module
print(math.pi)
# 2 radians = 114.59 degrees
print(math.degrees(2))
# 60 degrees = 1.04 radians
print(math.radians(60))
# Sine of 2 radians
print(math.sin(2))
# Cosine of 0.5 radians
print(math.cos(0.5))
# Tangent of 0.23 radians
print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random
# printing random integer between 0 and 5
print(random.randint(0, 5))
# print random floating point number between 0 and 1
print(random.random())
# random number between 0 and 100
print(random.random() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print(random.choice(List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print(time.time())
# Converts a number of seconds to a date object
print(date.fromtimestamp(454554))
Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
10. Packages
Create a folder named mypckg.
Inside this folder create an empty Python file i.e. init .py
Then create two modules mod1 and mod2 in this folder.
Mod1.py
def gfg():
print("Welcome to GFG")
Mod2.py
def sum(a, b):
return a+b
init .py
from .mod1 import gfg
from .mod2 import sum
main.py
from mypckg import mod1
from mypckg import mod2
mod1.gfg()
res = mod2.sum(1, 2)
print(res)
Output:
Welcome to GFG
3
11. Exception Handling
# Program to handle multiple errors with one
# except statement
# Python 3
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for
# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
Output
ZeroDivisionError Occurred and Handled
If you comment on the line fun(3), the output will be
NameError Occurred and Handled