PYTHON NOV 2023

Learn to Install Python from here: https://learn.swapnil.pw/python/pythoninstallation/

”’
print() – displays the content on the screen
functions have () after the name

python commands are case sensitive- Print is not same as print
”’

# idgjdsigjfigj
# comments mean that you are asking computer to ignore them

print(5)
print(5+3)
print(‘5+3’)
print(“5+3”)
print(‘5+2*3=’,5+2*3,“and 4*3=”,4*3)
print(“Hello How are you?”);print(‘Hello How are you?’)
# print always starts from a new line
# escape sequence: \n (newline) \t for tab spaces
print(“How are you doing? \nWhere are you \tgoing?”);
# What’s your name?
print(“What’s your name?”)
# He asked me,”What’s your name?”
print(“He asked me,\”What’s your name?\”,end=\n)

# He asked me,\”What’s your name?\”
print(“He asked me,\\\”What’s your name?\\\”,end=\n)
print(“Hello”,end=” – “)
print(“How are you?”)

print(“Basic data types in Python”)
# numeric – int (integer)- -99, -4,0,5,888: no decimal values
marks1 = 43

marks2 = 87
print(“Marks1 =”,marks1)
marks1 = 99
print(marks1)
# function: type() – it gives the datatype
print(type(marks1)) #<class ‘int’>

marks = 87.0 # <class ‘float’>
print(type(marks))

# complex: square root of -1: j
calc = 3j * 4j
print(calc) # 12 j-square = -12 + 0j
print(‘Data type of calc = ‘,type(calc))

# int float complex
a = –55
print(type(a))
a = –55.0
print(type(a))
a = –55j
print(type(a))

# str – string – text
print(“HELLO”)
name=“Sachin”
print(name)
print(“type = “,type(name))
name=‘Virat kohli leads \nbangalore team in IPL’
print(name)
print(“type = “,type(name))

name=”’Rohit is the captain
of Indian team
He opens in the ODIs”’
print(name)
print(“type = “,type(name))

name=“””Rohit led the Indian team
in 2023 ODI World cup and
reached finals”””
print(name)
print(“type = “,type(name))

#5th data type – Bool boolean – 2 values: True and False
val1 = True # False
print(type(val1))

# Formatting the print statement
quantity = 12
price = 39
total = quantity * price
print(“Total cost of”,quantity,“books which costs per copy Rs”,price,“will be Rs”,total)
# f – string is used to format the output
print(f”Total cost of {quantity} books which costs per copy Rs {price} will be Rs {total})

# f-string is used to format float values as well
quantity, total = 12, 231.35
price = total/quantity
print(f”Total cost of {quantity} books which costs per copy Rs {price:.1f} will be Rs {total})

# f-string for string values
name,country,title=“Rohit”,“India”,“Captain”
print(f”Player {name:<12} plays for {country:^10} and is the {title:>15} of the team”)
name,country,title=“Mangbwabe”,“Zimbabwe”,“Wicket-keeper”
print(f”Player {name:<12} plays for {country:^10} and is the {title:>15} of the team”)

### INPUT
## to take input from the user
## input can take no or at max 1 parameter
inp_val = int(input(“Enter first number: “))
print(inp_val)
print(“Datatype of input=”,type(inp_val))
inp_val2 = int(input(“Enter second number: “))
print(“Sum of two numbers=”,inp_val+inp_val2)

## change below programs to accept the values from the user using input

# 1. write a program to calculate area and perimeter of a rectangle
l=50
b=20
area = l*b
peri = 2*(l+b)
print(f”Area and perimeter of a rectangle with length {l} and breadth {b} is {area} and {peri} respectively”)
# 2. write a program to calculate area and perimeter of a square
#### Assignment ##
# 3. write a program to calculate volume and surface area of a cone
#### Assignment ##
# 4. write a program to calculate volume and surface area of a cylinder
#### Assignment ##
# 5. write a program to calculate area and circumference of a circle
r=50
pi = 3.12
area = pi*r**2
cir = 2*pi*r
print(f”Area and circumference of a circle with radius {r} is {area} and {cir} respectively”)
# input() – read input from the user
num1 = int(input(“Enter first number:”))
print(“type = “,type(num1))
num2 = int(input(“Enter second number:”))
print(“Sum is “,num1+num2)

# calculate area and perimeter for a rectangle
length=float(input(“Enter length of the rectangle:”))
breadth=float(input(“Enter breadth of the rectangle:”))
perimeter = (length+breadth)*2
print(“Perimeter of the rectangle is”,perimeter)

