0% found this document useful (0 votes)
9 views

Example Programs 11

This document contains code snippets and output demonstrating the use of various Python numeric, string, list, tuple, and conditional operations. It includes examples of using the math, base64, and other modules. The numeric operations calculate values like absolute, ceil, floor, exponent, logarithm, max, min, etc. of input numbers. String operations demonstrate methods like capitalize, center, count, endswith, find, isalpha, lower, upper, etc. List examples show append, count, index, insert, pop, remove, sort, etc. Tuples code calculates length, max, min, and converts a list to a tuple. IF/ELSE conditional blocks check for equality and output messages.

Uploaded by

ANUPAMA Ponnu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Example Programs 11

This document contains code snippets and output demonstrating the use of various Python numeric, string, list, tuple, and conditional operations. It includes examples of using the math, base64, and other modules. The numeric operations calculate values like absolute, ceil, floor, exponent, logarithm, max, min, etc. of input numbers. String operations demonstrate methods like capitalize, center, count, endswith, find, isalpha, lower, upper, etc. List examples show append, count, index, insert, pop, remove, sort, etc. Tuples code calculates length, max, min, and converts a list to a tuple. IF/ELSE conditional blocks check for equality and output messages.

Uploaded by

ANUPAMA Ponnu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

##NUMBERS EXAMPLE

expnumbers1.py
import math
n1=int(input("Enter first number"))
n2=eval(input("Enter second number"))
# The eval() method parses the expression passed to it and runs python expression(code) within the
program.
x=4
y=64
a=abs(n2)
c=math.ceil(n2)
#cm=cmp(n1,n2)
e=math.exp(x)
f=math.fabs(n2)
fl=math.floor(n2)
l=math.log(x)
lt=math.log10(x)
ma=max(1,2,3,4,5,6,7,8,9)
mi=min(0,1,2,3,4,5,6,-7,-10)
mo=math.modf(n1)
mo2=math.modf(n2)
p=pow(n1,x)
r=round(n2,3)
s=math.sqrt(y)
print("absolute value of %f is %d"%(n2,a))
print("ceil value of %f is %d"%(n2,c))
#print("compared value of %d,%f is %d"%(n1,n2,cm))
print("exponent value of %d is %d"%(x,e))
print("absolute value of %f is %d"%(n2,f))
print("floor of %f is %d"%(n2,fl))
print("Natural logarithm of %d is %d"%(x,l))
print("base 10 logarithm of %d is %d"%(x,lt))
print("maximum of given numbers is %d"%ma)
print("minimum of given numbers is %d"%mi)
print("modulo of n1 is %d",mo)
print("modulo of n2 is %d",mo2)
print(" %d power of %d is %d"%(n1,x,p))
print("rounding of %f is %d"%(n2,r))
print("square root of %d is %d"%(y,s))
OUTPUT:
Enter first number10
Enter second number20.45
absolute value of 20.450000 is 20
ceil value of 20.450000 is 21
exponent value of 4 is 54
absolute value of 20.450000 is 20
floor of 20.450000 is 20
Natural logarithm of 4 is 1
base 10 logarithm of 4 is 0
maximum of given numbers is 9
minimum of given numbers is -10
modulo of n1 is %d (0.0, 10.0)
modulo of n2 is %d (0.4499999999999993, 20.0)
10 power of 4 is 10000
rounding of 20.450000 is 20
square root of 64 is 8
##STRINGS EXAMPLE
##STRINGS EXAMPLE
expstrings1.py
from codecs import encode
import base64
s1=input("Enter first string in lower case: ")
s2=input("Enter second string: ")
s3 = input("Enter a string with some numberic value: ")
s4=input("Enter a string in upper case: ")
s5=input("Enter a string with first letter capitalized: ")#like 'This Is String Example....Wow!!'
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print("Capitalized form of %s is %s"%(s1,s1.capitalize()))
print ("s1.center(40, 'a') : ", s1.center(40, 'a'))
sub = 'i'
print ("s1.count('exam', 10, 40) : ", s1.count(sub,10,40))
suffix='!!'
print (s1.endswith(suffix))
print (s1.endswith(suffix,20))
suffix='exam'
print (s1.endswith(suffix))
print (s1.endswith(suffix, 0, 19))
print (s1.find(s2))
print (s1.find(s2, 10))
print (s1.find(s2, 40))
print ("s3 is isalnum: ",s3.isalnum())

print ("s3 is isalpha: ",s3.isalnum())

