print("Our doggie")
print(' o----,')
print(' ||||')
print("r"*10)
price=10
print(price)
price=20
print(price)
#Hospital : Using different datatyypes
name="John Smith"
age=45
weight=62.7
is_new_patient=True
print(name+"\n"+str(age)+"\n"+str(weight)+"\n"+str(is_new_patient))
#Getting input
#the input function always recieve input as string
name=input("Enter your name: ")
print("Hello " +name)
clr=input("What is your favourite color: ")
print(name+"'s favourite color is "+clr)
#type conversion
b_yr=input("Enter your birth year: ")
print("your age is "+str(2024-(int(b_yr))))
weight=input("Enter your weight in lbs: ")
print("Weight is "+str(int(weight)*.454)+" in pounds") #a number of
decimal places is found
#passages
email='''
Hi python,
This is my first day exploring you!
Thank you <3'''
print(email)
#Indeces
email='''Hi python,
This is my first day exploring you!
Thank you <3'''
print(email[5])
print(email[11:46])
print(email[-1])
print(email[3:]) #assumes end index as end of string
print(email[:8]) #assumes start index as zero, to 7th character
print(email[:]) #assumes 0 to end
new_email=email #or new_email=email[:] ....duplicating strings
print(new_email)
print(email[1:-1]) #displays from index 1 to before index -1
#Formatted strings
first="Gresham"
second="John"
msg=f'{first} {second} is a programmer' #formatted string : {} is a place
holder
print(msg)
#string methods
a="Are you having fun learning python"
print(len(a)) #len() is a general purpose function just like print(),
#its not a string method to be precise and ain't confined to strings
a="Are you having fun learning python"
# dot operator is used
print([Link]()) #To upper case
print([Link]()) #To lower case
print([Link]()) #To capitalize first letter
print([Link]()) #To title form
print([Link]()) #strip white space
print([Link]()) #strip white space from left
print([Link]()) #strip white space from right
print([Link]("n","d")) #repalcing a character
print([Link]("fun","pain")) #repalcing a word
print([Link]("g")) #index of first occurrence of a
character,returns -1 if the character is not found
print([Link]("fun")) #index of first occurrence of a word
print([Link]("g")) #number of occurrences of a character
print([Link]("fun")) #number of occurrences of a word
print([Link]("g")) #index of first occurrence of a word and throws
error if absent
print("fun" in a) #in operator is used to determine if something is present
in the [Link] a boolean value
#Arithmetic operators
print(5+3)
print(2*4)
print(10-2)
print(17/2)
print(2**3) #Exponent
print(20//3) #Quotient
print(8%3) #Remainder
#OPERATOR PRECEDENCE
#paranthesis
#exponentiation
#multiplication/Division
#addition/Subtraction
#Math functions
print(abs(34-120))
print(round(7.8))
import math
print([Link](4))
print([Link](2.3))
print([Link](2.3))
print([Link](5))
print([Link](5,4))
#First program with if and else
p=input("Price of the property:")
good_credit=False
if good_credit:
print("Price is "+str(int(p)-0.1*int(p)))
else:
print("Price is "+str(int(p)-0.2*int(p)))
#OR
p=input("Price of the property:")
good_credit=False
if good_credit:
price=int(p)-0.1*int(p) #10% discount
else:
price=int(p)-0.2*int(p) #20% discount
print(f"price to be paid is Rs.{price}")
#logical operators
#people with better credits and no criminal background is eligible
good_credit=False
criminal_bg=False
if good_credit and not criminal_bg:
print("Eligible")
else:
print("Not eligible")
#Comparison operator
name=input("Enter the name:")
n=len(name)
if n<3:
print("Should be atleast 3 characters long")
name=input("Enter the name:")
elif n>50:
print("Can't be more than 50 characters long")
name=input("Enter the name:")
else:
print("Name looks good!")
#Weight converter
weight=float(input("Enter the weight:"))
n=input("K or L:")
if [Link]()=="K": #Now its not case sensitive
print("Weight is "+str(weight/.454)+" pounds.")
else:
print("Weight is "+str(weight*.454)+" kilograms.")
#while loops
n=int(input("Enter the value:"))
guess_count=0
while guess_count<n:
print(guess_count+1)
guess_count+=1 #prints 1 to n
print("Done!")
#Guessing game
secret=9
guess_count=1
guess_limit=3
while guess_count<=guess_limit:
s=int(input("Enter the secret number:"))
if s==secret:
print("You won!")
break #breaks the while loop and program ends
else:
print("No :(")
guess_count+=1
else: #applies if the while loop has completed execution and control jumps
out
print("you failed :(")
#Car game
is_start=False
print("Welcome to the race!!!")
while True:
command=input("->").lower()
if command=="help":
print('''start:To start the car\nstop:To stop the car\nquit:To quit the
game\n''')
elif command=="start":
if is_start:
print("The car is already running__")
else:
is_start=True
print("The car has started!__ready to go!!")
elif command=="stop":
if is_start:
is_start=False
print("The car has stopped")
else:
print("The car is already stopped!")
elif [Link]()=="quit":
print("exited!!")
break
else:
print("Oops! I dont understand")
#for loops
for item in 'stephy':
print(item) #Over a string
for item in [3,5,"john","mary",6]:
print(item) #Over a list
for item in range(10):
print(item) #range() function prints 0 to 9
for item in range(35,45):
print(item) #prints 35 to 44
for item in range(35,55,2):
print(item) #jumps by two items in the range
sum=0
prices=[45,32,20,10]
for item in prices:
sum+=int(item)
print(f"Total price is {sum}")
#nested loop
for a in range(3):
for b in range(2):
print(f'({a}, {b})')
#printing an F
lis=[7,2,7,2,2]
for i in lis:
print("f"*i)
#OR how to do it in the correct(complicated ) way
lis=[6,2,6,2,2]
for z in lis: #loop goes through each value in list
out="" #out is an empty string
for y in range(z): #for each value n in list,y goes through 0 to n
out+="x" #for each y append an x to out
print(out) #print the out after finishing each of the inner loops
#list
names=["Joy","Bob","Casey","Ashlin","Clin"]
[Link]()
print(names) #prints the list
print(names[:])
print(names[0:3])
print(names[:2])
print(names[1:])
print(names[3])
names[1]="David"
print(names)
#Sum of items in list
prices=[34,67,31,98,45,20]
largest=prices[0]
for i in prices:
if i>largest:
largest=i
print(f'largest is {largest}')
#Matrix or 2D list
#List of lists
matrix=[[1,2,3], [4,5,6], [6,7,8]]
print(matrix)
print(matrix[0])
print(matrix[2][0])
matrix[2][0]=9
print(matrix[2][0])
#Traversal through 2D list
matrix=[[1,2,3], [4,5,6], [6,7,8]]
for row in matrix:
for item in row:
print(item)
#List methods
marks=[2,7,5,3,9]
[Link](5)
print(marks)
[Link](4,2)
print(marks)
[Link]()
print(marks)
[Link](9)
print(marks)
[Link]()
print(marks)
[Link]()
print(marks)
print([Link](5))
print([Link](5))
[Link]()
print(marks)
#sort() followed by reverse() will give descending order
print(20 in marks)
marks=[2,7,5,3,9]
print([Link](9))
newmarks=[Link]() #Further changes in the old list won't reflect in the
new list
print(newmarks)
#Removing duplicate items in list
names=["B","C","B","C","D","E","F","G","H","I","J","H","L","M"]
uniq=[] #an empty list is created
for name in names: #for each name in the list
if name not in uniq: #check if it is present in uniq
[Link](name) #if not present,add it
print(uniq) #print the uniq list
#tuples
#permanent list(immutable)
score=(9,5,11,3,2,11,"a")
print([Link](11))
print([Link](3))
print(score)
print(score[4])
#Unpacking
coordinates=(2,3,4)
(x,y,z)=coordinates #The coordinates are unpacked into three variables
#same as setting x=coordinates[0],y=coordinates[1],z=coordinates[2]
print(x,y)
length=[9,14,5,10]
(a,b,c,d)=length
print(a)
#Dictionary
#keyvalues should be unique
dicty={
"name":"Gresham john",
"age":"18",
"street_no":23
}
print(dicty["name"])
#print(dict["name","age"]) Generates error
#print(dict["birthdate"]) Generates error
print([Link]("street_no"))
print([Link]("birthdate")) #returns none,won't generate error
print([Link]("birthdate","24th dec 2014")) #prints the birth date
dicty["name"]="Daniel" #update existing
dicty["birthdate"]="24th dec 2014" #adding new
print(dicty)
#phone number program
ph=input("Enter phone:")
log={
"0":"Zero",
"1":"One",
"2":"Two",
"3":"Three",
"4":"Four",
"5":"Five",
"6":"Six",
"7":"Seven",
"8":"Eight",
"9":"Nine"}
out=""
for item in ph:
out+=[Link](item,"!")+" " #print ! if item not in list
print(out)
#imogi converter
#functions
#greetmessage
def greet_msg():
print("Hello,welcome home!")
print("please keep your feet clean!")
print("You're home")
greet_msg()
#the same with a parameter
def greet_msg(name):
print(f"Hello,{name} welcome home!")
print("please keep your feet clean!")
print("You're home")
name=input("Please enter your name:")
greet_msg(name)
#Parameters are placeholders for passing value in a function whereas
#arguments are the actual values passed to it.
#multiple arguments can be passed.
#eg:
def greet_msg(f_name,l_name):
print(f"Hello,{f_name} {l_name}, welcome home!")
print("please keep your feet clean!")
print("You're home")
f_name=input("Please enter your first name:")
l_name=input("Please enter your last name:")
greet_msg(f_name,l_name) #POSITIONAL arguments
def greet_msg(f_name,l_name):
print(f"Hello {f_name} {l_name}, welcome home!")
print("please keep your feet clean!")
print("You're home")
name1="Gresham"
name2="Vargheese"
greet_msg(f_name=name1,l_name=name2) #KEYWORD arguments
#if both positional and keyword arguments are to be passed into the same
function,
#positional arguments always comes first;
func_name("p_argument",key=k_argument)
#returning values
def sqr(number):
return int(number)**2
n=input("Enter the number:")
result=sqr(n)
print(result)
#or
print(sqr(n))
#all functions will return "None" by default
#exit code 0 :program is executed successfully
#exit code !=0: program crashed
#Error handling
#try
try:
age=int(input("Enter age:"))#Anything other than an integer entered will
raise an error
print(age)
except ValueError:
print("Invalid value") #The error is handled without crashing the
program
#Zero division error
try:
age=int(input("Enter age:"))
income=100000
tax=income/age
print(age)
print(tax)
except ZeroDivisionError:
print("Age cannot be zero")
except ValueError:
print("Invalid value")
#Classes are used to define new datatypes
#Methods for the new datatype can be defined inside the class definition
#Class is a template from which any number of objects can be created
#Objects are instances of a class
#Each of the objects can have attributes
class point:
def draw(self):
print("Draw")
def move(self):
print("Move")
point1=point() #creating an object
[Link]() #Calling defined methods over the object
[Link]()
point1.x=10 #defining attributes to objects
point1.y=20
print(point1.x,point1.y)