# int() -to convert to int
#similarly you can use float(), str() bool() complex()
# operators:
# Arithmatic operators: + – * / ** // % (modulo – remainder)
num1 = 11 #assignment operator = we are assigning value 11 to num1
num2 = 3
print(num1 + num2)
print(num1 – num2)
print(num1 * num2)
print(num1 / num2)
print(num1 ** num2) #power
print(num1 // num2) #integer division
print(num1 % num2) # remainder

## relational operators (comparision)
## > >= < <= == != (is it?)
## output is always bool (True or False)
num1,num2,num3 = 11,9,11
print(“Relational : “, num1 > num2) # T
print(“Relational : “, num1 >= num3) # T
print(“Relational : “, num1 < num2) # F
print(“Relational : “, num1 <= num3) # T
print(“Relational : “, num1 == num2) # F
print(“Relational : “, num1 == num3) # T
print(“Relational : “, num1 != num2) # T
print(“Relational : “, num1 != num3) # F
print(“Relational : “, num1 > num3) # F
print(“Relational : “, num1 < num3) # F

# Logical operators: and or not
# input and output are both bool values
”’
Prediction 1: Rohit and Ishan will open the batting
Prediction 2: Rohit or Ishan will open the batting
Actual: Rohit and Gill opened the batting
Prediction 1 False
Prediction 2 True

Truth Table: AND (*)
T and T = T
T and F = F
F and T = F
F and F = F

OR (+)
T or T = T
T or F = T
F or T = T
F or F = F

not T = F
not F = T
”’
num1,num2,num3 = 11,9,11
print( not(num1 > num2 and num1 >= num3 or num1 < num2 or num1 <= num3 and num1 == num2
and num1 == num3 or num1 != num2 or num1 != num3 and num1 > num3 or num1 < num3))
# T and T or F or T and F and T or T or F and F or F
# T or F or F or T or F or F
# T
# int to binary and vice-versa
num1 = 34
print(“Binary of num1=”,bin(34))
num2 = 0b100010
print(“Integer of num2=”,int(num2))
print(oct(34)) # 0o42
print(hex(34)) # 0x22

#Bitwise: & (bitwise and) | (bitwise or) >> (right shift) << (left shift)
num1 = 23 #0b10111
num2 = 31 #0b11111
print(bin(num1),“and”,bin(num2))
”’
bitwise &
10111
11111
——–
10111
”’
print(int(0b10111)) # 23
print(“23 & 31 = “,23 & 31) # 23

”’
bitwise |
10111
11111
——–
11111
”’
print(“23 | 31 = “,23 | 31) # 31

”’
THTO
54320
”’
print(“23 << 2:”,23 << 2) # 92
”’
1011100 << 2
”’
print(int(0b1011100))

print(“23 << 2:”,23 >> 2) # 5
”’
101
”’
print(int(0b101))

# conditions
”’
display message after checking if the student has passed or failed the exam
condition is avg >= 40 to pass

if command checks the condition is Python
syntax:
if condition :
# perform things when the condition is true


Title
* sub
o ss
i.
ii.
”’
avg =82
if avg >=40:
print(“Congratulations!”)
print(“You’ve passed!”)

print(“Thank you”)
”’
Check avg and print Pass or Fail
”’
avg = 19
if avg >=40:
print(“Pass”)
else:
print(“Fail”)
# IF – condition – will always result into True or False

num1 = 71.000000001
num2 = 71
# if num1 is greater than num2 then I want to print How are you? otherwise do nothing
if num1 > num2:
print(“How are you?”)
print(“Where are you going?”)

print(“Thank you”)

# if num1 is greater than num2 then I want to print How are you? otherwise print Do nothing
if num1 > num2:
print(“How are you?”)
print(“Where are you going?”)
else:
print(“Do Nothing”)

”’
Input a number from the user and check if its +ve, -ve or zero
”’
val = int(input(“Enter a number: “))
print(“Type of data =”,type(val))

# IF – ELIF – ELSE
if val==0: # == is to check the equality
print(“Its Zero”)
elif val <= 0:
print(“Its -ve number”)
else:
print(“Its +ve number”)

if val==0:
print(“Its Zero”)
if val<=0:
print(“Its -ve number”)
if val>=0:
print(“Its +ve number”)

”’
Write a program to take 2 inputs from the user and check if the first
number is greater, smaller or equal to the second one
”’
num1 = int(input(“Enter first number: “))
num2 = int(input(“Enter second number: “))
if num1 > num2:
print(num1,“is greater than”,num2)
elif num1 < num2:
print(num1,“is less than”,num2)
else:
print(num1, “and”, num2,“are equal”)

”’
WAP to take marks in 5 subjects as input, calculate total and average
and assign grade based on below condition:
a. avg 85 – Grade A
b. avg 70-85 – Grade B
c. avg 60-70 – Grade C
d. avg 50-60 – Grade D
e. avg 40 -50 – Grade E
f. avg <40 – Grade F
”’
marks1 = float(input(“Enter the marks in subject 1: “))
marks2 = float(input(“Enter the marks in subject 2: “))
marks3 = float(input(“Enter the marks in subject 3: “))
marks4 = float(input(“Enter the marks in subject 4: “))
marks5 = float(input(“Enter the marks in subject 5: “))
total = marks1 + marks5 + marks4 + marks3 + marks2
avg = total / 5
print(f”Total marks is {total:.2f} and average is {avg:.2f})
if avg>=85:
print(“Grade A”)
elif avg>=70:
print(“Grade B”)
elif avg>=60:
print(“Grade C”)
elif avg>=50:
print(“Grade D”)
elif avg>=40:
print(“Grade E”)
else:
print(“Grade F”)

”’
Let’s write a program to read length and breadth from the user
check if its square or rectangle and calculate area and perimeter
”’
length = int(input(‘Enter the length: ‘))
breadth = int(input(‘Enter the breadth: ‘))
#and & or are logical operator which connects you conditonal statements
# and: both the statements need to be true for True else its false
# or: both the statements need to be false for False else its True
if length>0 and breadth >0:
print(“Rectangle and Square both possible”)
if length==breadth:
print(“Square”)
print(f”Area is {length**2} and the perimeter is {4*length})
else:
print(“Rectangle”)
print(f”Area is {length * breadth} and the perimeter is {2 * (length+breadth)})
else:
print(“Neither Rectangle nor Square possible”)
”’
check if a number is positive, negative or zero
if the number is -ve, find the square root
if number is positive, check if its 2 digit or not
if 2 digits then interchange the values
otherwise, check if its divisible by 15,
”’

num1 = int(input(“Enter a number: “))
if num1<0:
print(“This is negative”)
print(f”Square root of {num1} is {num1**0.5})
elif num1==0:
print(“This is zero”)
else:
print(“This is positive”)
if num1>9 and num1<100:
#interchange the values: eg 35 = 53
# divide number by 10 =
d = num1 // 10
r = num1 % 10
new_num1 = r*10+d
print(f”{num1} is now made into {new_num1})

else:
if num1 % 15==0: # % mod – will give you remainder
print(“Number is divisible by 15”)
else:
print(“Number is not divisible by 15”)

#LOOPS – repeat the give block of code multiple times
# when you know exactly how many times to run – for
# repeatition is done based on a certain condition – while

# range(start,end,increment)- generates range of values from start upto end
# by increasing each element ny increment
# range(6,18,3): 6,9,12, 15
# range(start,end): increment is default 1
# range(15,19): 15,16,17,18
# range(end): start = 0, increment = 1
# range(6): 0, 1, 2, 3, 4, 5
#print(), input(), type(), int(),str(),complex(),bool(), float()

for var in range(6,18,3):
print(“Hello from the loop!”)
print(“Value of var is”,var)

for count in range(15,19):
print(“Hello from the loop2!”)
print(“Value of var is”,count)

for count in range(4):
print(“Hello from the loop3!”)
print(“Value of var is”,count)

###
for i in range(5):
print(“*”,end=” “)
print()
for i in range(1,101):
print(i,end=“, “)
print()
”’
Generate odd numbers between 1 and 30
”’
for i in range(1,30,2):
print(i,end=“, “)
print()
”’
Generate first 10 even numbers
”’
start = 0
for i in range(10):
print(start,end=“, “)
start=start+2

print()
# for loop examples
”’
Print all the numbers between 1 and 1000 which is perfectly divisible by 19 and 51
”’
start,end = 1, 10001
num1,num2 = 19,51
for n in range(start,end):
if n%num1==0 and n%num2==0:
print(n,end=“, “)
print()
”’
Generate prime numbers between 10000 and 50000
”’
start,end = 40000, 42000
for n in range(start,end):
isPrime = True
for num in range(2,n//2+1):
if n %num==0:
isPrime = False
break
if isPrime:
print(n,end=“, “)

”’
Print different * patterns
”’
for i in range(5):
print(“*”)

”’
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
”’
for j in range(5):
for i in range(5):
print(“*”,end=” “)
print()

”’
*
* *
* * *
* * * *
* * * * *
”’

for j in range(5):
for i in range(1+j):
print(“*”,end=” “)
print()

”’
* * * * *
* * * *
* * *
* *
*
”’

for j in range(5):
for i in range(5-j):
print(“*”,end=” “)
print()
”’
* * * * *
* * * *
* * *
* *
*
”’

for j in range(5):
for i in range(j):
print(” “,end=“”)
for i in range(5-j):
print(“*”,end=” “)
print()

”’
Assignment:
*
* *
* * *
* * * *
* * * * *

Solve assignments from the website
”’
## WHILE Loop
”’
WAP to print hello till user says no
”’
while True:
print(“HELLO 1”)
usr_inp=input(“Enter N to stop: “)
if usr_inp.lower()==“n”:
break
print(“====”)
usr_inp=input(“Enter N to stop: “)
while usr_inp.lower() !=‘n’:
print(“HELLO 2”)
usr_inp = input(“Enter N to stop: “)
”’
A company offers dearness allowance (DA) of 40% of basic pay and house
rent allowance (HRA) of 10% of basic pay. Input basic pay of an employee,
calculate his/her DA, HRA and Gross pay (Gross = Basic Pay + DA+ HRA).
a. Modify the above scenario, such that the DA and HRA
percentages are also given as inputs.
b. Update the program such that the program uses a user-defined
function for calculating the Gross pay. The function takes Basic pay,
DA percentage and HRA percentage as inputs and returns the gross pay.
”’
#Case 1
basic_pay = int(input(“Enter your basic pay:”))
da = basic_pay *0.4
hra = basic_pay*0.1
gross_pay = basic_pay + da + hra
print(“Your gross pay for this month is Rs”,gross_pay)

#Case 2
basic_pay = int(input(“Enter your basic pay:”))
da = int(input(“Enter the dearness allowance (%): “))
da = da/100
hra = int(input(“Enter the House rent allowance (%): “))
hra = hra/100
gross_pay = basic_pay + basic_pay*da + basic_pay*hra
print(“Your gross pay for this month is Rs”,gross_pay)
#case 3

# defining a user defined function (udf)
# input taken by the function – passing the value
# and anything returned from the function – function returns the output
def calc_gross_pay(bp,da,hra=10):
hra = hra / 100
da = da / 100
gross_pay = bp + bp * da + bp * hra
return gross_pay


basic_pay = int(input(“Enter your basic pay:”))
da = int(input(“Enter the dearness allowance (%): “))
hra = int(input(“Enter the House rent allowance (%): “))

result = calc_gross_pay(basic_pay,da,hra)
print(“Your gross pay for this month is Rs”,result)

result = calc_gross_pay(basic_pay,da)
print(“Your gross pay with default hra for this month is Rs”,result)

result = calc_gross_pay(da=da,bp=basic_pay,hra=hra)
print(“Your gross pay with non-positional for this month is Rs”,result)

# required positional arguments
# default (non-required)

”’
You have a monthly income of Rs 1100. Your monthly outgoings are as follows.
• Rent – Rs.500
• Food – Rs.300
• Electricity – Rs.40
• Phone – Rs 60
• Cable TV – Rs 30.
Calculate the Monthly Expenses and the remainder (what’s left over each month).
a. Modify the above program by inputting the income as well as values
for expenses and calculate Monthly expense.
b. Include a function to check whether you will have savings or you
have to borrow money based on the monthly income and total expenses.
The function should print an appropriate message for each case.
”’
#case 1
income = 1100
Rent=500
Food=300
Electricity=40
Phone=60
Cable=30
expenses = Rent+Food+Electricity+Phone+Cable
remainder = income-expenses
print(“Your expenses for this month is”,expenses)
print(“You remainder for this month is”,remainder)

#case 2
income = int(input(“Enter your Income:”))
Rent= int(input(“Enter your rent:”))
Food= int(input(“Enter your food expenses:”))
Electricity= int(input(“Enter your Electricity charges:”))
Phone= int(input(“Enter your Phone expenses:”))
Cable= int(input(“Enter your Cable TV expenses:”))
expenses = Rent+Food+Electricity+Phone+Cable
remainder = income-expenses
print(“Your expenses for this month is”,expenses)
print(“You remainder for this month is”,remainder)


# case 3
def check_remainder(income,expenses):
remainder = income-expenses
if remainder<0:
print(f”You need to borrow Rs {remainder} for this month”)
elif remainder>0:
print(f”You have a savings of Rs {remainder} for this month”)
else:
print(“This month you neither have savings nor need to borrow any money”)

income = int(input(“Enter your Income:”))
Rent= int(input(“Enter your rent:”))
Food= int(input(“Enter your food expenses:”))
Electricity= int(input(“Enter your Electricity charges:”))
Phone= int(input(“Enter your Phone expenses:”))
Cable= int(input(“Enter your Cable TV expenses:”))
expenses = Rent+Food+Electricity+Phone+Cable
check_remainder(income,expenses)


########## PRACTICE #################

# defining a user defined function (udf)
# input taken by the function – passing the value
# and anything returned from the function – function returns the output
def calc_gross_pay(n1,n2):
print(“Hi, I am in calc_gross_pay_function”)
total = n1 + n2
#print(total)
return total


val1 = 100
val2 = 150
ret_val = calc_gross_pay(val1,val2) #calling the function pass the value
print(“Value returned from the function is”,ret_val)
val1 = 10
val2 = 50
result = calc_gross_pay(val1,val2) #calling the function pass the value
print(“Value returned from the function is”,result)