print ("s2 is isalpha: ",s2.isalpha())

print ("s1 is isdigit: ",s1.isdigit())


print ("s4 is islower: ",s4.islower())

print ("s1 is islower: ",s1.islower())

print ("s4 is isupper: ",s4.isupper())

print ("s1 is isupper: ",s1.isupper())

print ("s5 is istitle: ",s5.istitle())

print ("s1 is istitle: ",s1.istitle())

print ("joined result: ",s.join( seq ))


print ("Length of the string: ", len(s1))
print ("s4 in lower: ",s4.lower())
print ("s1.upper : ",s1.upper())
es= base64.b64encode(s1.encode('utf-8',errors = 'strict'))
print("Encoded String: ",es)
ds= base64.b64decode(es.decode('utf-8',errors = 'strict'))

print("Decoded String: ",ds)


OUTPUT
Enter first string in lower case: hi hello gprec welcome!!
Enter second string: gprec
Enter a string with some numberic value: gprec2017
Enter a string in upper case: HI HELLO GPREC WELCOME!!
Enter a string with first letter capitalized: Hi Hello Gprec Welcome!!
Capitalized form of hi hello gprec welcome!! is Hi hello gprec welcome!!
s1.center(40, 'a') : aaaaaaaahi hello gprec welcome!!aaaaaaaa
s1.count('exam', 10, 40) : 0
True
True
False
False
9
-1
-1
s3 is isalnum: True

s3 is isalpha: True

s2 is isalpha: True

s1 is isdigit: False

s4 is islower: False

s1 is islower: True

s4 is isupper: True

s1 is isupper: False

s5 is istitle: True

s1 is istitle: False

joined result: a-b-c

Length of the string: 24


s4 in lower: hi hello gprec welcome!!
s1.upper : HI HELLO GPREC WELCOME!!
Encoded String: b'aGkgaGVsbG8gZ3ByZWMgd2VsY29tZSEh'
Decoded String: b’ hi hello gprec welcome!!
##STRING EXAMPLE2
expstrings2.py
from codecs import encode
import base64
s1='this is string example....wow!!'
s2='exam'
s3 = "this2016"
s4='THIS IS STRING EXAMPLE....WOW!!'
s5='This Is String Example....Wow!!'
s = "-"
seq = ("a", "b", "c") # This is sequence of strings.
print("Capitalized form of %s is %s"%(s1,s1.capitalize()))
print ("s1.center(40, 'a') : ", s1.center(40, 'a'))
sub = 'i'
print ("s1.count('exam', 10, 40) : ", s1.count(sub,10,40))
suffix='!!'
print (s1.endswith(suffix))
print (s1.endswith(suffix,20))
suffix='exam'
print (s1.endswith(suffix))
print (s1.endswith(suffix, 0, 19))
print (s1.find(s2))
print (s1.find(s2, 10))
print (s1.find(s2, 40))
print ("s3 is isalnum: ",s3.isalnum())

print ("s3 is isalpha: ",s3.isalnum())

print ("s2 is isalpha: ",s2.isalpha())

print ("s1 is isdigit: ",s1.isdigit())

print ("s4 is islower: ",s4.islower())

print ("s1 is islower: ",s1.islower())

print ("s4 is isupper: ",s4.isupper())

print ("s1 is isupper: ",s1.isupper())

print ("s5 is istitle: ",s5.istitle())

print ("s1 is istitle: ",s1.istitle())

print ("joined result: ",s.join( seq ))


print ("Length of the string: ", len(s1))
print ("s4 in lower: ",s4.lower())
print ("s1.upper : ",s1.upper())
es= base64.b64encode(s1.encode('utf-8',errors = 'strict'))
print("Encoded String: ",es)
ds= base64.b64decode(es.decode('utf-8',errors = 'strict'))

print("Decoded String: ",ds)

OUTPUT
Capitalized form of this is string example....wow!! is This is string example....wow!!

s1.center(40, 'a') : aaaathis is string example....wow!!aaaaa

s1.count('exam', 10, 40) : 1

True

True

False

True

15
15

-1

s3 is isalnum: True

s3 is isalpha: True

s2 is isalpha: True

s1 is isdigit: False

s4 is islower: False

s1 is islower: True

s4 is isupper: True

s1 is isupper: False

s5 is istitle: True

s1 is istitle: False

joined result: a-b-c

Length of the string: 31

s4 in lower: this is string example....wow!!

