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

Practical File

The document contains 19 code snippets demonstrating various Python programming concepts and tasks. The snippets include programs to: 1) Calculate the year a user will turn 100 years old based on their current age. 2) Convert between kilometers and miles. 3) Perform a unit conversion of the user's choosing, such as pounds to kilograms. 4) Loop through multiple calculations in an interactive calculator.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views

Practical File

The document contains 19 code snippets demonstrating various Python programming concepts and tasks. The snippets include programs to: 1) Calculate the year a user will turn 100 years old based on their current age. 2) Convert between kilometers and miles. 3) Perform a unit conversion of the user's choosing, such as pounds to kilograms. 4) Loop through multiple calculations in an interactive calculator.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Practical File

1) # Get user input for current age and name


name = input("What is your name: ")
age = int(input("How old are you: "))

# Calculate the year when the person will be 100 years old
current_year = 2023 # Update this to the current year
years_to_100 = 100 - age
future_year = current_year + years_to_100

print(f"{name} will be 100 years old in the year {future_year}")

2) Write a program that converts distances measured in kilometers to miles. One kilometer is
approximately 0.62 miles.

# Conversion factor
kilometers_to_miles = 0.621371

# Get user input for distance in kilometers


kilometers = float(input("Enter distance in kilometers: "))

# Convert kilometers to miles


miles = kilometers * kilometers_to_miles

# Display the result


print(f"{kilometers} kilometers is approximately {miles} miles")

3. Write a program to perform a unit conversion of your own choosing. Make sure that the program
prints an introduction that explains what it does.

# Introduction
print("This program converts weights from pounds to kilograms.")

# Conversion factor
pounds_to_kilograms = 0.453592

# Get user input for weight in pounds


pounds = float(input("Enter weight in pounds: "))

# Convert pounds to kilograms


kilograms = pounds * pounds_to_kilograms

# Display the result


print(f"{pounds} pounds is approximately {kilograms} kilograms")

4) Write an interactive Python calculator program. The program should allow the user to type a
mathematical expression, and then print the value of the expression. Include a loop so that the user can
perform many calculations (say, up to 100).

# Introduction
print("Welcome to the Interactive Python Calculator!")
print("You can type a mathematical expression to evaluate.")
print("Type 'exit' to quit the calculator.")

# Main loop
for _ in range(100):
expression = input("Enter a mathematical expression: ")

if expression.lower() == "exit":
print("Exiting the calculator.")
break

try:
result = eval(expression)
print("Result:", result)
except Exception as e:
print("Error:", e)

5) Write a program that asks the user to enter their name and their age. Print out a message addressed
to them that tells them the year that they will turn 100 years old.

# Get user input for name and age


name = input("What is your name: ")
age = int(input("How old are you: "))

# Calculate the year when the person will be 100 years old
current_year = 2023 # Update this to the current year
years_to_100 = 100 - age
future_year = current_year + years_to_100

# Display the result


print(f"Hi {name}, you will turn 100 years old in the year {future_year}.")

6) Write a program with a loop so that it executes 5 times before quitting. Each time through the loop,
the program should get another temperature from the user and print the converted value.

# Loop 5 times
for _ in range(5):
# Get user input for temperature in Celsius
celsius = float(input("Enter temperature in Celsius: "))

# Convert Celsius to Fahrenheit


fahrenheit = (celsius * 9/5) + 32

# Display the converted temperature


print(f"{celsius}°C is approximately {fahrenheit}°F")

print("Program finished.")

7) Write a program to find largest and smallest number

# Get user input for the number of elements


num_elements = int(input("Enter the number of elements: "))
# Initialize variables for largest and smallest numbers
largest = None
smallest = None

# Loop to get numbers and find the largest and smallest


for _ in range(num_elements):
num = float(input("Enter a number: "))

if largest is None or num > largest:


largest = num

if smallest is None or num < smallest:


smallest = num

# Display the results


print(f"Largest number: {largest}")
print(f"Smallest number: {smallest}")

8) Write a program to check if a number is positive negative or zero

# Get user input for the number


number = float(input("Enter a number: "))

# Check if the number is positive, negative, or zero


if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else:
print("Zero")

9) Write a program to find factorial of a number.

# Function to calculate factorial

def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n - 1)

# Get user input for the number

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

# Calculate the factorial

result = factorial(number)

# Display the result

print(f"The factorial of {number} is {result}")

10) Write a program to count characters in a string if character is repeated it should count only once.
# Get user input for a string

input_string = input("Enter a string: ")

# Create a set to store unique characters

unique_characters = set()

# Count unique characters in the string

for char in input_string:

if char not in unique_characters:

