[Go to site: main page, start]

0% found this document useful (0 votes)
18 views12 pages

Python Programming Exercises and Solutions

The document contains a collection of Python programming exercises that cover various fundamental concepts such as string manipulation, variable naming conventions, arithmetic operations, user input handling, control flow, and functions. Each exercise includes code snippets that demonstrate how to implement specific tasks, such as calculating averages, checking for prime numbers, and creating a simple calculator. Additionally, the document provides examples of using loops and conditionals to solve problems and manipulate data structures like lists.

Uploaded by

rushiln3391
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views12 pages

Python Programming Exercises and Solutions

The document contains a collection of Python programming exercises that cover various fundamental concepts such as string manipulation, variable naming conventions, arithmetic operations, user input handling, control flow, and functions. Each exercise includes code snippets that demonstrate how to implement specific tasks, such as calculating averages, checking for prime numbers, and creating a simple calculator. Additionally, the document provides examples of using loops and conditionals to solve problems and manipulate data structures like lists.

Uploaded by

rushiln3391
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Made by Harsh Sharma ♾

Python Programs
1. print this string: hihihihi there byebyebyebyebye

a = "hi"*4
b = "bye"*5
c = a + " there " + b
print(c)

2. Come up with 5 legal python variable names and 5 illegal names.

# Legal names:
name = "rohit"
_speed = 102
direction34 = "north"
PI = 3.14
age = 17

# Illegal names (first position a digit


# or variable name containing any special character):
1name = "rohit"
&speed = 102
d$irection = "north"
PI^ = 3.14
age! = 17

3. write a program to compute average of three numbers.

a = 10
b = 12
c = 54
avg = (a+b+c)/3
print(avg)

4. write a program to compute simple interest.

p = 100
r = 12
t = 2
simple_interest = (p*r*t)/100
print(simple_interest)

5. write a program to swap two variables.


1 / 12
Made by Harsh Sharma ♾

a = 10
b = 20

temp = a
a = b
b = temp

print(a, b)

6. Write a program that uses input to prompt a user for their name and then welcomes them.

name = input("enter your name")

output = "Hello " + name + " how are you?"

print(output)

7. Write a program to prompt the user for hours and rate per hour using input to compute gross pay.

hours = input("enter hours")


rate = input("enter rate")

gross = int(hours) * float(rate)

print(gross)

8. Write a program that takes user's age and prints if he or she is eligible for voting

age = int(input("enter age"))

if age >= 18:


print("eligible")
else:
print("not eligible")

9. Write a program to take an positive integer value from the user and print if the value is odd or even.

number = int(input("enter number"))

reminder = number % 2

if reminder == 0:
print("even")

2 / 12
Made by Harsh Sharma ♾

else:
print("odd")

10. Write a program that takes two integer inputs from the user and prints the largest one.

a = int(input("enter first number"))


b = int(input("enter second number"))

if a > b:
print(a)
else:
print(b)

11. Write a program that takes three integer inputs from the user and prints the largest one.

a = int(input("enter first number"))


b = int(input("enter second number"))
c = int(input("enter third number"))

if a > b:
if a > c:
print(a)
else:
print(c)
else:
if b > c:
print(b)
else:
print(c)

12. Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay
the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40
hours.

hours = int(input("Enter hours: "))


rate = float(input("Enter rate: "))

overtime = hours - 40

if hours <= 40:


pay = hours * rate
else:
pay = (40 * rate) + (overtime * rate * 1.5)

print("Pay:", pay)

3 / 12
Made by Harsh Sharma ♾

13. Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error. If
the score is between 0.0 and 1.0, print a grade using the following table:

Score Grade

>= 0.9 A

>= 0.8 B

>= 0.7 C

>= 0.6 D

< 0.6 F

score = float(input("enter score"))

if (score >= 0) and (score <= 1):


if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
else:
print("F")
else:
print("Error, score out of range")

14. Build a calculator by taking two numbers from user and the operation the user wants to do.

num1 = float(input("enter first number"))


num2 = float(input("enter second number"))
operator = input("enter operator")

if operator == '+':
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
elif operator == "/":
print(num1 / num2)
elif operator == "**":
print(num1 ** num2)
elif operator == "%":
print(num1 % num2)
else:
print("unsupported operator")

4 / 12
Made by Harsh Sharma ♾

15. check if character given by user is a vowel or consonant.

character = input("Enter character")

if character in "aeiou":
print("Vowel")
else:
print("Consonant")

16. print numbers from 1 to 10, but skip 5 using while loop.

i = 0
while i < 10:
i = i + 1
if i == 5:
continue
print(i)

17. count even numbers from 1 to 20 using while loop.

i = 1
count = 0
while i <= 20:
reminder = i % 2
if reminder == 0:
count = count + 1
i = i + 1

print(count)

18. print even numbers from 1 to 20 using for loop.

for i in range(1, 21):


reminder = i % 2
if reminder == 0:
print(i)

19. print first 10 multiples of 3 using while loop.

i = 1
while i <= 30:
reminder = i % 3

5 / 12
Made by Harsh Sharma ♾

if reminder == 0:
print(i)
i = i + 1

20. print first 20 numbers but skip multiples of 4. use for loop.

for i in range(1, 20):


if i % 4 == 0:
continue
print(i)

21. count number of elements in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]

count = 0
for number in numbers:
count = count + 1

print(count)

22. sum all the elements in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]

summation = 0
for number in numbers:
summation = summation + number

print(summation)

23. find the average of all the elements in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]

count = 0
summation = 0
for number in numbers:
count = count + 1
summation = summation + number