s1.upper : THIS IS STRING EXAMPLE....WOW!!

Encoded String: b'dGhpcyBpcyBzdHJpbmcgZXhhbXBsZS4uLi53b3chIQ=='

Decoded String: b'this is string example....wow!!'


##LISTS
Explists2.py
import math
#list1 = ['physics', 'chemistry','maths','social','chemistry']
#list2 = [1, 2, 3]
list1=[]
n=int(input("Enter the size of list1"))
for i in range(n):
list1.append(input("Enter the item"))
print("current item:",list1)
list2=[]
m=int(input("Enter the size of list2"))
for i in range(m):
list2.append(input("Enter the item"))
print("current item:",list2)

str="Hello World"

#print(cmp(list1, list2))#depricated from python3


print (len(list2))
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
print ("min value element : ", min(list1))
print ("min value element : ", min(list2))
print ("List elements : ", list(list1))#using list() function
list3=list(str)
print ("List elements : ", list3)
list1.append('C#')
print ("updated list : ", list1)
print ("Count for chemistry: ", list1.count('chemistry'))
print ('Index of chemistry', list1.index('chemistry'))
print ('Index of C#', list1.index('C#'))
list1.insert(2, 'Biology')#inserting new item to the list
print ('Final list : ', list1)
for i in range(1):
list1.remove(input("Enter the item to remove from list1"))
print("current item:",list1)
"""list1.remove('maths')
print ("list after removing maths : ", list1)"""
list1.sort()
print ("list after sorting : ", list1)
list1.reverse()
print ("list after reversing : ", list1)
list1.extend(list2)
print ('Extended List :', list1)
list1.pop()
print ("list after poping : ", list1)
list1.pop(1)
print ("list after poping item from index 1: ", list1)
OUTPUT
Enter the size of list13
Enter the itempython
Enter the itemchemistry
Enter the itemc
current item: ['python ', 'chemistry', 'c']
Enter the size of list24
Enter the item1
Enter the item2
Enter the item3
Enter the item4
current item: ['1', '2', '3', '4']
4
Max value element : python
Max value element : 4
min value element : c
min value element : 1
List elements : ['python ', 'chemistry', 'c']
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
updated list : ['python ', 'chemistry', 'c', 'C#']
Count for chemistry: 1
Index of chemistry 1
Index of C# 3
Final list : ['python ', 'chemistry', 'Biology', 'c', 'C#']
Enter the item to remove from list1chemistry
current item: ['python ', 'Biology', 'c', 'C#']
list after sorting : ['Biology', 'C#', 'c', 'python ']
list after reversing : ['python ', 'c', 'C#', 'Biology']
Extended List : ['python ', 'c', 'C#', 'Biology', '1', '2', '3', '4']
list after poping : ['python ', 'c', 'C#', 'Biology', '1', '2', '3']
list after poping item from index 1: ['python ', 'C#', 'Biology', '1', '2', '3']

##TUPLES EXAMPLE
exptuples1.py
tuple1 = ('physics', 'chemistry')
tuple2 = (1, 2, 3, 4, 5, 6, 7 )
list1= ['maths', 'che', 'phy', 'bio']
#print(cmp(tuple1, tuple2)) #cmp() has been depricated from python3
print ("Length of First tuple: ", len(tuple1))
print ("Length ofSecond tuple : ", len(tuple2))
print ("Max value element : ", max(tuple1))
print ("Max value element : ", max(tuple2))
print ("min value element : ", min(tuple1))
print ("min value element : ", min(tuple2))

tuple3=tuple(list1)
print ("tuple3 elements : ", tuple3)
OUTPUT
Length of First tuple: 2
Length ofSecond tuple : 7
Max value element : physics
Max value element : 7
min value element : chemistry
min value element : 1
tuple3 elements : ('maths', 'che', 'phy', 'bio')
##IF
firstif.py
v1=input("Enter the value of v1: ")
if(int(v1)==10):
print("the value of v1 is: ",v1)
print("in first if")
v2=input("Enter the value of v2: ")
if(int(v2)==100):
print("the value of v2 is: ",v2)
print("in second if")
OUTPUT:
>>>
Enter the value of v1: 10
the value of v1 is: 10
in first if
Enter the value of v2: 100
the value of v2 is: 100
in second if

##1. IF ELSE
exnested.py
a=input("Enter the value for a: ")
b=input("Enter the value for b: ")
c=input("Enter the value for c: ")
if(a>b):
if(a>c):
print("a is larger than b and c")
else:
print("c is larger than a and b")
else:
if(b>c):
print("b is larger than a and c")
else:
print("c is larger a and b")

