Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You do not
need to compile your program before executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.
Python is an open-source and cross-platform programming language. It is available for use
under Python Software Foundation License (compatible to GNU General Public License)
on all the major operating system platforms Linux, Windows and Mac OS.
Python Program to Print Hello World
# Python code to print "Hello World"
print ("Hello World")
Output
Hello World
Page 1 of 26
Example of Python Arithmetic Operators
a = 15
b=4
# Addition
print("Addition:", a + b)
# Subtraction
print("Subtraction:", a - b)
# Multiplication
print("Multiplication:", a * b)
# Division
print("Division:", a / b)
# Floor Division
print("Floor Division:", a // b)
# Modulus
print("Modulus:", a % b)
# Exponentiation
print("Exponentiation:", a ** b)
Page 2 of 26
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Example of Comparison Operators in Python
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Page 3 of 26
Example of Logical Operators in Python:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Output
False
True
False
Example of Bitwise Operators in Python:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
Page 4 of 26
14
2
40
Example of Assignment Operators in Python:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Example of Identity Operators in Python:
a = 10
b = 20
Page 5 of 26
c=a
print(a is not b)
print(a is c)
Output
True
True
Examples of Membership Operators in Python:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
Page 6 of 26
y is present in given list
Examples of Ternary Operator in Python:
a, b = 10, 20
min = a if a < b else b
print(min)
Output
10
Code to implement Comparison operations on integers
num1 = 30
num2 = 35
if num1 > num2:
print("The first number is greater.")
elif num1 < num2:
print("The second number is greater.")
else:
print("The numbers are equal.")
Output
The second number is greater.
Example:
age = 20
Page 7 of 26
if age >= 18:
print("Eligible to vote.")
Output
Eligible to vote.
Example:
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output
Travel for free.
Example:
marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")
Output
Result: Pass
Page 8 of 26
Example:
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Page 9 of 26
Output
30% senior discount!
Example:
number = 2
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
Output:
Two or Three
Page 10 of 26
Example:
Age=int(input(“Enter Age:
“)) If ( age>=18):
Print(“You are eligible for vote”)
If(age<0):
Print(“You entered Negative Number”)
Example
N=int(input(“Enter Number: “))
if(n%2==0):
print(N,“ is Even Number”)
Else:
print(N,“ is Odd Number”)
Example:
num=int(input(“Enter
Number: “)) If ( num<=0):
if ( num<0):
Print(“You entered Negative number”)
else:
Print(“You entered Zero ”)
else:
Print(“You entered Positive number”)
Page 11 of 26
Example
Program: find largest number out of given three numbers
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
z=int(input("Enter Third Number: "))
if(x>y and x>z):
largest=x
elif(y>x and
y>z):
largest=y
elif(z>x and
z>y):
largest=z
print("Larest Value in %d, %d and %d is: %d"%(x,y,z,largest))
Example
Program: calculate simple interest
Formula: principle x (rate/100) x time
p=float(input("Enter principle amount: "))
r=float(input("Enter rate of interest: "))
t=int(input("Enter time in months: ")) si=p*r*t/100
print("Simple Interest=",si)
Page 12 of 26
Example:
n=4
for i in range(0, n):
print(i)
Output
0
1
2
3
Example
li = ["geeks", "for", "geeks"]
for i in li:
print(i)
tup = ("geeks", "for", "geeks")
for i in tup:
print(i)
s = "Geeks"
for i in s:
print(i)
Page 13 of 26
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
Output
geeks
for
geeks
geeks
for
geeks
G
e
e
k
s
x 123
y 354
1
2
3
4
Page 14 of 26
5
6
Example
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
print(li[index])
Output
geeks
for
geeks
Example
li = ["geeks", "for", "geeks"]
for index in range(len(li)):
print(li[index])
else:
print("Inside Else Block")
Output
geeks
for
Page 15 of 26
geeks
Inside Else Block
Example
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Example
fruits = ["apple", "orange", "kiwi"]
iter_obj = iter(fruits)
while True:
try:
fruit = next(iter_obj)
print(fruit)
except StopIteration:
break
Output
apple
Page 16 of 26
orange
kiwi
Python Functions
Python Functions is a block of statements that does a specific task. The idea is to put some
commonly or repeatedly done task together and make a function so that instead of writing
the same code again and again for different inputs, we can do the function calls to reuse
code contained in it over and over again.
Example
def evenOdd(x: int) ->str:
if (x % 2 == 0):
return "Even"
else:
return "Odd"
print(evenOdd(16))
print(evenOdd(7))
Output
Even
Odd
Page 17 of 26
Example
def swap(x, y):
temp = x
x=y
y = temp
x=2
y=3
swap(x, y)
print(x)
print(y)
Output
2
3
Page 18 of 26
Python String
A string is a sequence of characters. Python treats anything inside quotes
as a string. This includes letters, numbers, and symbols. Python has no
character data type so single character is a string of length 1.
Example
s = "GfG"
print(s[1]) # access 2nd char
s1 = s + s[0] # update
print(s1) # print
Output
f
GfGG
Example
s = "GeeksforGeeks"
# Retrieves characters from index 1 to 3: 'eek'
print(s[1:4])
# Retrieves characters from beginning to index 2: 'Gee'
print(s[:3])
# Retrieves characters from index 3 to the end: 'ksforGeeks'
print(s[3:])
Page 19 of 26
# Reverse a string
print(s[::-1])
Output
eek
Gee
ksforGeeks
skeeGrofskeeG
Example
Page 20 of 26
Python Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of
data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and
usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output
3
Page 21 of 26
Python Tuples
Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities
and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a
defined order, and that order will not change.
Unchangeable
Page 22 of 26
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
Page 23 of 26
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Tuple, and Dictionary, all with different
qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate
values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and
cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items
after the set has been created.
Page 24 of 26
Example
True and 1 is considered the same value:
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset)
Example
Get the number of items in a set:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
Page 25 of 26
Python Dictionaries
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not
allow duplicates.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are ordered, changeable, and do not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"]
Page 26 of 26