average = summation/count
print(average)

6 / 12
Made by Harsh Sharma ♾

24. sum of numbers until user enters 0 using while loop.

summation = 0
number = int(input("enter number"))

while number != 0:
summation = summation + number
number = int(input("enter number"))

print(summation)

25. only print numbers that are greater than 25 in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]

for number in numbers:


if number > 25:
print(number)

26. count number of positive and negative numbers in a list using for loop.

numbers = [5, -2, 9, -7, 0, 4, -1]


positive = 0
negative = 0

for number in numbers:


if number > 0:
positive = positive + 1
elif number < 0:
negative = negative + 1

print(positive)
print(negative)

27. count number of vowels in a string using for loop.

text = "Hello World"


vowels = 0
for char in text:
if char in "aeiou":
vowels += 1
print(vowels)

28. print sum of numbers from 1 to 50, but only include those numbers which are divisible by either 3 or 5.
use for loop.
7 / 12
Made by Harsh Sharma ♾

summation = 0
for i in range(1, 51):
if (i % 3 == 0) or (i % 5 == 0):
summation += i
print(summation)

29. check if a number is prime. use for loop.

number = int(input("enter a number"))

prime = True

for i in range(2, number):


if number % i == 0:
prime = False
break

if prime is True:
print("number is prime")
else:
print("number is not prime")

30. search for an element in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]
number_to_search = 178
number_present = False

for number in numbers:


if number == number_to_search:
number_present = True

if number_present is True:
print("number is present")
else:
print("number not present")

31. Check Pass or Fail from Marks List using for loop. passing marks is 35.

marks = [45, 67, 32, 90, 25]


passing_marks = 35

for mark in marks:


if mark >=35:
print(mark, "pass")

8 / 12
Made by Harsh Sharma ♾

else:
print(mark, "fail")

32. find the largest number out of a bunch of numbers stored in a list using for loop.

numbers = [3,43,23,89,67,178,99,216]
largest = -float("inf")
# variable 'largest' is storing negative infinity

for number in numbers:


if number > largest:
largest = number

print(largest)

33. Make a password checking code which gives user 3 attempts to input correct password. if user inputs 3
incorrect passwords, print "Too many failed attempts". password is "1234".

attempts = 0
password = "1234"
while attempts < 3:
user_input = input("Enter password: ")
if user_input == password:
print("Access granted")
break
else:
print("Incorrect password, try again")
attempts += 1
if attempts == 3:
print("Too many failed attempts")

34. write a function to multiply all the elements in [4,3,1,-1,19,2,9].

def multiply_list(li):
multiplication = 1
for element in li:
multiplication = multiplication * element

return multiplication

li = [4,3,1,-1,19,2,9]

multiplication = multiply_list(li)
print(multiplication)

35. write a function to calculate factorial of a number.

9 / 12
Made by Harsh Sharma ♾

def calculate_factorial(num):
factorial = 1
for i in range(num):
factorial = factorial * (i+1)

return factorial

factorial = calculate_factorial(5)
print(factorial)

36. write a function to take name and surname from users and greet them all until user types done in name
prompt.

def greet(name, surname):


print("Hello", name, surname, "how are you?")

while True:
name = input("Enter name: ")

if name == "done":
break
else:
surname = input("Enter surname: ")
greet(name, surname)

37. write a function that inputs a number and prints the multiplication table of that number.

def multiplication_table(num):
for i in range(10):
multiplication = num * (i+1)
print(num, "x", i+1, "=", multiplication)

multiplication_table(13)

38. Given a pyramid height (integer), write a function to print a triangle.

"""
For num = 5:
*
* *
* * *
* * * *
* * * * *
"""

def triangle(num):
10 / 12
Made by Harsh Sharma ♾

for i in range(num):
for j in range(i+1):
print("* ", end="")
print()

triangle(5)

39. print all the characters in a string using indexing.

name = "rohit"
length = len(name)
for i in range(length):
print(name[i])

40. print all the characters in a string using indexing in reverse.

name = "rohit"
length = len(name)
for i in range(length):
print(name[length-1-i])

41. count the number of "a" in the string "banana".

string = "banana"
count = 0
for char in string:
if char == "a":
count = count + 1
print(count)

42. Write code using find() and string slicing to extract the number from the string "X-DSPAM-
Confidence: 0.8475". Convert the extracted value to a decimal number and print it out.

string = "X-DSPAM-Confidence: 0.8475"


start = [Link]("0")
end = len(string)
number = float(string[start:end])
print(number)

43. print elements and their corresponding position in a list.

my_list = [5,2.33,"rohit","raghav",5.3556,89,"alex"]
length = len(my_list)
11 / 12
Made by Harsh Sharma ♾

for i in range(length):
print(i, "->", my_list[i])

44. reverse a list.

my_list = [5,2.33,"rohit","raghav",5.3556,89,"alex"]
reversed_list = []
length = len(my_list)
for i in range(length):
reversed_list.append(my_list[length-i-1])
print(reversed_list)

45. make a frequency dictionary of a list containing duplicate names.

names = ["rohit", "virat", "harsh", "alex", "rahul", "rohit", "alex"]


frequency_dict = {}
for name in names:
frequency_dict[name] = frequency_dict.get(name, 0) + 1
print(frequency_dict)

46. using match case, print the day name for a number input by the user. so, if user inputs "3", print
"Wednesday" since it's the Third day. print "invalid input" if user inputs some number other than 1 to 7.

month = int(input("enter month number"))

match month:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
case _:
print("invalid input")

12 / 12

You might also like