OUTPUT:
Enter the value for a: 3
Enter the value for b: 4
Enter the value for c: 5
c is larger a and b
>>>
Enter the value for a: 0
Enter the value for b: 6
Enter the value for c: 2
b is larger than a and c
##2. IF ELSE
nestedifex.py
age = int(input(" Please Enter Your Age Here: "))
if age < 18:
print(" You are Minor ")
print(" You are not Eligible to Work ")
else:
if age >= 18 and age <= 60:
print(" You are Eligible to Work ")
print(" Please fill in your details and apply")
else:
print(" You are too old to work as per the Government rules")
print(" Please Collect your pension!")

OUTPUT:
>>>
Please Enter Your Age Here: 13
You are Minor
You are not Eligible to Work
>>>
Please Enter Your Age Here: 20
You are Eligible to Work
Please fill in your details and apply
>>>
Please Enter Your Age Here: 65
You are too old to work as per the Government rules
Please Collect your pension!

##IF..ELIF..ELSE
fourif.py
a=input("Enter value for a: ")
if(int(a)<20):
print("a is less than 20")
if(int(a)==15):
print("a is 15")
elif(int(a)==10):
print("a is 10")
elif(int(a)==5):
print("a is 5")
elif(int(a)<5):
print("a is less than 5")
else:
print("a is greater than 15 and less than 20")
else:
print("a is greater than 20")
OUTPUT:>>> Enter value for a: 15
a is less than 20
a is 15
>>>
Enter value for a: 10
a is less than 20
a is 10>>>
Enter value for a: 5
a is less than 20
a is 5
>>>
Enter value for a: 22
a is greater than 20

## 1.FOR
factorial.py
a=[1,2,3,4,5]
#n=int(input("Enter the value of n"))
for i in range(5):
#a.append(input("Enter the %d item:"%i))
#for i in range(n):
f=1
for fact in range(1,a[i]):
f*=fact
fact+=1
print("factorial is %d is %d:"%(i,f))
OUTPUT:>>> factorial is 0 is 1
factorial is 1 is 1
factorial is 2 is 2
factorial is 3 is 6
factorial is 4 is 24

OR

Factorial of a single number

n = eval(input("Please enter a whole number: "))


fact = 1
for factor in range(n,1,-1):
fact = fact * factor
print("The factorial of", n, "is", fact)

OUTPUT

Please enter a whole number: 5


The factorial of 5 is 120

##2.FOR
firstfor.py
for letter in 'PYTHON':
print("Current letter: ",letter)
fruits=['banana','apple','grapes','mango','melon']
for fruit in fruits:
print("current fruit: ",fruit)
OUTPUT:

>>>
Current letter: P
Current letter: Y
Current letter: T
Current letter: H
Current letter: O
Current letter: N
current fruit: banana
current fruit: apple
current fruit: grapes
current fruit: mango
current fruit: melon

##FOR ELSE

Write example using for else

##1.WHILE
firstwhile.py
count=0
while(count<5):
print(count,"is less than 5")
count+=1
else:
print(count,"is not less than 5")
OUTPUT:
>>>
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

## WHILE ELSE

secondwhile.py

reversedNumber = 0
n=input("Enter an integer: ")
while(int(n)>0):
remainder =int(n)%10
reversedNumber = reversedNumber*10 + remainder
n = int(n)/10;
print("Reversed Number = ", reversedNumber)
else:
print("reverse of a number is not possible")

OUTPUT:

Enter an integer: 134


Reversed Number = 4
Reversed Number = 43
Reversed Number = 431
reverse of a number is not possible
>>>
Enter an integer: -2
reverse of a number is not possible

##FUNCTIONS WITH NESTED IF

nestediffun.py

# menu() function prints the main menu, and prompts for a choice
def menu():
#print what options you have
print("Welcome to calculator in Python")
print("your options are:")
print(" ")
print("1) Addition")
print("2) Subtraction")
print("3) Multiplication")
print("4) Division")
print("5) Quit calculator")
print(" ")
return int(input("Choose your option: "))

# this adds two numbers given


def add(a,b):
print(a, "+", b, "=", a + b)

# this subtracts two numbers given


def sub(a,b):
print(b, "-", a, "=", b - a)

# this multiplies two numbers given


def mul(a,b):
print(a, "*", b, "=", a * b)

