0% found this document useful (0 votes)
12 views9 pages

Python S, L, F, T

The document contains examples of Python functions and programs using functions. It includes functions to accept user input, perform calculations, check conditions, iterate through lists and tuples, and manipulate string and list data.

Uploaded by

disss8989
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views9 pages

Python S, L, F, T

The document contains examples of Python functions and programs using functions. It includes functions to accept user input, perform calculations, check conditions, iterate through lists and tuples, and manipulate string and list data.

Uploaded by

disss8989
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/ 9

1. Write a function which will accept a name and print greeting message.

def greetings():
name = input("Enter your name:")
print("Hello", name)
greetings()

2. Write function check(n), which will check whether number is even or odd.
def check():
if(n%2==0):
print("even")
else:
print("odd")

n=int(input("Enter a number:"))
check()

3. Write function large (n1,n2) , which will print the largest number.
def large(n1, n2):
if (n1>n2):
print("Largest No is:", n1)
elif (n1<n2):
print("Largest No is:", n2)
else:
print("Both equal")
n1=int(input("Enter a number:"))
n2=int(input("Enter a number:"))
large(n1,n2)

4. Accept a number and write a function table(n) which will print


multiplication table of it.
def table(number):
for i in range(1, 11):
print(number, "x", i, "=", number * i)

num = int(input("Enter a number: "))


table(num)

5. Write function calculate(n1,n2,operator) , which will return addition/


subtraction/ multiplication/division of given number according to operator.
def calculation(n1, n2, op):
match op:
case '+': return n1 + n2
case '-': return n1 - n2
case '*': return n1 * n2
case '/':
if n2 == 0:
return "Division not possible"
else:
return n1 / n2
case _: return "Invalid operator"
n1 = float(input("Enter the first number: "))
n2 = float(input("Enter the second number: "))
op = input("Enter the operator (+, -, *, /): ")
result = calculation(n1, n2, op)
print("Result:", result)

6. Write a menu driven python program with functions which will accept a number
and option from user and print the output according to following option. Print
divisor, check no is prime, factorial. Accept the input till user enters invalid
option.
def print_divisors(n):
print("Divisors of", n, "are:")
for i in range(1, n + 1):
if n % i == 0:
print(i)
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
while True:
print("\nMenu:")
print("1. Print divisors of a number")
print("2. Check if a number is prime")
print("3. Calculate factorial of a number")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
num = int(input("Enter a number: "))
print_divisors(num)
elif choice == '2':
num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is prime")
else:
print(num, "is not prime")
elif choice == '3':
num = int(input("Enter a number: "))
print("Factorial of", num, "is", factorial(num))
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid option. Please choose again.")

7. Write a python code to print to days date in following


format 27 February 2024, Tuesday
from datetime import datetime
now = datetime.now()
s1 = now.strftime("%d/%B/%Y, %A")
print(s1)

8. Write a python program of a guessing game.


import random

def main():
secret_number = random.randint(1, 10)
attempts = 5

print("Welcome to the Guessing Game!")


