November 23 Morning Python
# Compiler
# interpreter – Python, R
# pycharm editor by Jetbrains
print(“HELLO”) #tffjhgjhj
”’
sdfgdfgdf
dfdfgfd
zdfgdfzgzdf
”’

Day 1 Python Tutorial - Introduction

# print – print the content on the screen
print(“5 + 3”)
print(5 + 3)
print(“5 + 3 =”, 5 + 3, “and 6+2 is also”,6+2)
#below we defined a variable called num1 and assgined a value
num1=30
num1 = 90

# there are 5 basic types of data:

# 1. integer (int): -infinity to + infinity no decimal
# 45, -99, 0, 678
num1=30
# type() which gives the type of the data (datatype)
print(type(num1)) #<class ‘int’>

# 2. Float (float) – decimal data
# 45.8, -99.9, 0.0, 678.123456678
num1=30.0
print(type(num1)) #<class ‘float’>
# 3. complex [square root of -1]: 3+2j, -7j

num1=30j
print(type(num1)) #<class ‘complex’>

print(30j* 30j)


# 4. string (str) – text data
# strings are defined using ‘ or ” or ”’ or “””
word1 = ‘hello’
print(type(word1)) #<class ‘str’>
word1 = ‘5’
print(type(word1)) #<class ‘str’>

# 5. boolean (bool) – just 2 values: True and False
b1 = ‘True’
print(type(b1)) #<class ‘str’>
b1 = True
print(type(b1)) #<class ‘bool’>

### ####
print(“Hello”)
a = 45;print(a);print(‘a’)

##
# variables – can have alphabets, numbers and _
# variable name cant start with a number
cost_potato = 35
cost_tomato = 55
qty_potato = 37
total_cost_potato = cost_potato * qty_potato
print(“Cost of potato is Rs”,cost_potato,“/kg so for the”,
qty_potato,“kg cost would be Rs”,total_cost_potato)

# f – string (format string)
print(f”Cost of potato is Rs {cost_potato} /kg so for the “
f”{qty_potato} kg cost would be Rs {total_cost_potato})

# print()
# int, float, bool, complex, str
# f string
print(“Hello”)
print(“Hi”)

# escape sequence: \
print(“Hello \\hi”)
print(\n will generate newline”)
print(\t will give tab spaces”)

print(\\n will generate newline”)
print(\\t will generate tab space”)

# \\n is not generate newline
print(\\\\n is not generate newline”)

# f string
q = 50
p = 25
t = q * p
print(f”The cost of each pen is {p} so for {q} quantities, the total cost will be {t}.”)

t = 200
q = 23
p = t / q
# how to format decimal places using f-string
print(f”The cost of each pen is {p:.2f} so for {q} quantities, the total cost will be {t}.”)

# format your string values
pos,country, name = “Batsman”,“India”, “Virat”
print(f”Player {name:<16} plays for {country:^16} as a {pos:>16} in the team”)
pos,country, name = “Wicket-keeper”,“South Africa”, “Mangabwabe”
print(f”Player {name:<16} plays for {country:^16} as a {pos:>16} in the team”)

