Python
Python
1
1.Given variables full and empty, write an expression that evaluates to
True if at most one of the variables is True and evaluates to False
otherwise.
Program:
num1= 45
num2= 56
if num1 > num2:
print("Statement is true")
else:
print("Statement is false")
OUTPUT:
2
2. You want an automatic wildlife camera to switch on if the light level is
less than 0.01 or if the tempreture is above freezing, but not if both
conditions are true.
Program:
light_level=0.001
temp=2
if light_level<0.01 and temp>0:
print(" on the camera")
if light_level>0.01 and temp<0:
print(" off the camera")
else:
print("camera can't be opened")
OUTPUT:
3
3. Print the numbers in the range 33 to 49 (inclusive).
Program:
for num in range(33,49+1):
print(num)
OUTPUT:
4
4. Write a script to print the following pattern.
TT
TTT
TTTT
TTTTT
TTTTTT
TTTTTTT
Program:
def pattern(n):
for i in range(0,n):
for j in range(0, i+1):
print("T " , end="")
print("\r")
pattern(7)
OUTPUT:
5
5. Write a programto prompt the user to enter the hours worked and hour
rate. If the no of hours worked is 40 then he gets the normal salary or else
he gets 1.5 times the hour rate. (Use function to compute pay)
Program:
def computepay(hr_worked,rate):
if hr_worked <= 40:
pay = hr_worked * rate
elif hr_worked >40:
pay=40*rate + (hr_worked-40)*rate*1.5
return pay
hr_worked=float(input("Enter hours worked:"))
rate=float(input("Enter hours rate:"))
p = computepay(hr_worked,rate)
print("pay salary:", p)
OUTPUT:
6
6.Write a program that repeatedly prompts a user for integer numbers
until the user enters ‘done’. Once ‘done’ is entered, print out the largest
and smallest of the numbers the user enters anything other than a number,
print an error message and skip to the next number.
Program:
largest=None
smallest=None
while True:
try:
num = input("Enter a number:")
if num=="done":
break
num = int(num)
if largest is None or largest<num:
largest =num
elif smallest is None or smallest>num:
smallest =num
except ValueError:
print("invalid input.")
print("Maximum number is:",largest)
print("Minimum number is:",smallest)
OUTPUT:
7
Lists Program
8
numberlist=[]
number=int(input("Enter the list of numbers:"))
for k in range(1,number+1):
value=int(input("Enter the values of %d elements:" %k))
numberlist.append(value)
total = sum(numberlist)
print("\n The sum of all elements in the list is:",total)
OUTPUT:
9
import collections
mylist=[13,13,23,23,34,45,50,50,7,7,7,7]
print("original list", mylist)
numberlist =collections.Counter(mylist)
print("Frequency of the element are", numberlist)
OUTPUT:
3.Write a function that finds the minimum and maximum values in list and
the corresponding list includes.
Program:
numberlist =[12,18,5,4,45]
print("The minimum nbr in list is :")
print(min(numberlist))
print("The maximum nbr in list is :")
print(max(numberlist))
OUTPUT:
10
Program:
list=['pooja','kajal','khusi','rahul','sona','kajal','pooja']
myset=set(list)
print(myset)
OUTPUT:
5.Use list comprehension to generate a list where the values are square of
numbers between 1 and 20(both included).
Program:
list = []
fori in range(1,20):
list.append(i*i)
print(*list)
OUTPUT:
11
integer= input("Enter integer:")
longest= max(integer.split(),key=len)
print("Longest integer is :",longest)
print("The length of the integer is :",len(longest))
OUTPUT:
OUTPUT:
12
word= input("Enter the word:")
integer= input("Enter integer:")
longest=word.split()
longestinteger=integer.split()
long1=[]
longinteger1=[]
k=int(input("Enter the value n :"))
for p in longestinteger:
if (len(p) > k):
longinteger1.append(p)
n=int(input("Enter the value n :"))
fori in longest:
if (len(i) > n):
long1.append(i)
print("List of the word are :",long1)
print("List of the integer are :",longinteger1)
OUTPUT:
9. Create two lists NAMES and AGES that defines names of the persons
and their age. Write a function combine_lists that combines these lists into
a dictionary and print the dictionary.
13
Program:
test_name= ["pooja","kavana","rahul","sona"]
test_age= [72,78,75,89]
print("Name list is :" + str(test_name))
print("Age list is :" + str(test_Age))
res={}
for key in test_name:
for value in test_Age:
res[key] = value
test_Age.remove(value)
break
print("Resultant list is :" + str(res))
OUTPUT:
14
String program
1.To print the items present from third to fifth position in the list.
Program:
15
item=[7,5,9,4,5,0,2];
print("List from third to fifth is : ")
print(item[3:5])
2. To print the items from second position to the last item in the list.
Program:
item=[7,5,9,4,5,3,2];
print("Last second position in item is : ")
print(item[-2])
3. To create the nested list and print the item in he embedded list.
Program:
16
item=[7,5,9,4,5,3,2,[4,6,8,1]];
print("nested list is : ")
print (item[7])
item=['black','green','yellow']
item.append('purple')
print("The list is :", item)
5. Write a program to Search the string for a specified value and return the
position where it was found.
17
Program:
ini_string = 'pooja'
c = "j"
Program:
string = "19mca10"
print(string.isalnum())
string = "19mca10"
print(string.isalnum())
Output:
18
Program:
test_list = ["4aa", "b23", "98", "74"]
print("The original list is : " + str(test_list))
res = all(ele.isdigit() for ele in test_list)
print("Are all strings digits ? : " + str(res))
Output:
Program:
def isValid(str1, n):
if (((ord(str1[0]) >= ord('a') and
ord(str1[0]) <= ord('z')) or
(ord(str1[0]) >= ord('A') and
ord(str1[0]) <= ord('Z')) or
ord(str1[0]) == ord('_')) == False):
return False
for i in range(1, len(str1)):
if (((ord(str1[i]) >= ord('a') and
ord(str1[i]) <= ord('z')) or
(ord(str1[i]) >= ord('A') and
ord(str1[i]) <= ord('Z')) or
(ord(str1[i]) >= ord('0') and
ord(str1[i]) <= ord('9')) or
ord(str1[i]) == ord('_')) == False):
return False
return True
str1 = "_19mca10"
n = len(str1)
if (isValid(str1, n)):
19
print("Is Identifier")
else:
print("Not")
Output:
Program:
def checkIfStartsWithUppercase(string) :
if (string[0] >= 'A' and string[0] <= 'Z') :
return 1;
else :
return 0;
def check(string) :
if (checkIfStartsWithUppercase(string)) :
print("Start With Uppercase:");
else :
print("Not");
if __name__ == "__main__" :
string = "Jyotinivas";
check(string);
string = "college";
check(string);
Output:
20
Dictionary
21
1.Write a Python script to sort (ascending and descending) a dictionary
by value.
Program:
import operator
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
Output:
22
2.Write a Python program to remove duplicates from dictionary
Program:
student_data = {'id1':
{'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id2':
{'name': ['David'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id3':
{'name': ['Sara'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
'id4':
{'name': ['Surya'],
'class': ['V'],
'subject_integration': ['english, math, science']
},
}
result = {}
23
result[key] = value
print(result)
Output:
24
3.Write a Python program to sum all the items in a dictionary.
Program:
my_dict={'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
Output:
25
File Handling
26
1.Suppose we have this hours.txt data:
123 Suzy 9.5 8.1 7.6 3.1 3.2
456 Brad 7.0 9.6 6.5 4.9 8.8
789 Jenn 8.0 8.0 8.0 8.0 7.5
Compute each worker's total hours and hours/day. (Assume each worker
works exactly five days.) Print the output in the following format
Suzy ID 123 worked 31.4 hours: 6.3 / day
Brad ID 456 worked 36.8 hours: 7.36 / day
Jenn ID 789 worked 39.5 hours: 7.9 / day
Program:
def main():
input = open("hours.txt")
for line in input:
id, name, mon, tue, wed, thu, fri = line.split()
hours = float(mon) + float(tue) + float(wed) + \
float(thu) + float(fri)
Output:
27
2. Write a program to read through the message.txt and figure out who
has the sent the greatest number of mail messages. The program looks for
'From ' lines and takes the second word of those lines as the person who
sent the mail. The program creates a Python dictionary that maps the
sender's mail address to a count of the number of times they appear in the
file. After the dictionary is produced, the program reads through the
dictionary using a maximum loop to find the most prolific committer.
Program:
words = list()
counts = dict()
maxval = None
maxkey = None
for key,val in counts.items() :
28
if val>maxval:
maxval = val
maxkey = key
Output:
29
PROJECT
30
Analogue clock
Purpose:
An analogue clock is a tool for reading the time of day. The shortest
hand indicates the hour, a longer hand indicates the minutes, and the
longest arm indicates the seconds. Some analogue clocks have only
two hands: the shorter hand indicating the hour and the longer hand
indicating the minutes. Analogue clocks can also help you realize a
cost savings beyond the initial purchase price. They are more energy
efficient than digital displays.
Features:
31
This program is great for those who are familiar with the Python
Turtle graphics module and its various functions. my GitHub for
some of my personal Python and Java Projects. This program is
included in my Python Programs repository. This program is written in
the fairly easy to read Turtle graphics module.
Features covered:
Code:
import turtle
import time
wndw = turtle.Screen()
wndw.bgcolor("black")
wndw.setup(width=600, height=600)
wndw.title("Analogue Clock")
wndw.tracer(0)
hands = [("white", 80, 12), ("blue", 150, 60), ("red", 110, 60)]
time_set = (hr, mn, sec)
for hand in hands:
time_part = time_set[hands.index(hand)]
angle = (time_part/hand[2])*360
33
pen.penup()
pen.goto(0, 0)
pen.color(hand[0])
pen.setheading(90)
pen.rt(angle)
pen.pendown()
pen.fd(hand[1])
while True:
hr = int(time.strftime("%I"))
mn = int(time.strftime("%M"))
sec = int(time.strftime("%S"))
draw_clock(hr, mn, sec, pen)
wndw.update()
time.sleep(1)
pen.clear()
wndw.mainloop()
OUTPUT:
34
35
36