7/21/2021 Revision_python
This is a revision document for python
Created by Prakshaal Jain
Course - Data Wrangling with Python
Date - 20-7-2021
In [1]:
#Print Statement
print("hello world")
hello world
What is a Variable
In [2]:
message = "Hello MBA"
i_am_a_variable = 10
In [3]:
print(message)
print(i_am_a_variable)
Hello MBA
10
Matematical Operations
In [4]:
#Mathematical Operations
first_num = 10
second_num = 20
sum_num = first_num+second_num
mult_num = first_num*second_num
divide_num = first_num/second_num
power_num = first_num**second_num
subtract_num = first_num-second_num
In [5]:
print("Sum = ",sum_num)
print("mult_num = ",mult_num)
print("divide_num = ",divide_num)
print("power_num = ",power_num)
print("subtract_num = ",subtract_num)
Sum = 30
mult_num = 200
divide_num = 0.5
power_num = 100000000000000000000
subtract_num = -10
String Operations
Lets do some operations in strings
In [6]:
localhost:8888/lab/tree/Revision_python.ipynb 1/11
7/21/2021 Revision_python
message = "prakshaal jain"
In [7]:
#Length of string
# Counts number of charaters including space
print(len(message))
14
In [8]:
print("Simple print ---->", message)
print("Title print ---->", [Link]()) ## Observe First word of each letter is cap
print("UPPER print ---->", [Link]()) ## Observe All Caps
print("lower print ---->", [Link]()) ## All chars are lower case
Simple print ----> prakshaal jain
Title print ----> Prakshaal Jain
UPPER print ----> PRAKSHAAL JAIN
lower print ----> prakshaal jain
In [9]:
# Printing with Tabs and in next line
print("With Tab seperation --->","prakshaal \t Jain")
print("With Next Line seperation --->","\n prakshaal \n Jain")
With Tab seperation ---> prakshaal Jain
With Next Line seperation --->
prakshaal
Jain
Strip! Strip! Left Right
In [10]:
## When to strip ??
strip_message = " This is Strip Message "
In [11]:
print("This is left stripped --->",strip_message.lstrip())
print("This is right stripped --->",strip_message.rstrip())
print("This is fully stripped --->",strip_message.strip())
This is left stripped ---> This is Strip Message
This is right stripped ---> This is Strip Message
This is fully stripped ---> This is Strip Message
Bring it on its LIST time
In [12]:
# its in [] <--- Square Bracket
my_list = ["prakshaal", "gaurav", "kriti", "praneel", "riva",10]
print("printing my list ---> ",my_list)
print("First element in list starts with 0 --->", my_list[0])
print("Second element in list starts is at index 1 and so on --->", my_list[1])
printing my list ---> ['prakshaal', 'gaurav', 'kriti', 'praneel', 'riva', 10]
First element in list starts with 0 ---> prakshaal
Second element in list starts is at index 1 and so on ---> gaurav
In [13]:
# Reverse indexing
print("Last element in list starts with -1 --->", my_list[-1])
localhost:8888/lab/tree/Revision_python.ipynb 2/11
7/21/2021 Revision_python
print("Last Second element in list starts is at index -2 and so on --->", my_list[-2])
Last element in list starts with -1 ---> 10
Last Second element in list starts is at index -2 and so on ---> riva
In [14]:
# Changing elements in list
my_list[-1] = "mona"
print(my_list)
['prakshaal', 'gaurav', 'kriti', 'praneel', 'riva', 'mona']
In [15]:
# Lets add stuff to the list
my_list.append("kamlesh")
print(my_list)
['prakshaal', 'gaurav', 'kriti', 'praneel', 'riva', 'mona', 'kamlesh']
In [16]:
# Inserting at a given index
my_list.insert(3,"neelam")
print(my_list)
['prakshaal', 'gaurav', 'kriti', 'neelam', 'praneel', 'riva', 'mona', 'kamlesh']
In [17]:
# Deleting Items from
del my_list[0]
print(my_list)
['gaurav', 'kriti', 'neelam', 'praneel', 'riva', 'mona', 'kamlesh']
In [18]:
#popping Names
popped_name = my_list.pop()
print('my list is ---> ',my_list)
print("popped name is --->", popped_name)
my list is ---> ['gaurav', 'kriti', 'neelam', 'praneel', 'riva', 'mona']
popped name is ---> kamlesh
In [19]:
#Removing Name
my_list.remove("neelam")
print(my_list)
['gaurav', 'kriti', 'praneel', 'riva', 'mona']
In [20]:
# List Operations
# Sorting of list
my_number_list = [8,2,9,4,9,7,5,4,3,2]
print("length of list ---->", len(my_number_list))
print("un-sorted list---->", my_number_list)
#inplace Sorting
my_number_list.sort()
print("sorted list---->", my_number_list)
length of list ----> 10
un-sorted list----> [8, 2, 9, 4, 9, 7, 5, 4, 3, 2]
sorted list----> [2, 2, 3, 4, 4, 5, 7, 8, 9, 9]
localhost:8888/lab/tree/Revision_python.ipynb 3/11
7/21/2021 Revision_python
In [21]: # Sorting of list
my_number_list = [8,2,9,4,9,7,5,4,3,2,3,21,65,67]
print("length of list ---->", len(my_number_list))
print("un-sorted list---->", my_number_list)
#Reverse Sorting
my_number_list_rev_sorted = sorted(my_number_list, reverse=True)
print("sorted list---->", my_number_list_rev_sorted)
length of list ----> 14
un-sorted list----> [8, 2, 9, 4, 9, 7, 5, 4, 3, 2, 3, 21, 65, 67]
sorted list----> [67, 65, 21, 9, 9, 8, 7, 5, 4, 4, 3, 3, 2, 2]
Programming Atti hai beta?
Haa sir loop laga lete hai!!
In [22]:
#Loops in list
In [23]:
for names in my_list:
print(names)
print([Link]())
gaurav
GAURAV
kriti
KRITI
praneel
PRANEEL
riva
RIVA
mona
MONA
In [24]:
for name in my_list:
print("The no of characters in",name,"is", len(name))
The no of characters in gaurav is 6
The no of characters in kriti is 5
The no of characters in praneel is 7
The no of characters in riva is 4
The no of characters in mona is 4
In [25]:
num=0 # initialising a variable to be 0
for name in my_list:
num=num+1 # increment the value of num by 1
print(num, name)
1 gaurav
2 kriti
3 praneel
4 riva
5 mona
In [26]:
## Range is very powerful use it!!
# range(n) --> (0,n-1)
# range(m,n) --> [m,n) ---> Total numbers = n-m
# Range(x,y,z) ---> Gives values from x, with an increment of z, upto y
localhost:8888/lab/tree/Revision_python.ipynb 4/11
7/21/2021 Revision_python
In [27]:
# To find the sum of all nmbers from 100 to 150 with an increment of 5
count = 0
sum_total = 0
for numbers in range(100, 150, 5):
count=count+1
sum_total = sum_total+numbers
print(numbers)
print("The count is:", count)
print("The sum of nos:", sum_total)
100
105
110
115
120
125
130
135
140
145
The count is: 10
The sum of nos: 1225
In [28]:
squares=[] # Empty list
for value in range(1,15): # range is used
square = value*value # square of each value
[Link](square) # Adding that value to the list, one by one
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196]
In [29]:
# Fininding Minimum and Maximum in the list
print("Minumum number is -->", min(squares))
print("Maximum number is -->", max(squares))
Minumum number is --> 1
Maximum number is --> 196
In [30]:
# Slicing of Strings
# This is how you copy a list also (or a subset of list) and create a new copy
# If you assign a new name it will update automatically (deep copy concept)
my_list_sliced = my_list[2:4]
print(my_list_sliced)
['praneel', 'riva']
In [31]:
# Tuples are like list they are immutable
my_tuple = (1,2,3,4,5)
my_tuple.remove(1)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-31-99e166b28353> in <module>
1 # Tuples are like list they are immutable
2 my_tuple = (1,2,3,4,5)
----> 3 my_tuple.remove(1)
localhost:8888/lab/tree/Revision_python.ipynb 5/11
7/21/2021 Revision_python
AttributeError: 'tuple' object has no attribute 'remove'
Conditional Statment and boolean
In [32]:
age = 52
age<100
Out[32]: True
In [33]:
age=20 # variable is assigned the value 20
if age>18: # evaluates the boolean expression
print('Yes, you are eligible to vote') # Since the boolean value id True, this is p
Yes, you are eligible to vote
Conditional operators
<: Less than
>: Greater than
<=: Less than or equal to
>=: Greater than or equal to
==: equal to
!=: Not equal to
In [34]:
age=15
if age>21:
print('Yes, you are legally eligible for marrying ')
elif age>18:
print(' You are not eligible to marry, but eligible to vote')
else:
print('No, you are not eligible for marrying')
No, you are not eligible for marrying
In [35]:
# If with a list
for name in my_list:
if name=='riva':
print(name,"is part of the list")
riva is part of the list
In [36]:
# Even Odd Numbers
# We require sum of nos, sum of even nos and sum of odd nos separately
nos = [1,2,3,4,5,8,9,12,25,64,7534,213,141,2]
sum_ = 0
sum_even = 0
sum_odd = 0
localhost:8888/lab/tree/Revision_python.ipynb 6/11
7/21/2021 Revision_python
for no in nos:
sum_ = sum_+no
if no%2==0: # checking the remainder is zero or not
sum_even = sum_even+no
else:
sum_odd = sum_odd+no
print("Sum of all nos:", sum_)
print("Sum of all even nos:",sum_even)
print("Sum of all odd nos:",sum_odd)
Sum of all nos: 8023
Sum of all even nos: 7626
Sum of all odd nos: 397
Its time for some dictionaries!!
In [37]:
details_dict = {'Number': 43,'Name':'Prakshaal'}
In [38]:
print("Dictionary is---->", details_dict)
print("Dictionary Keys Are ----->", details_dict.keys())
print("Dictionary Values Are ----->", details_dict.values())
Dictionary is----> {'Number': 43, 'Name': 'Prakshaal'}
Dictionary Keys Are -----> dict_keys(['Number', 'Name'])
Dictionary Values Are -----> dict_values([43, 'Prakshaal'])
In [39]:
# Adding elements in dictionary
details_dict['Place'] = "Bhilai"
print(details_dict)
{'Number': 43, 'Name': 'Prakshaal', 'Place': 'Bhilai'}
In [40]:
# Modifying values in dictionary
details_dict['Place'] = "Durg, Bhilai"
print(details_dict)
{'Number': 43, 'Name': 'Prakshaal', 'Place': 'Durg, Bhilai'}
In [41]:
#Deleting in dictionary
del details_dict["Place"]
print(details_dict)
{'Number': 43, 'Name': 'Prakshaal'}
In [42]:
#Looping in dictionay
# Only the values of the dictionary
for name in details_dict.values():
print(name)
43
Prakshaal
In [43]:
# Only the keys of the dictionary
for key in details_dict.keys():
localhost:8888/lab/tree/Revision_python.ipynb 7/11
7/21/2021 Revision_python
print(key)
Number
Name
In [44]:
details_dict.update({'place': 'Bhilai', 'District': 'Durg'})
print(details_dict)
{'Number': 43, 'Name': 'Prakshaal', 'place': 'Bhilai', 'District': 'Durg'}
In [45]:
# Nested Dictionary
# Dictionary within a dictionary
students = {
'stud_1': {'no': 1, 'name':'Prk'},
'stud_2': {'no': 2, 'name': 'Riva'},
'stud_3': { 'no': 3, 'name': 'Kriti'}
In [46]:
students['stud_3']['name']
Out[46]: 'Kriti'
In [47]:
count=0
for stud in [Link]():
if stud['name'] == 'Kriti':
count = count+1
print('No of repetitions of Kriti :',count)
No of repetitions of Kriti : 1
In [48]:
# List in Dictionary
stud_details={'no':'43',
'name':'Prakshaal',
'marks':[90,95,93,99,100,54]}
In [49]:
stud_details['marks'][1]
Out[49]: 95
In [50]:
minimum_marks = min(stud_details['marks'])
maximum_marks = max(stud_details['marks'])
Avergae_marks = sum(stud_details['marks']) / len(stud_details['marks'])
print("minimum_marks ---->",minimum_marks)
print("maximum_marks ---->",maximum_marks)
print("Avergae_marks ---->",Avergae_marks)
minimum_marks ----> 54
maximum_marks ----> 100
Avergae_marks ----> 88.5
localhost:8888/lab/tree/Revision_python.ipynb 8/11
7/21/2021 Revision_python
In [51]: # Counting the marks which are > 75 or not
count1 = 0
count2 = 0
for mark in stud_details['marks']:
if mark>75:
count1 = count1 + 1
else:
count2 = count2 + 1
print('Count of marks greater than 75:', count1)
print('Count of marks not greater than 75:', count2)
Count of marks greater than 75: 5
Count of marks not greater than 75: 1
Sets
In [52]:
my_set={29,34,12,39,33,24,46,66,55,55,55,55,5,55}
print(my_set)
{33, 34, 66, 5, 39, 12, 46, 55, 24, 29}
Input
In [54]:
# instance of input
name = input("Hi! what is your name? :")
print("Welcome! All the best for the test", name)
Welcome! All the best for the test Prk
Remark:
Whatever collected from the input() is treated as 'string'.
For mathemtical operation, we need to convert first before doing that operation.
In [56]:
x=float(input(" Supply a value for x as float:"))
y=float(input(" Supply a value for y as float:"))
print(" Sum : ", x+y)
print(" Difference : ", x-y)
print(" Prodcut : ", x*y)
print(" Divison : ", x/y)
Sum : 68.9
Difference : -21.699999999999996
Prodcut : 1069.08
Divison : 0.5209713024282562
While() loop
In [57]:
my_counter = 5
localhost:8888/lab/tree/Revision_python.ipynb 9/11
7/21/2021 Revision_python
while my_counter < 10:
my_counter = my_counter+1
print("my counter now, is:", my_counter)
print("Ho gaya!")
my counter now, is: 6
my counter now, is: 7
my counter now, is: 8
my counter now, is: 9
my counter now, is: 10
Ho gaya!
In [58]:
# Taking only even numbers in the looping
my_counter = 1
while my_counter < 10:
if my_counter%2 == 0:
print("my_counter now, is:", my_counter)
my_counter = my_counter + 1 # Change the order
print("Done with printing")
my_counter now, is: 2
my_counter now, is: 4
my_counter now, is: 6
my_counter now, is: 8
Done with printing
In [59]:
# To break out of the loop as soon as sum crosses 25
x = 1
sum_ = 0
while x<10:
sum_ = sum_ + x
print(" Now, sum is:", sum_, " and x is:", x)
x = x+1 # Change the order
if sum_>25:
break
print("Sum:",sum_)
Now, sum is: 1 and x is: 1
Now, sum is: 3 and x is: 2
Now, sum is: 6 and x is: 3
Now, sum is: 10 and x is: 4
Now, sum is: 15 and x is: 5
Now, sum is: 21 and x is: 6
Now, sum is: 28 and x is: 7
Sum: 28
In [60]:
# Continue Ststement
x=1
sum_=0
while x<10:
x = x+1 # Change the ord
if x%2 !=0: # odd numbers
continue
sum_=sum_+x
print(" Now, sum is:", sum_, " and x is:",x)
localhost:8888/lab/tree/Revision_python.ipynb 10/11
7/21/2021 Revision_python
# x = x+1 # Change the order
print("Sum:",sum_)
Now, sum is: 2 and x is: 2
Now, sum is: 6 and x is: 4
Now, sum is: 12 and x is: 6
Now, sum is: 20 and x is: 8
Now, sum is: 30 and x is: 10
Sum: 30
In [ ]:
localhost:8888/lab/tree/Revision_python.ipynb 11/11