print(‘5 + 3 =’, 5+3)
pi = 3.1 # variable
g = 9.8
radius = 15
# area of a circle = pi * r square
# commentsm jhjkhjkhkjhjghg
print(“Area of a circle =”,3.1 * radius * radius)
# Write a program to find area and perimeter of a rectangle by taking length and breadth as input
length = 21
breadth = 38
area = length * breadth
perim = 2 * (length + breadth)
print(“Area of rectangle =”,area)
print(“Perimeter of rectangle =”,perim)
#Write a program to find area and perimeter of a square
side = 35
area = side * side
perim = 4 * side
print(“Area of square =”,area)
print(“Perimeter of square =”,perim)
#Find total and average of five numbers
num1 = 78
num2 = 82
num3 = 79
num4 = 91
num5 = 59
total = num1 + num2 + num3 + num4 + num5
avg = total / 5
print(“Total = “,total,”Average is”,avg)
####
str1 = 'HELLO'
str2 = "I am fine"
str3 = '''Where are you going?
How long will you be here?
What are you going to do?'''
str4 = """I am here
I will be here for next 7 days
I am going to just relax and chill"""
print(type(str1),type(str2),type(str3),type(str4))
print(str1)
print(str2)
print(str3)
print(str4)
# What's you name?
str5 = "What's your name?"
print(str5)
#He asked,"Where are you?"
str6 = 'He asked,"Where are you?"'
print(str6)
#He asked,"What's your name?"
#escape sequence \
print('''He asked,"What's your name?"''')
print("He asked,\"What's your name?\"")
print('nnnnn\nnn\tnn')
print("\FOlder\\newfolder")
# \n is used to print newline in python
print("\\n is used to print newline in python")
# \\n will not print newline in python
print("\\\\n will not print newline in python")
str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")
#indexing
print(str1[2])
print("last element: ",str1[4])
print("last element: ",str1[-1])
print("second element: ",str1[-8])
print("ell: ",str1[1:4])
print("ell: ",str1[-8:-5])
print("First 3: ",str1[:3])
print("First 3: ",str1[:-6])
print("Last 3: ",str1[6:])
print("Last 3: ",str1[-3:])
#Methods - exactly same as your functions - only difference is they are linked to a class
import time
str1 = "HELLO"
print(str1.replace("L","X",1))
sub_str = "LL"
str2 = "HELLO HOW WELL ARE YOU LL"
cnt = str2.find(sub_str)
print("Count = ",cnt)
if cnt<0:
print("Sorry, no matching value hence removing")
else:
print("Value found, now replacing")
for i in range(5):
print(". ",end="")
time.sleep(0.5)
print("\n")
print(str2.replace(sub_str,"OOOO"))
out_res = str2.split("LL")
print("Output Result = ",out_res)
out_str = "LL".join(out_res)
print(out_str)
print(str2.title())
print(str2.lower())
print(str2.upper())
str3 = 'hello how well are you ll'
print(str3.islower())
print(str3.isupper())
num1 = input("Enter a number: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Invaid input")
ename = input("Enter your first name: ")
if ename.isalpha():
print("Your name is being saved...")
else:
print("Invaid name")
#WAP to count of vowels in a sentence
para1 = "Work, family, and endless to-do lists can make it tough to find the time to catch up. But you'll never regret taking a break to chat with your friend, Frost reminds us. Everything else will still be there later."
sum=0
for l in para1:
if l=='a' or l=='A' or l=='e' or l=='E' or l=='i' or l=='I' or l=='o' or l=='O' or l=='u' or l=='3':
sum+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)
COMPLETE THE PYTHON COURSE FROM HERE:
https://www.netacad.com/
Direct course link: https://www.netacad.com/courses/programming/pcap-programming-essentials-python
All videos are available here: https://www.youtube.com/playlist?list=PLF9fJE4vTtTLnXYzr_19r1NVRWuNV892t
For Basic information like installation, software to use, history, refer this link:
Exercise 1: Write a program in Python to display the Factorial of a number.
Exercise 2: Write a Python program to find those numbers which are divisible by 7 and multiples of 5, between 1500 and 2700 (both included).
Exercise 3: Write a Python program to reverse a number.
Exercise 4: Write a program to print n natural number in descending order using a while loop.
Exercise 5: Write a program to display the first 7 multiples of 7.
Exercise 6: Write a Python program to convert temperatures to and from Celsius and Fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f = temperature in fahrenheit ]
Expected Output :
60°C is 140 in Fahrenheit
45°F is 7 in Celsius
Exercise 7: Write a Python program that iterates the integers from 1 to 50. For multiples of three print “Fizz” instead of the number and for multiples of five print “Buzz”. For numbers that are multiples of three and five, print “FizzBuzz”.
Sample Output :
fizzbuzz
1
2
fizz
4
buzz
Exercise 8: Write a Python program to print the alphabet pattern ‘A’.
Expected Output:
***
* *
* *
*****
* *
* *
* *
Exercise 9: Write a Python program to print the alphabet pattern ‘G’.
Expected Output:
***
* *
*
* ***
* *
* *
***
P5.py file:
P6.py:
— Reading all the rows and columns
select * from HR.Employees;
— All the rows but given columns only
Select Employee_ID, FIRST_NAME, EMAIL from HR.Employees;
— Restricted columns and restricted rows
Select Employee_ID, FIRST_NAME, EMAIL from HR.Employees where Employee_ID =120;
select first_name||’ has a salary of $’|| salary “Salary Information” , email from hr.employees order by email;
select first_name||’ has a salary of $’|| salary “Salary Information” , email, HIRE_DATE from hr.employees order by HIRE_DATE, email desc;
select first_name, last_name, email, salary from hr.employees where salary > 10000 and salary <18000;
select first_name, last_name, email, salary from hr.employees where salary between 10000 and 18000;
select first_name, last_name, email, salary from hr.employees where salary in (17000, 11000, 13500);
select count(*) from hr.employees
select avg(salary) from hr.employees
select * from HR.Employees;
select * from hr.departments;
select first_name, last_name, email, to_char(hire_date, ‘Month DD, YYYY’), round(months_between(sysdate, hire_date)) Tenure_in_months from hr.employees;
select * from dual;
select 3+3 from HR.Employees where rownum<2;
select 3+3, abs(-80), to_date(‘May 14, 2023 08:01 P.M.’, ‘Month DD, YYYY HH:MI P.M.’) from dual
select Decode(3+5,8,’CORRECT’,’INCORRECT’) from dual;
— Aggregate functions
select JOB_ID, count(*), round(avg(salary)), round(sum(salary)) TOTAL_SALARY from hr.employees group by JOB_ID having count(*)>=5;
— JOINING TABLES
select FIRST_NAME , LAST_NAME, t1.DEPARTMENT_ID, t2.DEPARTMENT_ID, Department_name, HIRE_DATE from HR.Employees t1, hr.departments t2 where t1.department_id = t2.department_ID;
— SUB QUERY
select * from HR.Employees where Employee_ID in (select employee_id from hr.employees);
select * from HR.Employees where Employee_ID = (select employee_id from hr.employees where rownum < 2);
— SET OPERATIONS
select * from HR.Employees where salary <11000
INTERSECT
select * from HR.Employees where salary >20000
INFERENTIAL STATS:
Predicting for the population from the sample data
Led by probability – an event you are interested in / total possible outcome
1/6
Head/Tail: ½
Discrete and Continuous
Bayes theorem – p (probability of success) & q (probability of failure)
q = 1-p
Probability (1 time event) and Probability distribution (repetition)
Toss coin one after another: Sample Space: TT, HH, TH, HT = 2/4
Toss 2 coins at the same time: Sample Space: TT, HH, TH
#1. Python programming- Python interpreter (python.org)
#2. Data analytics - desriptive stats
#3. Python visualization
#4. Database & SQL (OLTP)
#5. Inferential stats
#6. warehousing (OLAP)
#7. machine learning (using Python)
#8.Visualization using Power BI ====>
#9. Machine learning using R programming
#10. Intro Tableau
# each topic will have a project
#assignments - they will not have code
# go through job description of the jobs you are interested in and put them in an excel
# you X against topics you know
#how to build your resume/profile
###################
# 1. Software to install: Python interpreter from Python.org
# 2. IDE - Integrated Development Environment
## pycharm, vs code, jupyter, colab (online)
print("Hello Everyone",end=". "); #this is comment which will not be executed by Python.
print("wiefsisdkjnsjdosidviosdosdiv");
print("Hello","How are you?","I am fine");print("5+4=",5+4,"another equation: 6+4=",6+4)
# f-string (format string)
print(f"5+4={5+4} another equation: 10/3={10/3:.2f}",end="")
#data type-what kind of value is it? - integer(int), float, complex,string (str), boolean(bool)
print()
var1=5 #<class 'int'>
print(type(var1))
var1="HEllo"
print(type(var1)) #<class 'str'>
var1=5.0 #<class 'float'>
print(type(var1))
var1=5j #<class 'complex'>
print(type(var1))
print(var1 * var1)
#bool
var1 = True #False
print(type(var1))
var1= "true"
print("HELLO")
# 1. INSTALLATION - getting your computer ready
# a. you can practice online at Google Colab (colab.reaserch.google.com)
# b. install all software on your machine -
## i. install Python : python.org and download the version of your choice
## ii. you can program on Python but its very easy to do
## iii. Another software to make it user friendly - IDE
## integrated development environment - you can practice
## eg Pycharm (jetbrains.com), VS Code , Notebooks like Jupyter, etc
print("HELLO", end="\n")
print("Good Morning")
# variables - we variable to store data and use it again and again when we want it
var1 = 5
# single line comment
# integer means - numbers without decimal part- includes _ve , +ve & zero
# type() - it gives the data type of the variable
print(type(var1)) # integer - int
# basic data types in Python- integer, float, string, boolean & complex
# basic = single value
print(var1)
var1 = 5.0 #float
print(type(var1))
var1 = 5+2j
print(type(var1))
print(var1 * var1) # 25 -4 +20j
print(2j * 2j)
var1 = "7890"
print(type(var1)) # str -> string
var2 = '5.4t'
print(var2)
print(type(var2))
#bool -> boolean : True / False
var1 = True
var2 = False
print(type(var1))
### use these values/ variables
# Arithematic operations - input as numbers and output are also numbers
# + - * / // ** %(modulo)
var1 = 14
var2 = 5
print(f"{var1} + {var2} : ",var1 + var2)
print("{var1} + {var2} : ",var1 + var2)
print(f"var1 + var2 : ",var1 + var2)
print(f"{var1} - {var2} : ",var1 - var2)
print(f"{var1} * {var2} : ",var1 * var2)
print(f"{var1} / {var2} : ",var1 / var2)
print(f"{var1} // {var2} : ",var1 // var2) #integer division
print(f"{var1} % {var2} : ",var1 % var2) #remainder from division
print(f"{var1} ** {var2} : ",var1 ** var2) #power- var1 to the power var2
print(f"{var1} ** {var2} : ",var1 * var1* var1*var1*var1)
# round() - round it off to the nearest integer value
### round(5.1) = 5 , round(5.6) = 6
# floor() - rounds it off to the lowest integer value
### floor(5.1) = 5 , floor(5.6) = 5 => similar to integer division
# ceil() - rounds it off to the higher integer value
### ceil(5.1) = 6 , ceil(5.6) = 6
# types of variables (data types) - Basic data types - they can store only one value at a time
var1 = 5 # integer - int
var1 = 5.0 # float
var1 = 5j #complex
var1 = "5" #string - str
var1 = False #boolean - bool
# arithematic operators: + - * / // %(mod) ** (power)
# Comparison operators: numeric as input and output is bool
num1, num2 = 10,20
print(num1, num2)
# > >= <= < == !=
print("num1==10: ",num1==10) # is num1 equal to 10 ?
print("num1!=10: ",num1!=10) # is num1 not equal to 10?
print(num1 > num2)
print(num1 < num2)
print(num1 >= 10)
print(num1 <= num2)
# Logical operators
#input values and output values - are all boolean
#operations = and or not
print("not True: ",not True)
print("not False: ",not False)
# and -> both values have to be True for it to be True else its False
print(True and False)
#tell: I will do this work and that work
#actual: I did only this work
#did I meet my committment ? - NO
# or - both values have to be False to be False otherwise its always True
#tell: I will do this work or that work
#actual: I did both
print("OR = ", True or False)
num1,num2 = 10,20
print("==> ",num1==10 and num1!=10 or num1 > num2 and num1 < num2 or num1 >= 10 or num1 <= num2)
# True
radius = 4
pi = 3.14
area_of_circle = pi * radius**2
circumference = 2 * pi * radius
print("Area of a circle with radius",radius,"is",area_of_circle,"square unit and circumference is",circumference,"unit")
# f - string is for formatting
print(f"Area of a circle with radius {radius} is {area_of_circle} square unit and circumference is {circumference} unit")
# Assignment -
# 1. WAP to find area and perimeter for a square
# 2. WAP to find area and perimeter for a rectangle
# for both the programs, display output is complete message as we have done above with circle.
# to check given number is an odd or even ?
# 5 - odd, 6 - even
num1 = 5
if num1 % 2==0:
print("EVEN Number")
else:
print("ODD Number")
#variables are used to store some values
var1 = 50
var2 = 100
print(var1 + var2)
var1 = 500
var2 = 100
print(var1 + var2)
#Basic
#datatypes: str, int, float, bool, complex
var1 = "HELLO" # str - you have the value in quoation
print(type(var1))
var1 = 100 #without any decimal part - integer(int)
print(type(var1))
var1 = 100.0 #float value
print(type(var1))
var1 = True #bool - False
print(type(var1))
var1 = 5j #complex (python)=imaginary (maths)
var2 = var1 * var1 #implicit conversion into complex since var1 is also complex
print(var2)
print(type(var1))
#
var1 = 100
var2 = 3.5
var3 = var1 + var2 #implicit conversion into float since var2 is a float
print()
str1 = "55"
str1 = int(str1) #explicit conversion
#int(), str(), float(), bool(), complex()
var1 = 0;var1 = bool(var1);print(var1); #False - bool
var1 = "";
var1 = bool(var1);
print(var1) ; #False - bool
len = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
area = len * breadth
print("Area of the rectangle is ",area)
print(f"Rectangle with length = {len} and breadth = {breadth} has an area of {area:.1f}")
player = "Imbababonbeta"
country = "Zimbabwe"
position = "wicket-keeper"
print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")
player = "Rohit"
country = "India"
position = "captain"
print(f"Player {player:<16} plays for {country:^10} and is {position:>15} of the team")
#Player Imbababonbeta plays for Zimbabwe and is wicket-keeper of the team
#Player Rohit plays for India and is captain of the team
########
## OPERATORS
### ARITHMETIC OPERATORS: + - * /
## input values have to be numeric (int, float, complex)
var1 = 50
var2 = 20
print(var1 + var2)
print(var1 - var2)
print(var1 * var2)
print(var1 / var2)
# ** power, 5 ** 4 => 5 * 5 * 5 * 5
print(var1 ** var2) # 50 to the power of 20
# how to find square root of 21 ?
print(21 ** 0.5) #4.58257569495584
#cube root of 21 =
print(21 ** (1/3))
# // - integer division
print(10 / 3)
print("Integer Division = ",10 // 3)
# % Modulo - remainder
#20 / 3 = 6 + 2/3
print(20 % 3)
print(50 % 30) # 20 is remainder
# Comparison operators: compare the values (bigger/smaller)
# input as numeric and output is BOOL
var1 = 15
var2 = 25
print(var1 > var2) #false
#Arithematic operations: + - * / , **, // and % (modulo)
## input as numbers and output was numbers
#Comparison operators: input are the numbers / output - bool
# > >= < <= == !=
val1 = 30
val2 = 40
val3 = 30
print(val1 > val2) #is leftside val greater than rightside value?
print(val1 > val3) #False
print(val1 >= val3) #is val1 greater than or equal to? - True
print(val1 < val2) #
print(val1 <= val3) #
print(val1 == val3) # == is for asking question, are they equal?
print(val1 == val2) #False
print(val1 != val3) #False
print(val1 != val2) #True
#bool operators - Logical operators : Input and Output- bool
#Prediction 1: Sachin and Laxman are going to do this job - F
#Prediction 2: Sachin or Laxman are going to do this job - T
#Actual: Sachin and Rahul did the job
#AND - even one False will make output False
#OR - even one TRUE will make output True
#NOT - opposite
val1 = 30
val2 = 40
val3 = 30
print("==>: ",val1 > val2 or val1 > val3 and val1 >= val3 or
val1 < val2 and val1 <= val3 or val1 == val3 and val1 == val2 or
val1 != val3 or val1 != val2)
#T
#membership operator - in
print(5 in [2,4,5,6,8])
#bitwise operator - works by converting the numbers to boolean
# binary equivalent of 33 ?
print(bin(33)) #0b100001
print(int(0b101111011111))
# and (&) or (|) >> (right shift) << (left shift)
print(22 & 33) #0
print(33 & 22) #0
print(bin(33), bin(22))
## 33 = 100001
## 22 = 010110
## (&) 000000
## (|) 110111
print(int(0b110111)) #55
print(33 | 22) # 55
##
print(55 >>2)
# 55 = 110111 >> 1 = 11011 >> 1 = 1101
print(int(0b1101)) #13
print(55 << 2) # 110111 << 1 = 1101110 << 1 = 11011100
###
# if - checking conditions
val1 = 30
if val1 > 0:
print("Value is positive")
print("Positive Positive Positive")
print("Thank you for using my program")
# 300 pts
## ? 300
print("You win")
print("You lose")
print("Tied")
#TUPLE - immutable version of List
str1 = "hello"
str2 = 'Good evening' \
'How are you?'
str3 = '''Hello there
hope you are doing good
we shall meet soon'''
str4 = """I am fine
how are you"""
print(str2)
print(str3)
print(type(str1))
#functions (global) v methods (belong to a class)
str1 = "hello"
print(str1.islower())
print(str1.isupper())
#isdigit()
val1 = input("Enter length of the rectangle: ")
if val1.isdigit():
val1 = int(val1)
print(val1)
else:
print("Sorry, this is not a valid number")
name1 = "Sachin Tendulkar"
print(name1.isalpha())
txt1 = "hello@123"
print(txt1.isalnum())
###
str1 = "HellOOO how are YOU?"
print(str1.lower())
#### Build a game - guessing number ####
import random
num = 55
attempt = 0
low,high = 1,100
while True:
#guess = int(input("Enter the number: "))
guess = random.randint(low, high)
attempt+=1
if guess ==num:
print(f"You got it in {attempt} attempts!")
break
elif guess > num:
print(f"Hint: Your value {guess} is higher")
high=guess-1
else:
print(f"Hint: Your value {guess} is lower")
low=guess+1
str1 = "Hello"
print(str1[-1] , str1[len(str1)-1])
print(str1[1])
print("Length = ",len(str1))
# range(a,b,c) - a=initial value, b = ending value, c=increment
# range(2,14,3) - 2,5,8,11
print(str1[0:4], str1[:4])
print(str1[-5:-1], str1[:-1])
# llo
print(str1[2:5], str1[2:])
print(str1[-3:])
vowel_count = 0
str1 = "This is a Sample STATEMENT to test"
for i in str1:
#print("Hello: ",i)
if i in 'aeiouAEOIU':
vowel_count+=1
print(f"Total vowels in '{str1}' is {vowel_count}")
# strings are immutable
str1 = "Hello"
str1=str1[0]+'E'+str1[2:]
print("New str1 = ", str1)
str2 = "This is a Sample STATEMENT to test"
str3="This,is,a,sample,text2,work,on,it"
output1 = str2.split()
output1 = str3.split(',')
print(output1)
print(str2)
print("Index: ",str2.index('i',3,len(str2)))
str4='abcd abc ab a'
#find all indices of b
tot = str4.count('ab')
print("Total bs = ",tot)
srt = 0
for i in range(3):
print(str4.index('ab',srt))
srt=str4.index('ab',srt)+1
### LIST: linear ordered mutable collection
l1 = []
print(type(l1))
l1=[3,"Hello",False,5.0, [2,4,6]]
l1.append(45)
#collection - stores multiple values with single variable name
#List, Tuple, Dictionary and Set
#List - linear collection
l1 = [5,"Hello",False,[4,8,12]]
print(type(l1)) #<class 'list'>
#accessing (similar to strings)
print(l1[1][0])
print(type(l1[1]))
print(l1[-1][1])
l2 = [5.6,"Good Evening"]
print(l1+l2)
print(l2 * 3)
l3=[-1]*10
print(l3)
for i in l1:
print(i)
for i in range(len(l1)):
print(l1[i])
l4=[]
#read the value from the user and if its number only then add to this list
val1 = input("Enter a number: ")
if val1.isdigit():
l4.append(int(val1))
print("After first step, L4 looks like: ",l4)
l5 = []
l5.append(100)
l5.append(200)
l5.insert(1,300) # takes- pos, value
l5.insert(1,400)
print("After addition: ",l5)
l5.pop(2) #input as position(index)
l5.remove(200) #takes values as input
print(l5)
### Stack & Queue ##
## Stack - LIFO data structure
stack=[]
while True:
print("Enter your options: ")
print("1. Display Your Stack")
print("2. Add a member to the stack")
print("3. Remove a member from the stack")
print("4. Exit")
ch=input("Choice : ")
if ch=="1":
print("Content of the stack is:\n",stack)
elif ch=="2":
pass
elif ch=="3":
pass
elif ch=="4":
break
else:
print("Sorry I dont understand you, try again!")
# Queue: First element added is the first one to go - FIFO (First In First Out)
l6 = [100,200,300,400,100,200,300,100,200,100]
print(l6.index(100)) #element
print(l6.index(100, 2)) # element with start position
print(l6.index(100, 5,8)) # element with start and end pos
print("count = ",l6.count(200))
#Deep and Shallow copy
l7 = l6 #Deep copy - 2 names for same set of values
l8 = l6.copy() #creates a duplicate copy -
print("1. L6 = ",l6)
print("1. L7 = ",l7)
print("1. L8 = ",l8)
l6.append(500)
l7.append(600)
l8.append(700)
print("2. L6 = ",l6)
print("2. L7 = ",l7)
print("2. L8 = ",l8)
# list is linear ordered mutable collection
l6[0] = 110 #edit the value unlike string
print(l6)
l7 = [2,4,6,8,10]
print(l6+l7) #l6 and l7 retains original values
l6.extend(l7) #l6 will get l7 values
print(l6)
print("Before Reverse: ",l6)
l6.reverse()
print("After Reverse: ",l6)
l6.sort()
print("After Sort: ",l6)
l6.sort(reverse=True)
print("After Reverse Sort: ",l6)
l6.clear()
print("Last: ",l6)
str1 = "HELLO HOW ARE YOU"
print(str1.split())
print(str1) #didnt change as it is immutable
l6.append(66)
print(l6) #existing list got changed as it is mutable
#Sequential search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
num = 10
count_num=0
count_index = []
for i in range(len(list1)):
if list1[i]==num:
count_num+=1
count_index.append(i)
print(f"Number of values = {count_num} and indices are: {count_index}")
# Binary Search
list1 = [12,14,8,6,10,20,4,10,16,18,2]
list1.sort()
num = 22
first = 0
last = len(list1)-1
isFound = False
while True:
mid = (first+last) // 2
if list1[mid] ==num:
isFound = True
break
elif list1[mid] <num:
first = mid+1
else:
last = mid-1
if first> last:
break
if isFound:
print("Number is in the list")
else:
print("Number is not in the list")
Q_LIST = ["What is 1+3? (a) 4 (b) 8 (c) 2 (d) 10",
"What is 4+3? (a) 5 (b) 7 (c) 12 (d) 16",
"What is 4*3? (a) 6 (b) 8 (c) 12 (d) 16"]
A_LIST = ["A","B","C"]
import random
q_no = random.randint(0,2)
print("Let's play the Quiz!")
print(Q_LIST[q_no])
inp=input("Your answer please (select a/b/c/d) : ")
if inp.upper() ==A_LIST[q_no]:
print("Congratulations! You win")
else:
print("Sorry, thats not right")
### input: 29 3 2023 output: 29th March 2023
months= ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
date_ending = ['st','nd','rd']+17*['th']+['st','nd','rd'] + 7*['th']+['st']
month_val = 3
print(months[3-1])
date = 21
print(str(date)+date_ending[date-1])
#Tuple - linear ordered immutable collection
t1 = ()
print("type 1 = ",type(t1), len(t1))
t1 = (1,)
print("type 1 = ",type(t1), len(t1))
t1 = (1,2,3,4,1,2,3,1,2,1) #packcing
print("type 1 = ",type(t1), len(t1))
print("4th member - ", t1[3])
print("2s = ",t1.count(2))
print("Position of 3 = ",t1.index(3))
t2 = (2,4,6,8)
a,b,c,d = t2 #unpacking
print(c,d,b,a)
# you can convert tuple to list and list to tuple
t2 = list(t2)
t2 = tuple(t2)
# Tuple like String, is immutable
#advantage is - working with Tuples is faster than reading through a list
##### DICTIONARY
# Dictionary - mutable collection of key-value pair
d1 = {}
print(type(d1))
d1 = {"Advait":[45,34,89,81],"Saurav":[12,42,23,44]}
print(d1["Advait"])
d2 = {False: 45,45:"Cricket","Name": "Sachin",10:"Zeeeero"}
# dictionary should have unique keys
print(d2)
d2.update(d1)
print("After Update: ", d2)
print("Only Keys = ",d2.keys())
print("Only Values = ",d2.values())
print("Only Items = ",d2.items())
for j in d2.keys():
print(j," = " ,d2[j])
print("Printing Items: ")
for i,j in d2.items():
print("Key:",i," & Value: ",j)
# to remove: pop(), popitem()
#popitem removes the last updated KEY (not value)
d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor"}
print("D3 = ",d3)
d3.popitem()
print("After Popitem: ",d3)
d3 ={1:"Hello",2:"Hola",3:"Namaste",4:"Bon Jor",1:"Good Morning"}
print("D3 = ",d3)
d3.popitem()
print("2. After Popitem: ",d3)
d3.pop(1)
print("1. After Pop = ",d3)
actors = {"David":32,"Tim":42,"Rebecca":21,"Mary":45}
male = {"David":"LA","Tim":"NY"}
female = {"Rebecca":"SD","Mary":"WS"}
# David who is a male of 32 years lives in LA
for name in actors.keys():
print_sentence=name +" who is a "
for male_city in male.keys():
if name==male_city:
print_sentence+="male of "+str(actors[name]) +" years lives in "+ male[name]
for female_city in female.keys():
if name==female_city:
print_sentence+="female of "+str(actors[name]) +" years lives in "+ female[name]
print(print_sentence)
# SET - sets - linear unordered mutable collection - doesnt allow duplicate
set1 = {'Apple','Grapes','Banana','Orange'}
print(type(set1))
set1.add('Cherry')
set2 = {"Pineapple","Mango","Apple","Orange"}
# two ways to remove
set1.remove("Banana")
set1.discard("Apple")
#set1.remove("Rose") - if value isnt there throws error
set1.discard("Rose") #doesnt throw error
print("1. Set1: ",set1)
set1.pop()
set1.update(set2) #union
print("2. Set1: ",set1)
set1.clear()
print("3. Set1: ",set1)
### SET FUNCTIONS ####
set1 = {'Apple','Grapes','Banana','Orange'}
set2 = {"Pineapple","Mango","Apple","Orange"}
#UNION
print("UNION")
print(set1 | set2)
print(set1.union(set2))
print("INTERSECTION")
print(set1 & set2)
print(set1.intersection(set2))
print("DIFFERENCE")
print(set1 - set2)
print(set1.difference(set2))
print(set2 - set1)
print(set2.difference(set1))
print("SYMMETRIC DIFFERENCE")
print(set1 ^ set2)
print(set2 ^ set1)
print(set1.symmetric_difference(set2))
#update() will update the values of main set
# set1.union(set2) - this gives a new set as output
# set1.update(set2) - set1 is updated with the values
# union - update()
set1.update(set2)
print(set1)
# intersection: intersection_update()
set1.intersection_update(set2)
print(set1)
# difference_update()
set1.difference_update(set2)
print(set1)
#symmetric_difference_update()
set1.symmetric_difference_update(set2)
print(set1)
# set, list, tuple => they are inter-convertible
list1 = [3,6,9,12,3,6,9,3,6,3]
list1 = list(set(list1))
print(list1)
set1 = {'Apple','Grapes','Banana','Orange'}
set1 = list(set1)
set1.index("Grapes")
set1 = set(set1)
set1 = tuple(set1)
set1 = set(set1)
print(set1.issubset(set2))
#
list1 = [3,6,9,12,3,6,9,3,6,3]
list2 = [3,6,9,12,15]
#does all the elements of list2 present in list1?
t_list1 =set(list1)
if set(list1).issuperset(set(list2)):
print("yes, list2 value exists in list1")
else:
print("No, list2 has additional elements")
# Session on MODULES
#Create a python file with name p2.py and paste below programs there
#Run below programs from different file
########################
####
str1 = 'HELLO'
str2 = "I am fine"
str3 = '''Where are you going?
How long will you be here?
What are you going to do?'''
str4 = """I am here
I will be here for next 7 days
I am going to just relax and chill"""
print(type(str1),type(str2),type(str3),type(str4))
print(str1)
print(str2)
print(str3)
print(str4)
# What's you name?
str5 = "What's your name?"
print(str5)
#He asked,"Where are you?"
str6 = 'He asked,"Where are you?"'
print(str6)
#He asked,"What's your name?"
#escape sequence \
print('''He asked,"What's your name?"''')
print("He asked,\"What's your name?\"")
print('nnnnn\nnn\tnn')
print("\FOlder\\newfolder")
# \n is used to print newline in python
print("\\n is used to print newline in python")
# \\n will not print newline in python
print("\\\\n will not print newline in python")
str1 = "Hello You"
str2 = "There"
print(str1 + str2)
print(str1 *5)
for i in str1:
print("Hello")
#indexing
print(str1[2])
print("last element: ",str1[4])
print("last element: ",str1[-1])
print("second element: ",str1[-8])
print("ell: ",str1[1:4])
print("ell: ",str1[-8:-5])
print("First 3: ",str1[:3])
print("First 3: ",str1[:-6])
print("Last 3: ",str1[6:])
print("Last 3: ",str1[-3:])
#Methods - exactly same as your functions - only difference is they are linked to a class
import time
str1 = "HELLO"
print(str1.replace("L","X",1))
sub_str = "LL"
str2 = "HELLO HOW WELL ARE YOU LL"
cnt = str2.find(sub_str)
print("Count = ",cnt)
if cnt<0:
print("Sorry, no matching value hence removing")
else:
print("Value found, now replacing")
for i in range(5):
print(". ",end="")
time.sleep(0.5)
print("\n")
print(str2.replace(sub_str,"OOOO"))
out_res = str2.split("LL")
print("Output Result = ",out_res)
out_str = "LL".join(out_res)
print(out_str)
print(str2.title())
print(str2.lower())
print(str2.upper())
str3 = 'hello how well are you ll'
print(str3.islower())
print(str3.isupper())
num1 = input("Enter a number: ")
if num1.isdigit():
num1 = int(num1)
else:
print("Invaid input")
ename = input("Enter your first name: ")
if ename.isalpha():
print("Your name is being saved...")
else:
print("Invaid name")
#WAP to count of vowels in a sentence
para1 = "Work, family, and endless to-do lists can make it tough to find the time to catch up. But you'll never regret taking a break to chat with your friend, Frost reminds us. Everything else will still be there later."
sum=0
for l in para1:
if l=='a' or l=='A' or l=='e' or l=='E' or l=='i' or l=='I' or l=='o' or l=='O' or l=='u' or l=='3':
sum+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l=='a' or l=='e' or l=='i' or l=='o' or l=='u':
sum+=1
print("Total vowesl = ",sum)
sum=0
for l in para1.lower():
if l in 'aeiou':
sum+=1
print("Total vowesl = ",sum)
########## LIST
#LIST
#collection of linear ordered items
list1 = [1,2,3,4,5]
print(type(list1))
print("Size = ",len(list1))
print(list1[0])
print(list1[-1])
print(list1[3])
print(list1[:3])
print(list1[-3:])
print(list1[1:4])
for i in list1:
print(i)
print([2,3,4]+[6,4,9])
print([2,3,4]*3)
str2 = "A B C D A B C A B A "
print(str2.count("D"))
print(list1.count(3))
l1 = [2,4,6,8]
print(l1.append(12))
print(l1)
l1[0]=10
print(l1)
l1.insert(2,15)
print(l1)
# Queue: FIFO
# Stack: LIFO
if 16 in l1:
l1.remove(16) #takes in value to remove
l1.remove(15)
print(l1)
l1.pop(1) #index
print(l1)
#################
while False:
print("Queue is: ",l1)
print("1. Add\n2. Remove\n3. Exit")
ch=input("Enter your choice: ")
if ch=="1":
val = input("Enter the value: ")
l1.append(val)
elif ch=="2":
l1.pop(0)
elif ch=="3":
break
else:
print("Try again!")
while False:
print("Stack is: ",l1)
print("1. Add\n2. Remove\n3. Exit")
ch=input("Enter your choice: ")
if ch=="1":
val = input("Enter the value: ")
l1.append(val)
elif ch=="2":
l1.pop(-1)
elif ch=="3":
break
else:
print("Try again!")
l2 = l1 #they become same
l3 = l1.copy()
print("1. List1 = ",l1)
print("1. List2 = ",l2)
print("1. List3 = ",l3)
l1.append(33)
l2.append(44)
l3.append(55)
print("2. List1 = ",l1)
print("2. List2 = ",l2)
print("2. List3 = ",l3)
l1.extend(l3)
print(l1)
print(l1.count(6))
sum=0
marks=[]
for i in range(3):
m = int(input("Enter marks in subject "+str(i+1)+": "))
marks.append(m)
sum+=m
print("Sum is ",sum, "and average is ",sum/3)
print("Marks obtained is ",marks)
#THREE STUDENTS AND THREE SUBJECTS:
allmarks=[]
for j in range(3):
sum=0
marks=[]
for i in range(3):
m = int(input("Enter marks in subject "+str(i+1)+": "))
marks.append(m)
sum+=m
print("Sum is ",sum, "and average is ",sum/3)
print("Marks obtained is ",marks)
allmarks.append(marks)
print("All the marks are: ",allmarks)
# All the marks are: [[88, 66, 77], [99, 44, 66], [44, 99, 88]]
# find the highest marks of each subject
#Tuple - linear order immutable collection
#strings are also immutable
tuple1 = (1,3,1,4,1,5,1,6)
print(type(tuple1))
print(len(tuple1))
print(tuple1.count(1))
print(tuple1.index(4))
print(tuple1[2])
for i in tuple1:
print(i)
t1 = list(tuple1)
t1.append(55)
t1=tuple(t1)
t2 = (2,4,6,8) #packing
#unpacking
a,b,c,d,e = t2
print(a,b,c,d)
#packing
print('hello')
print(5 +3 )
print('5+3=', 5+3)
var1 = 53
print(type(var1)) #<class 'int'> integer
var1 = '53' # str - string
print(type(var1))
var1 = 53.0 #float
print(type(var1))
var1 = 53j #complex
print(type(var1))
var1 = False #
print(type(var1))
count_of_pens = 23 #variable names can only have alphabets, numbers, _
#variable shouldnt begin with a number
cost_each_pen = 21.23
total_cost = cost_each_pen \
* count_of_pens
print('Cost of each pen is',cost_each_pen,"so for",count_of_pens,"pens, "
"total cost would be",total_cost)
#f-string format string
print(f"Cost of each pen is {cost_each_pen} so for {count_of_pens} pens, total cost would be {total_cost:.1f}")
###################
player= "Rohit"
country = "India"
position = "Captain"
print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")
player= "Mbangawapo"
country = "Zimbabwe"
position = "Wicketkeeper"
print(f"The Player {player:<15} plays for the country {country:^15} and is {position:>15} of the team")
num1 = 5
num2 = 3
#Arithematic Operations
print(num1 + num2)
print(num1 - num2)
print(num1 * num2)
print(num1 / num2) #float output
print(num1 // num2) #integer division (double division)- integer (int)
print(num1 % num2) #remainder - modulo
print(num1 ** num2) #num1 to the power num2
#post office stamp problem for assignment
length = input("Enter length of the rectangle: ")
length = int(length)
print(type(length))
breadth = int(input("Enter breadth of the rectangle: "))
area = length * breadth
perimeter = 2*(length + breadth)
print(f"The rectangle with length {length} and bread {breadth} has an area of {area} and perimeter of {perimeter}")
#Comparison operators: < > <= >= == !=
#input here is variables, output is always bool value
val1=34
val2=34
print("Is val1 less than val2? ", val1 < val2)
print("Is val1 greater than val2? ", val1 > val2)
print("Is val1 less than or equal to val2? ", val1 <= val2)
print("Is val1 greater than or equal to val2? ", val1 >= val2)
print("Is val1 equal to val2? ", val1 == val2)
print("Is val1 not equal to val2? ", val1 != val2)
#Logical operators: and or not: Input is bool and output is also bool
print(val1 < val2 and val1 > val2 or val1 <= val2 and val1 >= val2 and val1 == val2 or val1 != val2)
#in AND - even if you have one false - o/p is False otherwise True
# in OR - even if you have one True - o/p is True otherwise False
print(not val1==val2)
#membership operator: in, not in
print( 5 in [5,10,15,20])
print("a" not in "ABCDE")
marks1 = int(input("Enter the marks in subject 1: "))
marks2 = int(input("Enter the marks in subject 2: "))
marks3 = int(input("Enter the marks in subject 3: "))
total = marks1 + marks2 + marks3
avg = total / 3
print(f"Total marks obtained is {total} and the average is {avg:.2f}")
#Conditional
num1 = -90
if num1 >0:
print("Number is positive")
print("This is second line of if")
if num1 >0:
print("Number is positive")
else:
print("Number is not positive")
if num1 >0:
print("Number is positive")
elif num1 <0:
print("Number is negative")
else:
print("Its Zero")
avg = 80
'''
avg >= 90: Grade A, 80-90: B, 70-80: C, 60-70: D, 50-60:E, 40-50: F and Grade Failed <40
'''
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")
elif avg>=40:
print("Grade: F")
else:
print("Grade: FAILED")
if avg>=40:
print("You have passed")
#print - You have passed for all those who got over 40%
avg=99.1
if avg>=40:
print("You have passed")
if avg >= 90:
print("Grade: A")
if avg >=95:
print("You win President's medal")
if avg>=99:
print("WOW")
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")
else:
print("Grade: FAILED")
#to evaluate an algorithm - we look at Space complexity and Time complexity
# President medal for >95%
num1 = 78
if num1%2==0:
print("Even")
else:
print("Odd")
age=21
nationality = "USA"
if age>21 and nationality=="USA":
print("Vote")
####### LOOPS - repeatition
# for loop: exactly how manytimes to run the loop
# while loop: condition under which to repeat the loop
# range(a,b,c): a= initial value (including), b=end value (excluding), c= increment
#range(3,12,3): 3,6,9
#range(3,13,3): 3,6,9,12
for i in range(3,16,3):
print("HELLO")
print("i = ",i)
for i in range(5):
print("*",end=' ')
print()
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=' ')
print()
'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(j+1):
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(5-j-1):
print(" ",end='')
for k in range(j+1):
print("*",end=' ')
print()
n=5
m=1
for j in range(1,11):
for i in range(1,11):
print(f"{i:>2} * {j:>2} = {j*i:>3}",end=" ")
print()
#### WHILE Loops: no fixed times - based on some condition
i=1
while i<=10:
print(i)
i+=1
#print hello untill user wants
ch='y'
while ch=='y':
print("HELLO")
ch=input("Press y to continue, anyother key to stop: ")
import random
num = random.randint(1,100)
print("==> ",num)
l1="="
total_attempts,max,min=0,0,9999
n=250000
pc = n//100
for i in range(n):
attempt = 0
while True:
guess = int(input("Guess the number: "))
#guess = random.randint(1,100)
attempt +=1 # attempt = attempt + 1
if guess ==num:
print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")
total_attempts +=attempt
if min > attempt:
min = attempt
if max < attempt:
max = attempt
if i%pc==0:
print(i//pc,"% Completed")
break
elif guess > num:
print("Sorry, Actual number is smaller")
else: #guess < num:
#pass
print("Sorry, Actual number is greater")
print("Average number of attempts it took: ",total_attempts/n)
print("Maximum attempt:",max," and minimum attempt:",min)
#########################
######### Attempt 2 ##
import random
#print("==> ",num)
l1="="
total_attempts,max,min=0,0,9999
n=250000
pc = n//100
num = random.randint(1, 100)
for i in range(n):
attempt = 0
start, end = 1, 100
while True:
#guess = int(input("Guess the number: "))
guess = random.randint(start,end)
if guess>100 or guess <1:
continue #takes you to the beginning of the loop
attempt +=1 # attempt = attempt + 1
if guess ==num:
#print(f"Congratulations! You have guessed it correctly in {attempt} attempts.")
total_attempts +=attempt
if min > attempt:
min = attempt
if max < attempt:
max = attempt
if i%pc==0:
print(i//pc,"% Completed")
break
elif guess > num:
#print("Sorry, Actual number is smaller")
end=guess-1
else: #guess < num:
#pass
#print("Sorry, Actual number is greater")
start =guess+1
print("Average number of attempts it took: ",total_attempts/n)
print("Maximum attempt:",max," and minimum attempt:",min)
#Strings
str1 = 'Hello'
str2 = "How are you?"
str3 = """I am fine
I am great
I am amazing"""
str4 = '''I am here'''
print(str3)
print("What's your name?")
print('What\'s your name?')
print(str1 + " "+str2)
print(str1 *5)
for i in str1:
print("Hello")
#subset of the string
str6 = "What's your name?"
print(str6[0])
print(str6[2])
print(len(str6))
print(str6[len(str6) - 1]) #last char
print(str6[len(str6) - 2]) #2nd last char
print(str6[- 1]) #last char
print(str6[- 2]) #2nd last char
print(str6[-len(str6)])
print(str6[:3])
print(str6[-3:])
### Methods
print(str6.index("W"))
str1 = 'How are YOU I AM fine'
#they are immutable - you cant edit them
#str1[0] = 'h' #TypeError: 'str' object does not support item assignment
str1 = 'h'+str1[1:]
print(str1)
#functions are independent - print(), len(), input(), int(), str()
#methods - they are functions written within a class
print(str1.isdigit())
val1 = str(5)#input("Enter a number: ")
if val1.isdigit():
val1 = int(val1)
else:
print("Invalid number! setting val1 to zero")
val1 = 0
print(val1)
str2="Hello123"
print(str2.isalnum())
print(str1.upper()) #isupper()
print(str1.lower())
print(str1.title())
print(str1)
print(str1.split("o")) #default split is done on blank space
l1 = str1.split()
str2 = "|| ||".join(l1)
print(str2)
str3 = "Ioooamooofineooohowoooareoooyouooo?"
str4 = " ".join(str3.split("ooo"))
print(str4)
occ = str3.find("ooo")
print("Occurences = ",occ)
occ = str3.count("ooo")
print("Occurences = ",occ)
start,end=0,len(str3)
for i in range(occ):
po = str3.index('ooo',start,end)
print(po,end=" , ")
start = po+1
print()
# LIST
l1 = []
print(type(l1))
print(len(l1))
l1 = [4,"Hello",8.0,True,[2,4,5],"Fine"]
print(type(l1))
print(len(l1))
print(len(l1[4]))
print(l1[4][1])
#list is mutable (unlike str)
l1[0]= 444
print(l1)
print(l1+l1)
print(l1 *3)
for i in l1[4]:
print(i)
#list methods
#Tuple - immutable version list
t1 = (2,2,4,6,8,10) #packing
a,b,c,d,e,f = t1
#print(a,b,c,d,e,f)
print(type(t1))
print(len(t1))
for i in t1:
print(i," - ",t1)
print(t1[-2:])
#t1[2] = 88
print(t1.index(8))
print(t1.count(2))
t1= list(t1)
t1.append(18)
t1=tuple(t1)
a=(5,88,1,77,99)
b=(5,88,1,77,99)
if a>b:
print(a)
elif b>a:
print(b)
else:
print("both are same")
# List - linear ordered collection
l1=[4,6,8,10,12,8,10,12,8,0,8]
l1.append(55) #add element at the end
print(l1)
l1.insert(3,90)
l1.insert(3,70)
print("2. ",l1)
#
element = 12
if element in l1:
l1.remove(12)
else:
print("Element doesnt exist")
if l1.count(element)<1:
print("Element doesnt exist")
print()
print("3. ",l1)
l1.pop(3)
print("4. ",l1)
print(l1.index(8))
s,e=0,len(l1)
for i in range(l1.count(8)):
inx = l1.index(8,s,e)
print(inx,end=", ")
s=inx+1
print()
print("5. ",l1)
#copy
l2 = l1 #deep copy - (giving another name)
l3 = l1.copy() #shallow copy (photocopy)
print("After copy")
print("L1 = ",l1)
print("L2 = ",l2)
print("L3 = ",l3)
l1.append(101)
l2.append(102)
l3.append(103)
print("After editing")
print("L1 = ",l1)
print("L2 = ",l2)
print("L3 = ",l3)
l1.reverse()
print("Reverse: ",l1)
l1.sort()
print("Sort: ",l1)
l1.sort(reverse=True)
print("Sort R: ",l1)
#stack - LIFO: add using append, remove: pop(-1)
#queue - FIFO: append, pop(0)
# 1,5,8,9,7
#add 5 numbers from the user
sum=0
nums=[]
for i in range(5):
num = int(input("Enter the number: "))
sum+=num
nums.append(num)
print("Sum is ",sum)
print("Printing values: ",nums)
# [[a,b,c],[x,y,z],[p,q,r]]
master_list = []
for i in range(3):
temp=[]
for j in range(3):
m=int(input("Enter the marks: "))
temp.append(m)
master_list.append(temp)
print("Master list: \n",master_list)
'''
Assignment: Exten the above program to find highest marks for each subject and for
each students. Eg if the marks are: [[66, 77, 88], [98, 87, 76], [45, 65, 76]]
Highest for subject 1 = 98
2 = 87
3 = 88
Highest for Student 1 = 88
2 = 98
3 = 76
'''
# Dictionary - key:value
dict1 = {:,:, :,:}printtype
(dict1[])print
"Hello""Hola"
(dict1)
#deep copy
#shallow copy
(dict1.keys())print
(dict1.items())
i dict1.keys(): (i, dict1[i])
a,b dict1.items(): (a,b)
k dict1.items(): (k)
stats = {:[,,,],:[,,,],:[,,,]}for in
if "Virat"
dict3.pop()
#Sets
#data structures - collections: String, List, Tuple, Dictionary
#SETS - A B M O C - there is no order
# doesnt allow duplicate
set1 = {2,4,6,8}
print(set1)
#union intersection minus
set2 = {6,8,10,12}
#union
print(set1.union(set2))
print(set1 | set2)
#intersection
print(set1.intersection(set2))
print(set1 & set2)
#difference
print(set1.difference(set2))
print(set1 - set2)
print(set2.difference(set1))
print(set2 - set1)
#symmetric difference
#union of 2 differences
print(set1.symmetric_difference(set2))
print(set1 ^ set2)
print(set1, set2)
#update doesnt give new set, it changes the main set
set1.update(set2)
#union -> update
# {intersection_update, difference_update, symm_diff_update}
print(set1, set2)
set3 = {2,4,10,12}
# sets to list and to tuple
set1 = tuple(set1)
list(set1)
set()
print("HELLO")
# 1. INSTALLATION - getting your computer ready
# a. you can practice online at Google Colab (colab.reaserch.google.com)
# b. install all software on your machine -
## i. install Python : python.org and download the version of your choice
## ii. you can program on Python but its very easy to do
## iii. Another software to make it user friendly - IDE
## integrated development environment - you can practice
## eg Pycharm (jetbrains.com), VS Code , Notebooks like Jupyter, etc
print("Hello how are you?")
print('uyuyuiiugiub7y7 7t6t6vt87tovtotff87yvpyv')
print(5+11)
print('5+11=',5+11)
num1 = 5 #num1 are called variables
num2 = 11 #variable names are case sensitive, name should not start with a digit
#alphabets, numbers and underscore(_) - only these are allowed
print(num1 + num2)
var1 = 5
var2 = 5.0
var3 = "Hello"
var4 = True
var5 = 5j
#arithmetic operations
var1 = 15
var2 = 4
print(var1 + var2) #8
print(var1 - var2) #
print(var1 * var2)
print(var1 / var2)
print(var1 // var2) #integer divison, the integer part of the divison
print(var1 % var2) #modulo - remainder
print(var1 ** var2)
# a,b = 30,6 30 % 20
#Comparison operators: is ?? and answer will be bool
var1 = 15
var2 = 4
var3 = 15
print(var1 > var2)
print(var1 >= var3) #is it greater than or equal to
print(var1 < var2)
print(var2 <= var3)
print(var1 == var2)
print(var1 != var2)
#logical operators: input and output both are bool
#and, or, not
print(var1 == var2 and var1 != var2)
print(False and False) #False
print(False and True) #False
print(True and False) #False
print(True and True) # True
print(False or False) #False
print(False or True) #True
print(True or False) #True
print(True or True) # True
var1 = 15
var2 = 4
var3 = 15
print(var1 > var2 and var1 >= var3 or var1 < var2 or var2 <= var3 and var1 == var2 and var1 != var2)
#T or F
print("Hello \nHow are you \nI am fine thank you")
# \n is for newline
print("\\n is for newline")
print("\\\\n is for newline")
print("Hello",end=" ")
print("How are you",end=" ")
print("I am fine thank you",end="\n")
#Conditional statements
num1=0
if num1 > 0:
print("Positive")
print("This is a positive number")
print("my 3rd line for positive number")
elif num1 < 0:
print("Negative")
print("This is a negative number")
print("my 3rd line for negative number")
else:
print("Its neither positive or nagtive")
print("Thank you for using IF")
num1 = int(input("Enter a number to be tested: "))
if num1 %3==0:
print("Its divisible by 3")
else:
print("Its not divisible by 3")
avg = 89
if avg>=50:
print("Result: Pass")
#85: Grade A, 75> Grade B, >60: C, > 50-D
if avg>=85:
print("Grade: A")
if avg>=90:
print("Please collect your merit certificate!")
if avg>=95:
print("You win President's medal")
elif avg>=75:
print("Grade: B")
elif avg>=60:
print("Grade: C")
else:
print("Grade: D")
else:
print("Result: Fail")
# a & b=> which is greater
a=45
b=95
if a>b:
print("A is greater than B")
elif b>a:
print("B is greater than A")
else:
print("They are equal")
#Assignment: take three numbers a,b,c and arrange them in increasing order without using any inbuilt function.
[Hint: Build on the last example shared]
#INPUT: a,b,c=20,60,30
#OUPUT: 20,30,60 (increasing order)
a,b,c=80,60,30
# a>b, b>c => clear
# a>b, c>b => wrote additional code to find
#b>a,
a, b, c=50,30,30 #increasing order
if a<b:
#print (f"{b} {a}")
if c<b: #b is greatest
if a<c:
print(f"{a}, {c}, {b}")
else:
print(f"{c}, {a}, {b}")
else: #c is greatest
print (f"{a}, {b}, {c}")
else: #b<a
if c<b: #b is greatest
print(f"{c}, {b}, {a}")
else: #b is lowest
if a<c:
print (f"{b}, {a}, {c}")
else:
print(f"{b}, {c}, {a}")
# 30<50=50
# LOOPS - repeation
#FOR loop - when we know exactly how many times to execute
### Range(a,b,c): generates values from a (inclusive) to b (exclusive) at steps of c
# range(2,12,3): 2,5,8,11
# range(3,12,3): 3,6,9
# range(6,10): a&b. c is default 1:
#range(5): b & a,c are deafult 0 and 1 respectively => 0,1,2,3,4
for i in range(5):
print("Hello",i)
for i in range(3,12,3):
print("Hi there", i)
for i in range(2,12,3):
print("Hello there", i)
print()
for i in range(5):
print("*",end=" ")
print()
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()
#While Loop = based on condition- executes till its True
#print("Hello")
# loops - for & while
## For loop is used when you know exactly how many times to run the loop
for i in range(2,10,2):
print("* ",i)
print("-------------")
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for j in range(5):
for i in range(5):
print("*",end=" ")
print()
print("-------------")
for i in range(5):
print("* "*5)
print("-------------")
'''
*
* *
* * *
* * * *
* * * * *
'''
for j in range(5):
for i in range(j+1):
print("*",end=" ")
print()
print("-------------")
'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for i in range(5-j):
print("*",end=" ")
print()
print("-------------")
'''
* * * * *
* * * *
* * *
* *
*
'''
for j in range(5):
for x in range(j):
print(" ",end="")
for i in range(5-j):
print("*",end=" ")
print()
print("--- Assignment ----------")
'''
*
* *
* * *
* * * *
* * * * *
'''
#WHILE
i=0
while i<5:
print("hello")
i+=1
print("Thank you")
cont='y'
while cont=='y' or cont=='Y':
print("Ok, printing some values...")
cont = input("Do you want to continue? (y for yes)")
cont='y'
while cont=='y' or cont=='Y':
sum=0
for i in range(3):
marks = int(input("Enter the marks: "))
sum+=marks
print("Total marks is",sum,"and average is",sum/3)
cont = input("Do you want to continue? (y for yes)")
import turtle
#screen = turtle.getscreen()
plot = turtle.Turtle() #creates screen
screen = turtle.Screen()
turtle.Screen().bgcolor("yellow")
plot.forward(100)
turtle.color("red")
plot.right(90)
plot.forward(100)
plot.right(90)
plot.forward(100)
plot.right(90)
plot.forward(100)
##
plot.right(45)
plot.forward(100)
plot.right(45)
plot.forward(100)
plot.right(135)
plot.forward(100)
plot.right(45)
plot.forward(100)
plot.backward(100)
plot.left(45)
plot.backward(100)
plot.left(45)
plot.forward(100)
plot.right(45)
plot.forward(100)
## circle
plot.circle(50)
width = screen.window_width()
height = screen.window_height()
plot.penup()
plot.goto(width/2,height/2)
plot.pendown()
plot.dot(30,"red")
turtle.mainloop() #keep displaying the screen
# Forward, Backward, Left, Right
#When the value is = to 16 and you want to add 5, you add 5 units to 16
num1 = 18
num2 = 5
num3 = num1 + num2
num4 = num1 * num2
num5 = num1 / num2
num6 = num1 - num2
# 3 square + 4 square + 5 square + 6 square + 7 square
num1 = 3
num2 = 4
num3 = 5
num4 = 6
num5 = 7
result = num1 * num1 + num2*num2 + num3*num3 + num4*num4 + num5*num5
print ("Final result = ",result)
#read 2 values from the user and display val1 square + val2 square
val1 = input("Enter val1: ")
val1 = int(val1)
val2 = int(input("Enter val2: "))
#when you read using input by default values are of type string
print("Type = ", type(val1))
print("Result=", val1*val1+val2*val2)
#solve: 2x.x + 9x - 5 = 0
# 1. Calculate Descriminant: b.b - 4.a.c = 81+40=121
# 2. Root of D = 121 ** 0.5 = +/- 11
# 3. x = (-b +/-D) / 2.a = (a) (-9+11)/4 = 0.5 (b) (-9-11)/4 = -5
print("Solving a quadratic equation for x:")
a=4
b=2
c=-6
D = b**2 - 4*a*c
print("Finding Discriminant = ",D)
if D==0:
print("This equation has only 1 solution and x = ",(-b/(2*a)))
elif D<0:
print("This equation has imaginary solution")
else:
sol1 = (-b+D**0.5)/(2*a)
sol2 = (-b - D ** 0.5) / (2 * a)
print(f"Solutions are: {sol1} and {sol2}")
## x.x + 4.5x - 2.5 = 0 / (x+p)(x+q): p.q = -2.5 and p+q = 4.5
#If the number given divides into 2 whole numbers, then it is even. If it is divided by two and it is a decimal or fraction, then it is odd.
#If the number is divided by 5 and the value is a whole number, than it is a multiple of 5
# if <> - elif <> - else
num = -35
if num>0:
print("Its positive")
print("Its inside num > 0 condition")
else:
print("Its not positive")
print("What else")
print("This is another statement")
# In a block (only IF, IF-ELSE or IF-ELIF-ELSE)
num2 = -10
if num2==0:
print("Its zero")
elif num2<0:
print("Its negative")
else:
print("Its positive")
# WAP to check if a number is odd or even (I will do now)
#Modify the above program to give a message is number is less than 0
# Msg - "Invalid number
num3 = -11
if num3 %2==0:
print("Its even number")
else:
print("Its odd number")
var1 = 5 #let’s take a variable called var1 and make it equal to 5
# number without decimal point – integer
#var1 is a variable of type integer
print(“var1”)
print(var1)
print(type(var1))
var1 = 5.0 #float – -inf to +inf with decimal point
print(type(var1))
var1 = 5j #complex (imaginary) – i
# square root of -25 = sq rt(25* -1) = 5j
print(type(var1))
print(5j * 5j)
# string – text (str)
var1 = “hello”
print(type(var1))
#5th basic data types – bool (boolean – 2 values: True / False)
var1 = True
print(type(var1))
#Functions for explicit conversion – convert data from given type to this:
# int(), float(), complex(), str(), bool()
var1 = int(“5”)
print(type(var1))
quantity =49
cost_pc = 51.89
total_cost = quantity * cost_pc
print(“Total quantity bought is”,quantity,”each one at a cost of”,cost_pc,”so the total cost is”,total_cost)
print(f”Total quantity bought is {quantity} each one at a cost of {cost_pc:.1f} so the total cost is {total_cost}”)
pl=”Rohit”
cn=”India”
pos=”captain”
print(f”Player {pl:<12} plays for {cn:^12} and is {pos:>20} of the team!”)
pl=”Mabwange”
cn=”Zimbabwe”
pos=”Wicket-keeper”
print(f”Player {pl:<12} plays for {cn:^12} and is {pos:>20} of the team!”)
num1 = int(input(“Enter first number to be added: “)) #default input will read as str
print(type(num1))
num2 = int(input(“Enter second number to be added: “))
print(type(num2))
print(num1+num2)