Python Programming
Python Programming
Python Programming
Beginners
Python print()
Python print() is used to print the output on the
screen.
print("hello world")
print("Nishant Tiwari")
Add, sub, multiply, and divide two number together and print the
output
Python Comments
Python Comments are used to explain your python
code and make your code more readable.
'''
example of muti-line comment
print(20+20)
'''
#or
"""
Python Variables
Variables are the space or a location used to
store data in memory
a = 10 #here a is a variable
print(a) #output: 10
Now let us take three variable and print the values of each
a = 30
b = 40
c = 50
#print in a single line
print(a,b,c) #output: 30 40 50
print(a) #output: 30
print(b) #output: 40
print(c) #output: 50
a = b = c = 10
print(a,b,c) #output: 10 10 10
a = "hello"
A = "world"
_ = "dx4iot here"
print(a) #output: hello
print(A) #output: world
print(_) #output: dx4iot here
% = "hello"
1 = "hello"
print(%) #output: Error
print(1) #output: Error
#snake_case
snake_case = "hello" #output: hello
#camelCase
camelCase = "world" #output: world
Numbers
There are three types of data type under numbers
a = 10 #int (integer)
print(type(a)) #output: <class 'int'>
b = 10.5 #float
print(type(b)) #output: <class 'float'>
d = [10,10.5,20]
print(d) #output: [10, 10.5, 20]
print(type(d)) #output: <class 'list'>
d = [10,10.5,20]
print(d[0]) #output: 10
print(d[1]) #output: 10.5
fruit = ["apple","mango","grapes"]
fruit.insert(0,"banana")
print(fruit) #output: ['banana', 'apple', 'mango', 'grapes']
Tuple
Tuple is the same as list it is also used to store multiple
elements of different data types but the difference is tuple
is immutable.
months = ("jan","feb","march")
print(months[0]) #output: jan
months = ("jan","feb","march")
months.insert(0,"april") #ERROR
String
String is a sequence of characters that are immutable
Example of a string
a = "hello world"
e = """nishant
tiwari
age: 19
"""
Set
Example of a set
f = {1,5,6,9,2,4,4}
print(f) #output: {1, 2, 4, 5, 6, 9}
print(type(f)) #output: <class 'set'>
Dictionary
Dictionary is a collection of key-value pairs
#dictionary : key/value
name = {1:"nishant",2:"kartik"}
print(type(name)) #output: <class 'dict'>
print(name[1]) #output: nishant
a = 100 #int
b = "40" #str
c = int(b) #convert to int
d = a + c #int + int = int
print(type(d)) #output: <class 'int'>
Python Input()
Input() statement is used to take input from
the user
Example of a Input()
Python Operator
Operators are used to perform operations (eg:
addition, compare two value, assign a value,
etc)
#Addition
print(a+b) #output: 5
#Subtraction
print(a-b) #output: 1
#Multiplication
print(a*b) #output: 6
#Division
print(a/b) #output: 1.5
#Exponent: power
print(a**b) #output: 9
#x is greater than y
print(x > y) #output: false
#x is less than y
print(x < y) #output: true
#x is equal to y
print(x == y) #output: false
#x is not equal to y
print(x != y) #output: true
a = 5
print(a) #output: 5
a = a - 5
print(a) #output: 5
a = 5
a -= 2
print(a) #output: 8
#print the value from 0 to 4, and when the loop end, it prints hello world
for x in range(5):
print(x)
print("hello world")
#output:
'''
0
1
2
3
4
hello world
'''
#print the value from 5 to 10, and when the loop end, it prints hello world
for x in range(5,21):
print(x)
print("hello world")
#output:
'''
5
6
w
o
r
l
d
hello world
'''
a = 1
#loop runs until the value of a is not greater than 9
while a < 10:
print(a) #print the value of a each time until loop end
a = a + 1 #adding the current value of a with 1
print("hello world") #when the loop end then (hello world) prints
#output:
'''
1
2
3
4
5
6
#python break
a = "hello"
for x in a:
#python continue
a = "hello"
for x in a:
if x == "l":
continue
print(x)
print("hello world")
#output:
'''
h
e
o
hello world
'''
Python Numbers
There are three types of data type under numbers
1) Integer (int) : integer values such as (-1,0,1,2)
Example of integer
a = 5 #int (integer)
print(type(a)) #output: <class 'int'>
Example of float
b = 5.5 #float
print(type(b)) #output: <class 'float'>
Example of complex
max() method
max() method return the highest value
Example of max() method
If we have three numbers then the min() method return the
lowest number
min() method
min() method return the lowest value
Example of max() method
print(min(80,80,100)) #output: 80
print(min(30,40,50)) #output: 30
print(min(-1,-2,-3)) #output: -30
Python List
List is used to store multiple elements of
different data types. List is an ordered
sequence of mutable elements.
a_list = []
print(a_list) #output: []
a_int = [1,2,3,4,5]
print(a_int) #output: [1,2,3,4,5]
a_float = [1.0,2.2,3.4,3.5]
print(a_float) #output: [1.0,2.2,3.4,3.5]
a_mix = [1,1.0,"apple"]
print(a_mix) #output: [1,1.0,"apple"]
a_mix = [1,1.0,"apple"]
print(a_mix[0]) #output:1
print(a_mix[1]) #output: 1.0
print(a_mix[2]) #output: apple
Nested list
A nested list means list within a list
Example of Nested list
nest_list = ["hello",[1,2,3]]
#print the 1 of 0 element
print(nest_list[1][0]) #output: 1
#print the 1 of 1 element
print(nest_list[1][1]) #output: 2
#print the 1 of 2 element
print(nest_list[1][2]) #output: 3
Negative Indexing
Negative Indexing means index starts from the end
Example of Negative Indexing
#negative indexing
a = [1,2,3,4,5]
#print the last element of the list
print(a[-1]) #output: 5
append()
append() is used to add the elements to the end of the list
Example of append()
fruit = ["apple","mango","grapes"]
print(fruit) #output: ["apple","mango","grapes"]
#append "banana" to the end of the list
fruit.append("banana")
print(fruit) #output: ["apple","mango","grapes","banana"]
extend()
extend() is used to merge two list
Example of extend()
lang = ["English","Hindi"]
lang1 = ["French","German"]
#add elements of lang1 to the end of lang list
lang.extend(lang1)
print(lang) #output: ['English', 'Hindi', 'French', 'German']
index()
insert()
insert() is used to insert an element at a specified position
Example of insert()
lang = ["English","Hindi","French"]
#inserting "German" on 2 position
lang.insert(2,"German")
print(lang) #output: ['English', 'Hindi', 'German', 'French']
count()
Example of count()
list_int = [1,2,3,1,2,1,1,5]
#print the total occurrence of 1 in a list
print(list_int.count(1)) #output: 4
remove()
remove() is used to remove an element according to their
element name
Example of remove()
lang = ["English","Hindi","French"]
#remove "French" from above list
lang.remove("French")
print(lang) #output: ["English","Hindi"]
lang = ["English","Hindi","French"]
#remove "Hindi" from above list
lang.pop(1)
print(lang) #output: ['English','French']
reverse()
reverse() is used to reverse the element of a list
lang = ["English","Hindi","French"]
#reverse the element
lang.reverse()
print(lang) #output: ['French', 'Hindi', 'English']
sort()
sort() is used to sort the elements of a list in ascending
order (by default)
Example of sort()
list_int = [1,5,4,7,8,3,2,1]
#sort in ascending order
list_int.sort()
print(list_int) #output: [1, 1, 2, 3, 4, 5, 7, 8]
Python Tuple
Tuple is the same as list it is also used to
store multiple items of different data types
but the difference is tuple is immutable.
e_tuple = ()
print(e_tuple) #output: ()
months = ("jan","feb","march")
print(months) #output: ("jan","feb","march")
months = ("jan","feb","march")
print(months[0]) #output: jan
print(months[1]) #output: feb
print(months[2]) #output: march
Nested Tuple
Nested Tuple is same as Nested List
Negative Indexing
Negative Indexing means index starts from the end
Example of Negative Indexing
e_tuple = (1,2,3)
#print the last element of the tuple
print(e_tuple[-1])
#print the second last element of the tuple
print(e_tuple[-2])
Python Set
Set is used to store unique elements (set
automatically removes duplicate elements)
my_set = {}
print(my_set) #output: {}
my_set = {1,2,9,6,8}
print(my_set) #output: {1, 2, 6, 8, 9}
a = {"a","b","c"}
print(a[0]) #Error: not support indexing
my_set = {1,2,9,6,8}
my_set.add(3)
print(my_set) #output: {1, 2, 3, 6, 8, 9}
my_set = {1,2,9,6,8}
my_set.update([10,11,12])
print(my_set) #output: {1, 2, 6, 8, 9, 10, 11, 12}
my_set = {1,2,9,6,8}
my_set.remove(2)
print(my_set) #output: {1, 6, 8, 9}
Set Operation
The set operations are performed on two or more sets to
obtain a combination of elements
a = {0,1,2,3,4}
b = {0,2,4,9,8,7}
print(a&b) #output: {0, 2, 4}
Python Dictionary
Dictionary is a collection of key-value pairs
my_dict = {"fruit":"apple","veg":"carrot"}
print(my_dict) #output: {'fruit': 'apple', 'veg': 'carrot'}
my_dict = {"fruit":"apple","veg":"carrot"}
print(my_dict["fruit"]) #output: apple
print(my_dict["veg"]) #output: carrot
my_dict = {"fruit":"apple","veg":"carrot"}
#with the help of keys()
print(my_dict.keys()) #output: dict_keys(['fruit', 'veg'])
my_new = {"fruit":["apple","mango","grapes"],"veg":["carrot","potato","tomato"]}
print(my_new)
#output: {'fruit': ['apple', 'mango', 'grapes'], 'veg': ['carrot', 'potato', 'tomato']}
my_new = {"fruit":["apple","mango","grapes"],"veg":["carrot","potato","tomato"]}
print(my_new["fruit"][0]) #output: apple
print(my_new["fruit"][1]) #output: mango
print(my_new["fruit"][2]) #output: grapes
Python Function
Function are the block of code and it only runs
when it called
def hello():
print("my name is nishant")
#output: no output because function is not called
calling a function
def hello():
print("my name is nishant")
hello() #function called
#output: my name is nishant
def hello(f,l):
print(f,l)
fname = "Nishant"
lname = "Tiwari"
#passing fname and lname as a parameter to a function
hello(fname,lname)
#output: Nishant Tiwari
def hello():
print("hello world")
hello()
x = 10 #old value: 10
def hello():
#use of global variable inside a function
global x
print(x)
#reassign a value to x
x = 20 #new value: 20
hello() #first print the old value
print(x) # then the new value
#output:
'''
10
20
'''
def hello():
x = "hello" #local variable
print(x)
hello() #output is hello
print(x) #error because local variable are use within there scopes
#output:
'''
hello
'x' is not defined
'''
#using lambda
add = lambda x,y:x+y #return x+y
print(add(2,55)) #output: 57
#using function
def add(a,b):
return a+b
print(add(5,6)) #output: 57
With the help of the open() method, you can open any file
in python
f = open("hello.txt")
#hello.txt
'''
hello world
'''
f = open("hello.txt","r") #"r" : Opens a file for reading
print(f.read()) #Output: hello world
f.close() #closes the opened file
#If try condition is true then only else condition will run
try:
print("hello")
except:
print("hello world")
else:
print("hello")
#output:
'''
hello
hello
'''
#If try condition is false then only except codition will run
try:
print(x) #x is not define
except:
print("hello world")
else:
print("hello")
#output: hello world
Raise an exception
raise keyword is used to throw an exception for a
condition if a condition occurs
#raise an exception
x = 5
if x < 11:
raise Exception("Sorry, no number below 11")
output:
'''
Exception: Sorry, no number below 11
'''