print(f"I've picked a number between 1 and 10. You have {attempts}
attempts to guess it.")

while attempts > 0:


try:
guess = int(input("Enter your guess: "))
if guess == secret_number:
print(f"Congratulations! You guessed it. The secret number was
{secret_number}.")
break
elif guess < secret_number:
print("Try a higher number.")
else:
print("Try a lower number.")
attempts -= 1
print(f"You have {attempts} attempts left.")
except ValueError:
print("Invalid input. Please enter a valid integer.")

if attempts == 0:
print(f"Sorry, you're out of attempts. The secret number was
{secret_number}.")

if __name__ == "__main__":
main()
9. S = “WelCome”
s="welcome"
print(s[0:3])
print(s[3:])
print(s[3:6])
print(s[5:])
10. Write a python function which will print the string as-
s="Hello"
for i in range(0,6):
print(s[0:i])
11. Using above string print the following output using loop
Hello
s = "Hello"
i=5
while i > 0:
print(s[0:i])
i -= 1

12. Write a python program to accept 3 strings and concatenate it.


s1=input("enter : ")
s2=input("enter : ")
s3=input("enter : ")
print(s1+" "+s2+" "+s3)

13. Write a python function repeat_string(s,n) which will print given string s , n times.
def repeat_string():
s = input("Enter the string: ")
n = int(input("Enter the number of times to repeat: "))
print((s + " ") * n)
repeat_string()

14. s =“ Communication”
s="Communication"
print(s[4:7])
print(s[1:3])
print(s[0:3])
print(s[7:])

15. Write a python function check(s,ch) which checks whether ch is present in s or


not and return the value “yes” or “no” according to it.
def checks(s, ch):
if ch in s:
return "yes"
else:
return "no"

s = input("Enter a string: ")


ch = input("Enter a character to check: ")
print(checks(s, ch))

16. Accept a string and a choice(l / u/c/s) and convert the given string into lower or
uppercase or capitalize or swapcase according to choice.
def convert_string(string, choice):
if choice == 'l':
return string.lower()
elif choice == 'u':
return string.upper()
elif choice == 's':
return string.swapcase()
elif choice == 'c':
return string.capitalize()
else:
return "Invalid choice"

s = input("Enter a string: ")


s1= input("Enter choice (l for lower, u for upper, s for swapcase, c for capitalize): ")

result = convert_string(s, s1)


print("Converted string:", result)

17. Accept a string and substring and print the count i.e how many times substring
occurs in a string.
def count_substring_occurrences(string, substring):
count = string.count(substring)
return count

string = input("Enter a string: ")


substring = input("Enter a substring: ")

occurrences = count_substring_occurrences(string, substring)


print("The substring '{}' occurs {} times in the string.".format(substring, occurrences))

18. Create list of 5 fruits. Print first 4 fruits from list. Print last fruit from the list. Print the
middle fruit from the list. Print last 3 fruits from the list. 2- consists of only 1 & last
l=["Apple","Mango","Pineapple","Watermelon","Grapes"]
print(l[0:4])
print(l[-1])
print(l[2])
print(l[2:5])

f = l[::4]
print(f)

19. Write a python program which will accept a range and create a list consisting of
even numbers from that range.
n1 = int(input("Enter the first number: "))
n2 = int(input("Enter the second number: "))
even = []
for i in range(n1, n2 + 1):
if i % 2 == 0:
even.append(i)
print("Even numbers:", even)

20. Write a python program which will create a list of 4 names and print the name
which has length greater than 5.
names = ["Disha","Sukruit","Dhruvil","Bob","Jack"]
for n in names:
if len(n) > 4:
print(n)

21. Write a python program which will create a list of 5 numbers and accept a
number & delete it from list.
no=[4,8,12,16,20]
print(no)
n=int(input("Enter a number to delete : "))
if n in no:
no.remove(n)
print(no)
else:
print(n,"number does not exit in the list")

22. Write a python program which will create a list of 5 colours and print the list in
reverse order using pop() function.
colours=["Blue","Red","Green"]
r=[]
while colours:
r.append(colours.pop())
print("colours in the reverse order",r)

23. Write a python program which will accept a number and delete the element specify
by the number from above colour list.
colours = ["Red", "Pink", "Blue", "Black", "White"]
print( colours)
n = int(input("Enter the Index to delete: "))
if 0 <= n < len(colours):
del colours[n]
print("Updated list after deletion:", colours)
else:
print(f"Index {n} is out of range for the list.")

24. Write a python program which will define a list of prime numbers and accept a
choice (r/ s / l /m ) & write a function which will print the list in reverse order or in sorted
or large element from list or minimum element form list ,according to users choice.
def display(prime_list, ch):
print(prime_list)
match ch:
case 's':
sorted_prime = sorted(prime_list)
print("Sorted list:", sorted_prime)
case 'r':
reversed_prime = list(reversed(prime_list))
print("Reverse list:", reversed_prime)
case 'l':
max_prime = max(prime_list)
print("Large list:", max_prime)
case 'm':
min_prime = min(prime_list)
print("Minimum list:", min_prime)
case _:
return "Invalid choice"

def main():
prime = [3, 7, 11, 2, 5]
choice = input("Enter a choice (r/s/l/m): ")
display(prime, choice) # function call
if __name__ == "__main__":
main()

25. Write a python program which will define a list of 5 numbers and create a new list
from this list which consists of the numbers grater than 20.(Use List
Comprehension)
l=[10,15,20,30,40]
new=[x for x in l if x>20]
print(new)

26. Write a program which will define list of colours and create a new list which consist
B” letter in the colours. .(Use List Comprehension)
colours=["White","Blue","Black","RedBerry","Pink","Red"]
new=[new for new in colours if "B" in new]
print(new)

27. Accept a number and create a tuple.


n = int(input("Enter a number: "))
tuple = (n,)
print("Tuple created:", tuple)

28. Accept a string and create a tuple, using constructor.


n = input("Enter a string: ")
tuple = (n,)
print("Tuple created:", tuple)

29. Write a python program which will define tuple of month in words & accept
number from user and print month in words.
months = ("January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December")
no = int(input("Enter a number (1-12): "))
if no>=1 and no<=12:
print("Month:", months[no - 1])
else:
print("Invalid")

30. Write a python program which will define tuple of one digit number in words &
accept number from user and print it in words using function.
def words(no):
word = ("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
print("Number in word:", word[no])
n = int(input("Enter a number (0-9): "))
words(n)

31. Create a tuple of mobile brands. Accept a name of mobile and check whether it is
present in tuple or not.

mobile_brands = ("Apple", "Samsung", "Huawei", "Xiaomi", "OnePlus")


mobile_name = input("Enter the name of a mobile: ")
print("Mobile present:", mobile_name in mobile_brands)

You might also like