unique_characters.add(char)

# Display the count of unique characters

count = len(unique_characters)

print(f"The number of unique characters in the string is: {count}")

11) Write a program to swap two variables without using third variables.

# Get user input for two variables

var1 = input("Enter the value of the first variable: ")

var2 = input("Enter the value of the second variable: ")


# Display the values before swapping

print(f"Before swapping: var1 = {var1}, var2 = {var2}")

# Swap the values

var1, var2 = var2, var1

# Display the values after swapping

print(f"After swapping: var1 = {var1}, var2 = {var2}")

12) Write a program to find the sum of the first n natural numbers, where the value of n is provided by
the user.

# Get user input for the value of n

n = int(input("Enter a positive integer (n): "))

# Calculate the sum of the first n natural numbers

sum_of_natural_numbers = (n * (n + 1)) // 2

# Display the result

print(f"The sum of the first {n} natural numbers is: {sum_of_natural_numbers}")

13) Write a program to find the sum of the cubes of the first n natural numbers where the value of n is
provided by the user
# Get user input for the value of n

n = int(input("Enter a positive integer (n): "))

# Calculate the sum of the cubes of the first n natural numbers

sum_of_cubes = sum([i ** 3 for i in range(1, n + 1)])

# Display the result

print(f"The sum of the cubes of the first {n} natural numbers is: {sum_of_cubes}")

``

14) Write a program to print all prime numbers in an interval.

# Function to check if a number is prime

def is_prime(num):

if num <= 1:

return False

if num <= 3:

return True

if num % 2 == 0 or num % 3 == 0:

return False

i=5
while i * i <= num:

if num % i == 0 or num % (i + 2) == 0:

return False

i += 6

return True

# Get user input for the interval

start = int(input("Enter the starting number: "))

end = int(input("Enter the ending number: "))

# Display prime numbers in the interval

print(f"Prime numbers between {start} and {end}:")

for num in range(start, end + 1):

if is_prime(num):

print(num)

15) Write a program to print all odd/even number in given range

# Get user input for the range

start = int(input("Enter the starting number: "))

end = int(input("Enter the ending number: "))


# Get user input for odd or even choice

choice = input("Enter 'odd' or 'even': ").lower()

# Display numbers based on the user's choice

print(f"{choice} numbers between {start} and {end}:")

if choice == "odd":

for num in range(start, end + 1):

if num % 2 != 0:

print(num)

elif choice == "even":

for num in range(start, end + 1):

if num % 2 == 0:

print(num)

else:

print("Invalid choice. Please enter 'odd' or 'even'.")

16) A Fibonacci sequence is a sequence of numbers where each successive number is the sum of the
previous two. The classic Fibonacci sequence begins: 1, 1, 2, 3, 5, 8, 13, write a program that computes
the nth Fibonacci number where n is a value input by the user. For example, if n = 6, then the result is 8.

# Function to calculate nth Fibonacci number


def fibonacci(n):
if n <= 0:
return 0
elif n == 1 or n == 2:
return 1
else:
a, b = 1, 1
for _ in range(3, n + 1):
a, b = b, a + b
return b

# Get user input for n


n = int(input("Enter a positive integer (n): "))

# Calculate the nth Fibonacci number


result = fibonacci(n)

# Display the result


print(f"The {n}th Fibonacci number is: {result}")

17) Write a program to calculate the volume and surface area of a sphere from its radius, given as
input.

import math

# Get user input for the radius


radius = float(input("Enter the radius of the sphere: "))

# Calculate the volume of the sphere


volume = (4/3) * math.pi * radius**3

# Calculate the surface area of the sphere


surface_area = 4 * math.pi * radius**2

# Display the results


print(f"Radius: {radius}")
print(f"Volume of the sphere: {volume:.2f}")
print(f"Surface area of the sphere: {surface_area:.2f}")

18) Write a program to check weather a given number is Armstrong number (It can be for any number
of digits)

# Function to check if a number is an Armstrong number


def is_armstrong(number):
num_str = str(number)
num_digits = len(num_str)
total = sum(int(digit) ** num_digits for digit in num_str)
return total == number

# Get user input for the number


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

# Check if the number is an Armstrong number


if is_armstrong(number):
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")

19) Write a program to check weather a given number is leap year or not

# Function to check if a year is a leap year


def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False

# Get user input for the year


year = int(input("Enter a year: "))

# Check if the year is a leap year


if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

20) Write a program to calculate quadratic equation.

import math

# Get user input for coefficients


a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))

# Calculate the discriminant


discriminant = b**2 - 4*a*c

# Check the nature of roots


