100% found this document useful (1 vote)
100 views36 pages

Python

The document contains 7 simple Python programs that demonstrate basic concepts like conditionals, loops, functions, lists, dictionaries, and strings. The programs include examples of printing patterns, finding minimum/maximum values in lists, combining lists into a dictionary, and checking properties of strings. Overall, the document provides a variety of small exercises to practice common Python programming techniques.

Uploaded by

pooja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
100% found this document useful (1 vote)
100 views36 pages

Python

The document contains 7 simple Python programs that demonstrate basic concepts like conditionals, loops, functions, lists, dictionaries, and strings. The programs include examples of printing patterns, finding minimum/maximum values in lists, combining lists into a dictionary, and checking properties of strings. Overall, the document provides a variety of small exercises to practice common Python programming techniques.

Uploaded by

pooja
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 36

Simple Program

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

1 .Write a python program to sum all items in a list.


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:

2.Write a python program to get the frequency of the elements in a list.


Program:

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:

4. Write a python program to remove duplicates/to get unique values from


a list.

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:

6.Write a program that maps a list of integersrespresenting the length of


the corresponding words.
Program:

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:

7.Write a function find_long_word() that takes a list of words and returns


the length of the longest one.
Program:
word= input("Enter the word:")
longest= max(word.split(),key=len)
print("Longest word is :",longest)
print("The length of the word is :",len(longest)

OUTPUT:

8. Write a function filter_long_words() that takes a list of words and and


integer n and retruns the list of words that are longer than n.
Program:

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])

4. Demonstrate list method


Program:

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"

print ("initial_string : ", ini_string, "\ncharacter_to_find : ", c)


res = None
for i in range(0, len(ini_string)):
if ini_string[j] == c:
res = j + 1
break
if res == None:
print ("No such character available in string")
else:
print ("Character {} is present at {}".format(c, str(res)))

6. Write a program to check if all characters in the string are


alphanumeric.

Program:
string = "19mca10"
print(string.isalnum())

string = "19mca10"
print(string.isalnum())

Output:

7. Write a program to check if all characters in the string are digits.

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:

8. Write a program to check if the string is an identifier.

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:

9. Write a program to check if each word starts with an uppercase letter.

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}

print('Original dictionary : ',d)

sorted_d = sorted(d.items(), key=operator.itemgetter(1))

print('Dictionary in ascending order by value : ',sorted_d)

sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))

print('Dictionary in descending order by value : ',sorted_d)

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 = {}

for key,value in student_data.items():


if value not in result.values():

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)

print(name, "ID", id, "worked", \


hours, "hours: ", hours/5, "/ day")
main()

 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:

name =input("Enter file:")


if len(name) <1 : name = "mybox-short.txt"
name = "mybox-short.txt"
handle = open(name)
text = handle.read()

words = list()

for line in handle:


if not line.startswith("From:") : continue
line = line.split()
words.append(line[1])

counts = dict()

for word in words:


counts[word] = counts.get(word, 0) + 1

maxval = None
maxkey = None
for key,val in counts.items() :

28
if val>maxval:
maxval = val
maxkey = key

print (maxkey, maxval)

Output:

29
PROJECT

30
Analogue clock

Aim of the project:


My main aim for this project was to develop a model for analogue
clock identification, and to implement it with a program that would be
able to receive an image of a clock, and return the time displayed after
its analysis. And this project is simple and good for beginners or the
student who wants to learn and develop the project in python
programming language.

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.

Turtle is a built-in module in Python, so copy and pasting


directly into your console shouldn’t be a problem at all.

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)

# Create the drawing pen


pen = turtle.Turtle()
pen.hideturtle()
pen.speed(0)
pen.pensize(3)
32
def draw_clock(hr, mn, sec, pen):
# Draw clock face
pen.up()
pen.goto(0, 210)
pen.setheading(180)
pen.color("green")
pen.pendown()
pen.circle(210)
# Draw hour hashes
pen.up()
pen.goto(0, 0)
pen.setheading(90)
for _ in range(12):
pen.fd(190)
pen.pendown()
pen.fd(20)
pen.penup()
pen.goto(0, 0)
pen.rt(30)

# Draw the hands


# Each tuple in list hands describes the color, the length
# and the divisor for the angle

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

You might also like