# this divides two numbers given


def div(a,b):
print(a, "/", b, "=", a / b)

# NOW THE PROGRAM STARTS, AS CODE IS RUN


loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add(int(input("Add this: ")),int(input("to this: ")))
elif choice == 2:
sub(int(input("Subtract this: ")),int(input("from this: ")))
elif choice == 3:
mul(int(input("Multiply this: ")),int(input("by this: ")))
elif choice == 4:
div(int(input("Divide this: ")),int(input("by this: ")))
elif choice == 5:
loop = 0

print("Thankyou for using calculator!")

OUTPUT:
Welcome to calculator in Python
your options are:

1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Quit calculator

Choose your option: 1


Add this: 2
to this: 3
2+3=5
Welcome to calculator in Python
your options are:

1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Quit calculator

Choose your option: 2


Subtract this: 3
from this: 2
2 - 3 = -1
Welcome to calculator in Python
your options are:

1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Quit calculator

Choose your option: 3


Multiply this: 3
by this: 4
3 * 4 = 12
Welcome to calculator in Python
your options are:

1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Quit calculator

Choose your option: 4


Divide this: 10
by this: 2
10 / 2 = 5
Welcome to calculator in Python
your options are:

1) Addition
2) Subtraction
3) Multiplication
4) Division
5) Quit calculator

Choose your option: 5


Thankyou for using calculator!

Expdict1.py

d1={}
n=int(input("Enter the size of dictionary"))
for i in range(n):
key=input("Enter the key to be added:")#d1 = {'Name': 'Zara', 'Age': 7}
value=input("Enter the value for the key to be added:")
d1.update({key:value})
print("dictionary d1 is:")
print(d1)
print("Length of d1 is: ",len(d1))
print("Equivalent String of d1: %s" % str (d1))

d2 = {'Name': 'Mahnaz', 'Branch': 'ece','Section':'c'}


#print("Comaprision of d1 and d2",cmp(d1,d2))#Removed from Python3

print("Variable Type : %s" % type (d1))


print("Length of d2 before clear: %d" % len(d2))
d2.clear()
print("Length of d2 after clear : %d" % len(d2))

d3=d1.copy()
print("New dictionary after copied: %s"%str(d3))

seq = ('name', 'branch', 'section')


d4 = dict.fromkeys(seq, 10)
print("New Dictionary after using fromkeys : %s" % str(d4))

print("Value retrieved after using get : %s" % d1.get('branch'))


#default − This is the Value to be returned in case key does not exist
print("Value : %s" % d1.get('Education', "Never"))

"""print("has_key method output : %s" % d1.in('Branch'))


print("Value : %s" % d1.has_key('Age'))"""

print("The items of d1 are: %s" % d1.items())


print("The keys of d1 are : %s" % d1.keys())
print("The Values of d1 are : %s" % d1.values())

print("The default Value set to key is : %s" %d1.setdefault('Marks', 100))


print("d1 after adding Marks key: %s"%d1)

d5={'gen':'female'}
d1.update(d5)
print("The updated d1 is : %s" % d1)

OUTPUT

Enter the size of dictionary3


Enter the key to be added:Name
Enter the value for the key to be added:mahi
Enter the key to be added:branch
Enter the value for the key to be added:cse
Enter the key to be added:section
Enter the value for the key to be added:b
dictionary d1 is:
{'section': 'b', 'Name': 'mahi', 'branch': 'cse'}
Length of d1 is: 3
Equivalent String of d1: {'section': 'b', 'Name': 'mahi', 'branch': 'cse'}
Variable Type : <class 'dict'>
Length of d2 before clear: 3
Length of d2 after clear : 0
New dictionary after copied: {'section': 'b', 'Name': 'mahi', 'branch': 'cse'}
New Dictionary after using fromkeys : {'section': 10, 'name': 10, 'branch': 10}
Value retrieved after using get : cse
Value : Never
The items of d1 are: dict_items([('section', 'b'), ('Name', 'mahi'), ('branch', 'cse')])
The keys of d1 are : dict_keys(['section', 'Name', 'branch'])
The Values of d1 are : dict_values(['b', 'mahi', 'cse'])
The default Value set to key is : 100
d1 after adding Marks key: {'section': 'b', 'Name': 'mahi', 'branch': 'cse', 'Marks': 100}
The updated d1 is : {'section': 'b', 'gen': 'female', 'Name': 'mahi', 'branch': 'cse', 'Marks': 100}

You might also like