if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
print(f"Roots are real and distinct: {root1} and {root2}")
elif discriminant == 0:
root = -b / (2*a)
print(f"Root is real and equal: {root}")
else:
real_part = -b / (2*a)
imaginary_part = math.sqrt(-discriminant) / (2*a)
print(f"Roots are complex: {real_part} + {imaginary_part}i and {real_part} -
{imaginary_part}i")

21) Write a menu driven Python program that should perform the following four tasks:
(i) After getting a word (of input) from the user, your program should use a while (or for) loop to
print out each of the letters of the word. Just remember that strings in Python start with element
0.

(ii) Your program should then use another loop to print out each of the letters of the (same) word
in reverse order.
(ii) Make a new variable that is the original word in reverse and print that variable. You can do
this very easily in Python with a "string slice".

(iv) Ask the user for a letter to count. Use another loop to count how many times that letter
appears in the original word. Print out this count.

# Function to print each letter of the word


def print_letters(word):
print("Printing each letter of the word:")
for letter in word:
print(letter)

# Function to print each letter of the word in reverse order


def print_reverse(word):
print("Printing each letter of the word in reverse order:")
for letter in reversed(word):
print(letter)

# Function to print the word in reverse


def print_reverse_word(word):
reverse_word = word[::-1]
print("The word in reverse:", reverse_word)

# Function to count the occurrence of a letter


def count_letter(word, letter):
count = 0
for char in word:
if char == letter:
count += 1
print(f"The letter '{letter}' appears {count} times in the word.")

# Get user input for a word


word = input("Enter a word: ")

while True:
print("\nMenu:")
print("1. Print each letter of the word")
print("2. Print each letter of the word in reverse order")
print("3. Print the word in reverse")
print("4. Count the occurrence of a letter")
print("5. Exit")

choice = int(input("Enter your choice (1/2/3/4/5): "))

if choice == 1:
print_letters(word)
elif choice == 2:
print_reverse(word)
elif choice == 3:
print_reverse_word(word)
elif choice == 4:
letter = input("Enter a letter to count: ")
count_letter(word, letter)
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")

22) Write a program that inputs a word and prints "Yes it starts !!" if the given word starts with "0", "1",
"2", ... , "9".

# Get user input for a word


word = input("Enter a word: ")

# Check if the word starts with a digit


if word and word[0].isdigit():
print("Yes it starts !!")
else:
print("No, it doesn't start with a digit.")

23) Carefully go through the code given below and answer the questions based on it:

in1Str = input ("Enter string of digits: ")


in2Str = input ("Enter string of digits: ")
if len(in1Str) > len(in2Str) :
small = in2Str
large = in1Str
else :
small = in1Str
large = in2Str
newStr = ''
for element in small :
result = int(element) + int(large[0])
newStr = newStr + str(result)
large = large[1:]

print (len(newStr))#Line 1
print(newStr)#Line 2
print (large)#Line 3
print (small)#Line 4

(i) Given a first input of 12345 and a second input of 246, what result is produced by a Line 1?

(ii) Given a first input of 12345 and a second input of 246, what result is produced by Line 2?

(iii) Given a first input of 123 and a second input of 4567, what result is produced by Line 3?

(iv) Given a first input of 123 and a second input of 4567, what result is produced by Line 4?

i)3
ii)357
iii)7
iv)123

24) Write a menu driven program to print the following:

a)
8
86
864
8642

b) #######
# #
# #
# #
# #
# #
#######
c)

#######
#
#
#
#
#
#######
d)

#######
#
#
#
#
#
#######

def pattern_a():
n = int(input("Enter the number of rows: "))
for i in range(n, 0, -1):
for j in range(i, n + 1):
print(j, end="")
print()

def pattern_b():
n=7
for i in range(n):
for j in range(n):
if i == 0 or i == n - 1 or j == 0 or j == n - 1:
print("#", end="")
else:
print(" ", end="")
print()

def pattern_c():
n=7
for i in range(n):
for j in range(n):
if i == 0 or i == n - 1 or j == i:
print("#", end="")
else:
print(" ", end="")
print()

def pattern_d():
n=7
for i in range(n):
for j in range(n):
if i == 0 or j == n - 1 or i == j:
print("#", end="")
else:
print(" ", end="")
print()

while True:
print("\nMenu:")
print("a) Pattern A")
print("b) Pattern B")
print("c) Pattern C")
print("d) Pattern D")
print("e) Exit")

choice = input("Enter your choice (a/b/c/d/e): ").lower()

if choice == 'a':
pattern_a()
elif choice == 'b':
pattern_b()
elif choice == 'c':
pattern_c()
elif choice == 'd':
pattern_d()
elif choice == 'e':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")

You might also like