### working with variables
# numeric operations available: Arithematic operations
n1, n2 = 10,5
print(n1 + n2)
print(n1 – n2)
print(n1 * n2)
print(n1 / n2)
print(n1 // n2) # integer division
print(31/4)
print(31//4)
print(n1 ** n2) #power of10 to 5
print(n1 % n2) # modulus – mod – remainder
print(31 % 4)

### relational operations
# comparators – comparison operators: > < <= >=, == , !=
# output is bool values
# 6 > 9 : is 6 greater than 9? False
n1,n2,n3 = 10,5, 10
print(n1 > n2) # T
print(n1 < n2) # F
print(n1 >= n2) # T
print(n1 <= n2) # F
print(n1 == n2) # F
print(n1 != n2) # T
print(“checking with n3….”)
print(n1 > n3) # F
print(n1 < n3) # F
print(n1 >= n3) # T
print(n1 <= n3) # T
print(n1 == n3) # T
print(n1 != n3) # F

# Assignment operation =
n1 = 10
print(n1) # value is 10

#logical operators: i/p and o/p both bool
#operators are: and or not
”’
Prediction: Rohit and Gill will open the batting
Actual: Rohit and Kishan opened the batting
Prediction ? False

Prediction: Rohit or Gill will open the batting
Actual: Rohit and Kishan opened the batting
Prediction ? True

AND:
T and T => True and rest everything is False

OR:
F or F => False and rest everything is True

NOT: Not True is false and Not false is true
”’
n1,n2,n3 = 10, 5, 10
print(n1 == n2 and n1 != n2 and n1 > n3 or n1 < n3 or n1 >= n3 and n1 <= n3 or
n1 == n3 and n1 != n3)
# F and T and F or F or T and T or T and F
# F or F or T or F
# T
# BODMAS: AND take priority over OR
## converting one type to another:
# int() str() bool() complex() float()
n1 = 50
print(n1)
print(type(n1))
n2 = str(n1)
print(type(n2))
print(n2)

# input() – is to read the content from the user
# by default, input() will read as string value
val1 = input()
print(val1)
print(type(val1))

#WAP to add two numbers by taking input from the user
a = input(“Enter first number: “)
b = input(“Enter second number: “)
c = int(a) + int(b)
print(“Sum is “,c)

# WAP to read length and breadth of a rectangle from the user
# and display area and perimeter.
len = int(input(“Enter length: “))
breadth = int(input(“Enter breadth: “))
area = len * breadth
peri = 2*(len + breadth)
print(f”Area = {area} and Perimeter = {peri})
# calculate area and circunference of a circle
pi = 3.14
rad = float(input(“Enter the radius of the circle: “))
area = pi*(rad**2)
cir = 2*pi*rad
print(f”A circle with radius {rad:.1f} has an area of {area:.2f} and circunference of {cir:.2f})


#program to calculate total and average of marks obtained in 5 subjects
sub1 = int(input(“Enter the marks in subject 1: “))
sub2 = int(input(“Enter the marks in subject 2: “))
sub3 = int(input(“Enter the marks in subject 3: “))
sub4 = int(input(“Enter the marks in subject 4: “))
sub5 = int(input(“Enter the marks in subject 5: “))
total = sub1 + sub2 + sub3 + sub4 + sub5
avg = total / 5
print(“Total marks obtained is”,total,“with an average of”,avg)

# WAP to indicate number of each value of currency note you will pay
# based on the total demand
”’
Currency notes available: 500, 100, 50, 20, 10, 5, 2, 1
Total bill = 537
500 – 1
20 – 1
10 – 1
5 – 1
2 – 1
”’
five00, one00,fifty,twenty, ten,five,two,one = 0,0,0,0,0,0,0,0
total_amount= int(input(“Enter total bill amount = “))
five00 = total_amount // 500
total_amount = total_amount % 500
one00 = total_amount // 100
total_amount = total_amount % 100
fifty = total_amount // 50
total_amount = total_amount % 50
twenty = total_amount // 20
total_amount = total_amount % 20
ten = total_amount // 10
total_amount = total_amount % 10
five = total_amount // 5
total_amount = total_amount % 5
two = total_amount // 2
total_amount = total_amount % 2
one = total_amount
print(“Total currency that would be paid:”)
print(f”500s = {five00}, 100s = {one00}, 50s ={fifty},20s = {twenty}, “
f”10s = {ten},5s = {five},2s ={two},1s={one})
# Conditions: if command is used to check for the conditions
# if command is followed by condition (conditional operator) and if
# the condition result in true it will get into If block

num1 = 9
q = int(input(“Enter the quantity: “))
if q > 0:
print(“Quantity accepted”)
print(“Sales confirmed”)
print(“Thank You”)
#but lets say you want to have alternate condition, that means when
# its True then print True part and when its not then you want to
#print false part
if q > 0: #True then go to below
print(“Given Quantity accepted”)
else: # if condition is false then comes here
print(“Quantity rejected”)

##
num = 0
if num>0:
print(“Number is positive”)
else:
print(“Number is not positive”)

# WAP to indicate number of each value of currency note you will pay
# based on the total demand
”’
Currency notes available: 500, 100, 50, 20, 10, 5, 2, 1
Total bill = 537
500 – 1
20 – 1
10 – 1
5 – 1
2 – 1
”’
five00, one00,fifty,twenty, ten,five,two,one = 0,0,0,0,0,0,0,0
total_amount= int(input(“Enter total bill amount = “))
five00 = total_amount // 500
total_amount = total_amount % 500
one00 = total_amount // 100
total_amount = total_amount % 100
fifty = total_amount // 50
total_amount = total_amount % 50
twenty = total_amount // 20
total_amount = total_amount % 20
ten = total_amount // 10
total_amount = total_amount % 10
five = total_amount // 5
total_amount = total_amount % 5
two = total_amount // 2
total_amount = total_amount % 2
one = total_amount
print(“Total currency that would be paid:”)
if five00>0:
print(f”500s = {five00})
if one00>0:
print(f”100s = {one00})
if fifty>0:
print(f”50s ={fifty})
if twenty>0:
print(f”20s = {twenty})
if ten>0:
print(f”10s = {ten})

if five>0:
print(f”5s = {five})
if two>0:
print(f”2s ={two})
if one>0:
print(f”1s={one})

#program to calculate total and average of marks obtained in 5 subjects
sub1 = int(input(“Enter the marks in subject 1: “))
sub2 = int(input(“Enter the marks in subject 2: “))
sub3 = int(input(“Enter the marks in subject 3: “))
sub4 = int(input(“Enter the marks in subject 4: “))
sub5 = int(input(“Enter the marks in subject 5: “))
total = sub1 + sub2 + sub3 + sub4 + sub5
avg = total / 5
print(“Total marks obtained is”,total,“with an average of”,avg)

# we need to check if the student has passed or failed
# avg > 50 – pass otherwise fail
if avg>=50:
print(“Student has passed”)
else:
print(“Student has failed”)
# check if a number is positive or negative or neither
num = int(input(“Enter the number: “))
if num > 0:
print(“Its positive”)
elif num < 0:
print(“Its negative”)
else:
print(“Its neither – its zero”)

#program to calculate total and average of marks obtained in 5 subjects
sub1 = int(input(“Enter the marks in subject 1: “))
sub2 = int(input(“Enter the marks in subject 2: “))
sub3 = int(input(“Enter the marks in subject 3: “))
sub4 = int(input(“Enter the marks in subject 4: “))
sub5 = int(input(“Enter the marks in subject 5: “))
total = sub1 + sub2 + sub3 + sub4 + sub5
avg = total / 5
print(“Total marks obtained is”,total,“with an average of”,avg)

# we need to check if the student has passed or failed
# avg > 50 – pass otherwise fail
if avg>=50:
print(“Student has passed”)
else:
print(“Student has failed”)

# Grading of the student:
”’
avg >= 90 : Grade A
avg >= 80 : Grade B
avg >= 70: Grade C
avg >= 60: Grade D
avg >= 50: Grade E
avg <50: Grade F
”’
if avg >= 90 :
print(“Grade A”)
elif avg >= 80 :
print(“Grade B”)
elif avg >= 70:
print(“Grade C”)
elif avg >= 60:
print(“Grade D”)
elif avg >= 50:
print(“Grade E”)
else:
print(“Grade F”)

# input a number and check if the number is odd or even
num = int(input(“Enter the number: “))
if num<0:
print(“Invalid number!”)
elif num%2==0:
print(“Even number”)
else:
print(“Odd Number”)

# input a number and check if the number is odd or even
# example of nested condition
num = int(input(“Enter the number: “))
if num>0:
if num%2==0:
print(“Even number”)
else:
print(“Odd Number”)

#program to calculate total and average of marks obtained in 5 subjects
sub1 = int(input(“Enter the marks in subject 1: “))
sub2 = int(input(“Enter the marks in subject 2: “))
sub3 = int(input(“Enter the marks in subject 3: “))
sub4 = int(input(“Enter the marks in subject 4: “))
sub5 = int(input(“Enter the marks in subject 5: “))
total = sub1 + sub2 + sub3 + sub4 + sub5
avg = total / 5
print(“Total marks obtained is”,total,“with an average of”,avg)
# we need to check if the student has passed or failed
# avg > 50 – pass otherwise fail
# and also assign Grades
if avg>=50:
print(“Student has passed”)
if avg >= 90:
print(“Grade A”)
if avg>95:
print(“You win President’s Medal”)
if avg >98:
print(“You win State Governor’s Award!”)
elif avg >= 80:
print(“Grade B”)
elif avg >= 70:
print(“Grade C”)
elif avg >= 60:
print(“Grade D”)
else:
print(“Grade E”)
else:
print(“Student has failed”)
print(“Grade F”)

########## ###########
## LOOPS
########## ###########
# Loops : repeatition
# hello 10 times
# for loop: used when we know how many times to repeat
# while loop: used when we know when to repeat and when not to
# range() works with if
# range(=start, <end, =step): start = 5, end =11, step=2:
# 5, 7, 9,
# range(=start, <end): step default = 1
# range(5,11): 5,6,7,8,9,10

# range(<end): step default = 1, start default = 0
# range(5): 0,1,2,3,4
for i in range(5,11,2):
print(i,“hello 1”)

for i in range(5,10):
print(i,“hello 2”)

for i in range(5):
print(i,“hello”)
# Loops – repeatitive tasks
# for loop and while loop

# generate numbers from 1 to 20
for i in range(1,21):
print(i,end=“, “)
print()
# generate first 10 odd numbers
for i in range(10):
print(i*2+1,end=“, “)
print()
# generate even numbers between 10 and 20
for i in range(10,21,2):
print(i,end=“, “)
print()
#multiplication table of 8 upto 10 multiples
num = 8
for i in range(1,11):
print(f”{num} * {i} = {num*i})

#multiplication table of 1 to 10 upto 10 multiples
for num in range(1,11):
for i in range(1,11):
print(f”{num} * {i} = {i*num})

#multiplication table of 1 to 10 upto 10 multiples
# print them side by side
”’
1×1=1 2×1=2 … 10×1=10
1×2=2 2×2=2

1×10=10
”’
for num in range(1,11):
for i in range(1,11):
print(f”{i} * {num} = {num*i},end=\t)
print()

print(“Thank you”)
######### #######
## More examples of For Loop
####### #######
for i in range(5):
print(“*”,end=” “)
print()
print(\n#print square pattern of stars”)
num = 5
for j in range(num):
for i in range(num):
print(“*”,end=” “)
print()

print(\n#right angled triangle pattern”)
num = 5
for j in range(num): #tracking rows
for i in range(j+1): #column
print(“*”,end=” “)
print()

print(\n#inverted right angled triangle pattern”)
num = 5
for j in range(num): #tracking rows
for i in range(num-j): #column
print(“*”,end=” “)
print()

print(\n#Isoceles triangle pattern”)
”’
* * * * *
* * * *
* * *
* *
*
”’
num = 5
for j in range(num): #tracking rows
for i in range(j): #column
print(” “,end=“”)
for k in range(num-j): #column
print(“*”,end=” “)
print()

print(\nASSIGNMENT: Inverted Isoceles triangle pattern”)
”’
*
* *
* * *
* * * *
* * * * *
”’
# Write your code here

# Calcualte total of 5 subjects marks
total = 0
for i in range(5):
m1 = int(input(“Marks in subject “+ str(i+1)+ “: “))
total += m1 #total = total + m1
print(total)
# Loops – While loop: we know the condition when to start/stop
# generate numbers from 1 to 20
i=1
while i<21:
print(i,end=“, “)
i=i+1
print()
# generate first 10 odd numbers
i = 0
while i <10:
print(i*2+1,end=“, “)
i+=1
print()
# generate even numbers between 10 and 20
i=10
while i<21:
print(i,end=“, “)
i+=2
print()

## ## ##
# Calcualte total of 5 subjects marks for given number of students
cont = 1
while cont ==1:
total = 0
for i in range(5):
m1 = int(input(“Marks in subject “+ str(i+1)+ “: “))
total += m1 #total = total + m1
print(total)
inp = input(“Do you want to add more students (y for yes/anyother key to stop):”)
if inp!=“y”:
cont = 0

## rewriting above program
while True:
total = 0
for i in range(5):
m1 = int(input(“Marks in subject “+ str(i+1)+ “: “))
total += m1 #total = total + m1

print(total)
inp = input(“Do you want to add more students (y for yes/anyother key to stop):”)
if inp!=“y”:
break
”’
break: it will throw you out of the loop
”’
”’
Create a set of Menu options for a Library
”’
while True:
print(“Menu:”)
print(“1. Add books to the library”)
print(“2. Remove books from the library”)
print(“3. Issue the book to the member”)
print(“4. Take the book from the member”)
print(“5. Quit”)
choice = input(“Enter your option:”)
if choice==“1”:
print(“Adding books to the library”)
elif choice==“2”:
print(“Removing books from the library”)
elif choice==“3”:
print(“Issuing the book to the member”)
elif choice==“4”:
print(“Taking the book from the member”)
elif choice==“5”:
break
else:
print(“Invalid option! try again…”)

”’
Based on this program, create a Menu option for performing basic
arithematic operations like + – * / // ** %
”’
”’
Develop a guessing number Game

”’
import random
num1 = random.randint(1,100)
attempts = 0
while True:
guess = int(input(“Guess the number (1-100): “))
if guess >100 or guess < 1:
print(“INVALID NUMBER!”)
continue
attempts+=1
if num1 ==guess:
print(f”Good job! You guessed it correctly in {attempts} attempts.”)
break
elif num1 < guess:
print(“Sorry! Try guessing lower number”)
else:
print(“Sorry! Try guessing higher number”)

# # # # # #
”’
Develop a guessing number Game

”’
import random
num1 = random.randint(1,100)
attempts = 0
low,high = 1,100
while True:
#lets make computer guess the number
guess = random.randint(low,high)
if guess >100 or guess < 1:
print(“INVALID NUMBER!”)
continue
attempts+=1
if num1 ==guess:
print(f”Good job! You guessed {guess} correctly in {attempts} attempts.”)
break
elif num1 < guess:
print(f”Sorry! Try guessing lower number than {guess})
high=guess – 1
else:
print(f”Sorry! Try guessing higher number than {guess})
low= guess + 1

# # # #
# # # # #
# LIST
# # # # #
l1 = [25,45.9,“1”,[29,41]]
print(“Data type of L1 : “,type(l1))
print(“Number of values in L1 : “,len(l1))
print(“Values in the list = “,l1)

l2 = [“Hello”,“How”,“Are”,“You”]
l3 = l1 + l2
print(“L3 = “,l3)
print(“Multiply = “,l2 * 3)

# Indexing
#indexing starts with 0,
print(“4th value from the list: “,l3[3])
l5 = l3[3]
print(l5[1])
print(l3[3][1])
print(“last member of the list = “,l3[len(l3)-1])
print(“last member of the list = “,l3[-1])
print(“first member of the list = “,l3[0])
print(“first member of the list = “,l3[-len(l3)])
print(“First 3 members of the list: “,l3[0:3])
print(“First 3 members of the list: “,l3[:3])
print(“Last 3 members of the list: “,l3[:])
”’
List – linear ordered mutable collection
”’
l1 = [5,15,25,35]
l1[1] = 20 #mutable
print(l1)
print(l1[1:3])
print(l1[:]) #left of : blank -0 index, blank on right indicate – last index
print(“Last 2 members of L1=”,l1[2:4], “or”,l1[2:],“or”,l1[-2:])
var1 = ‘hello’
print(var1[1])
# strings are immutable
#var1[1]=”E” – TypeError: ‘str’ object does not support item assignment

l1 = [100]
print(type(l1))
l1.append(10) # to add members to the list – it will add at the end
l1.append(20)
l1.append(30)
#insert() – also adds but it needs the position
l1.insert(40,1)
l1.insert(1,50)
l1.insert(1,20)
l1.insert(1,20)

print(l1)
#remove(value_to_be_removed) , pop(index_to_be_deleted)
# remove all 20s
#first count the # of 20
num_20 = l1.count(20)
for i in range(num_20):
l1.remove(20)
print(l1)
l1.pop(1)
print(l1)
l1.append(100)
# check if 100 is in the list
count_100 = l1.count(100)
if count_100 >0:
print(“100 is in the list and at position”,l1.index(100))
print(“100 is in the list and at position”, l1.index(100,1,7))
else:
print(“100 is not in the list”)

## write a program to read marks of 5 subjects
# and store the values and display total and avg

marks=[]
for i in range(5):
m = int(input(“Enter marks: “))
marks.append(m)

print(“Total marks = “,sum(marks),“and avg=”,sum(marks)/5)
l2 = [1,2,3,4,5,6,2,3,4]
l2.reverse()
print(“Reverse: “,l2)
l2.sort() #sort in increasing order
print(“Sort: “,l2)
l2.sort(reverse=True) #sorting in decreasing order
print(l2)
####
print(“======= ========”)

l3 = l2 #deep copy – two names of same list
l4 = l2.copy() #shallow copy – photocopy
print(“L2 = “,l2)
print(“L3 = “,l3)
print(“L4 = “,l4)
l2.append(77)
l3.append(88)
l4.append(99)
print(“L2 = “,l2)
print(“L3 = “,l3)
print(“L4 = “,l4)
print(“======= ========”)

l2.clear() # delete all the members from the list
print(“After clear: “,l2)

”’
Stack – First In Last Out:
Assignment – Implement Stack concept using List:
use: while True to create a menu with 4 options:
1. Add to the stack
2. Remove to the stack
3. Print the values from the stack
4. Quit
Start with an empty list and perform addition/deletion
to the list based on user selection
”’
# TUPLE
val1 = (1, “hello”, [3, 4, 5]) # packing
print(“Data type = “, type(val1))
# immutable
l1 = [2, 3, 4]
l1[1] = 33
print(“L1 = “, l1)
# val1[1]=”There” TypeError: ‘tuple’ object does not support item assignment
# so tuples are immutable

# indexing – reading values from tuple is exactly like list
for t in val1:
print(t)

# unpacking:
v1, v2, v3 = val1
print(v1, v2, v3)
print(“Number of values in tuple=”, len(val1))

val2 = (39, 68)
val3 = (14, 98, 254, 658)
if val2 > val3:
print(“Val2 is greater”)
else:
print(“Val3 is greater”)

# converting tuple to list
val1 = list(val1)
val1 = tuple(val1)
#STRINGS
# handling text data
str1 = “HELLO”
str2 = ‘Hi there’
str3 = ”’Hello how are you?
Are doing well?
See you soon”’
str4 = “””I am fine
I am doing well
hope you are doing great too”””
print(str3)

# indexing is very similar to list and tuple
print(str1[0],str1[-1],str1[:])
print(str1+” “+str2)
print(str1*3)
# strings are also (like tuple) immutable
# you cant edit the existing string value
#str1[0]=”Z” TypeError: ‘str’ object does not support item assignment
str1 = “Z”+str1[1:]
print(“New Value = “,str1)

# you can use str in for loop just like List or Tuple
for s in str1:
print(s)

#methods in str class
str1 = “heLLO how aRE YOU?”
# case related – convering to a specific case
print(str1.lower())
print(str1.upper())
print(str1.title())

#checking the existing str value
str1 = “heLLO how aRE YOU?”
str2= “helohowru”
print(str1.isalpha())
print(str2.isalpha())
print(str1.isspace())
print(str2.islower())
print(str2.isalnum())