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

2nd Programs unit-2

The document contains various Python programming tasks, including checking if a number is even or odd, summing numbers in a list, and finding unique elements. It also includes programs for temperature conversion, palindrome checking, factorial calculation, and simple voting systems. Each task is accompanied by code snippets and example outputs.

Uploaded by

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

2nd Programs unit-2

The document contains various Python programming tasks, including checking if a number is even or odd, summing numbers in a list, and finding unique elements. It also includes programs for temperature conversion, palindrome checking, factorial calculation, and simple voting systems. Each task is accompanied by code snippets and example outputs.

Uploaded by

mrimpatient04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 17

1. Check Even or Odd 2.

Sum of Numbers in a List


number = int(input("Enter a number: numbers = [1, 2, 3, 4, 5]
")) total_sum = 0
if number % 2 == 0: for number in numbers:
print(f"{number} is even.") total_sum += number
else: print("The sum of the numbers is:",
print(f"{number} is odd.") total_sum)

Output: Output:
Enter a number: 4 The sum of the numbers is: 15
4 is even.
3. Count Down Using While Loop 4. Find the Maximum Number in a
List
start_number = int(input("Enter a number
to count down from: ")) numbers = [10, 50, 30, 20, 40]
while start_number >= 0:
max_number = numbers[0]
print(start_number)
for number in numbers:
start_number -= 1
if number > max_number:
Output: max_number = number
Enter a number to count down from: 3 print("The maximum number is:",
max_number)
3
2
1 Output:
0 The maximum number is: 50
5. Dictionary to Store Student Grades 6. FizzBuzz Output
1
2
grades = {
for i in range(1, 101): Fizz
"Alice": 85, 4
if i % 3 == 0 and i %
"Bob": 92, Buzz
5 == 0: Fizz
"Charlie": 78,
print("FizzBuzz") 7
}
8
for student, grade in grades.items(): elif i % 3 == 0:
Fizz
print(f"{student}: {grade}") print("Fizz") Buzz
elif i % 5 == 0: 11
Fizz
Output: print("Buzz") 13
Alice: 85 else: 14
Bob: 92 FizzBuzz
print(i)
Charlie: 78 ...
Question:
Write a program that converts a temperature from Celsius to Fahrenheit.
The program should prompt the user to enter a temperature in Celsius and
then display the equivalent temperature in Fahrenheit.

# Program to convert Celsius to Fahrenheit


celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")

Output:
Enter temperature in Celsius: 25
25.0°C is equal to 77.0°F
Question:
Write a program that checks if a given word is a palindrome (a word that reads the
same backward as forward). The program should prompt the user to enter a word
and display whether it is a palindrome.
# Program to check if a word is a palindrome
word = input("Enter a word: ")
if word == word[::-1]:
print(f"{word} is a palindrome.")
else:
print(f"{word} is not a palindrome.")

Output:
Enter a word: radar
radar is a palindrome.
(If you enter "hello", the output will be "hello is not a palindrome.")
Question:
Write a program that calculates the factorial of a number entered by the user. The
program should prompt the user for a non-negative integer and print the factorial.

# Program to calculate the factorial of a number


number = int(input("Enter a non-negative integer: "))
factorial = 1

for i in range(1, number + 1):


factorial *= i

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

Output:
Enter a non-negative integer: 5
The factorial of 5 is 120.
Question:
Write a program that takes a list of numbers and prints only the unique elements.
The program should define a list and iterate through it to find unique values.

# Program to find unique elements in a list


numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = []

for number in numbers:


if number not in unique_numbers:
unique_numbers.append(number)

print("Unique elements:", unique_numbers)

Output:
Unique elements: [1, 2, 3, 4, 5]
Question:
Write a program that simulates a simple voting system. The program should allow users to vote for one of three
candidates and display the total votes for each candidate at the end.

# Program for a simple voting for _ in range(5): # Let's say we have 5


system voters
choice = int(input("Enter your choice (1- Output:
votes = { 3): ")) Vote for your candidate:
1. Candidate A
"Candidate A": 0, if choice == 1: 2. Candidate B
votes["Candidate A"] += 1 3. Candidate C
"Candidate B": 0, Enter your choice (1-3): 1
elif choice == 2: Enter your choice (1-3): 2
"Candidate C": 0 votes["Candidate B"] += 1 Enter your choice (1-3): 1
Enter your choice (1-3): 3
} elif choice == 3: Enter your choice (1-3): 2
Total votes:
votes["Candidate C"] += 1 Candidate A: 2 votes
else: Candidate B: 2 votes
print("Vote for your candidate:") Candidate C: 1 votes
print("Invalid choice. Please vote
print("1. Candidate A") again.")
print("2. Candidate B") print("Total votes:")
for candidate, vote_count in votes.items():
print("3. Candidate C")
print(f"{candidate}: {vote_count} votes")
Question:
Write a program that implements a simple calculator. The program should allow the user to choose an operation
(addition, subtraction, multiplication, division) and input two numbers. It should then display the result.

# Simple calculator program


elif choice == '3':
print("Select operation:")
print("1. Addition") result = num1 * num2 Output:
print("2. Subtraction")
print("3. Multiplication")
print(f"The result is: {result}") Select operation:
print("4. Division") elif choice == '4': 1. Addition
choice = input("Enter choice (1/2/3/4): ") 2. Subtraction
num1 = float(input("Enter first number: "))
if num2 != 0: 3. Multiplication
num2 = float(input("Enter second number: ")) result = num1 / num2 4. Division

if choice == '1': print(f"The result is: {result}") Enter choice (1/2/3/4): 1


Enter first number: 10
result = num1 + num2
else: Enter second number: 5
print(f"The result is: {result}")
elif choice == '2': print("Error: Division by The result is: 15.0
result = num1 - num2 zero.")
print(f"The result is: {result}")
else:
print("Invalid input.")
Question:
Write a program that generates a multiplication table for a number entered by the user.

Output:
# Program to generate a multiplication table Enter a number: 5
number = int(input("Enter a number: ")) Multiplication table for 5:
5x1=5
5 x 2 = 10
print(f"Multiplication table for {number}:")
5 x 3 = 15
for i in range(1, 11):
5 x 4 = 20
print(f"{number} x {i} = {number * i}")
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
Question:
Write a program that removes duplicates from a predefined list and prints the
resulting list.
# Program to remove duplicates from a list
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))

print("List after removing duplicates:", unique_numbers)

Output:
List after removing duplicates: [1, 2, 3, 4, 5]
Question:
Write a program that creates a dictionary from two lists, where one list
contains keys and the other contains values.
# Program to create a dictionary from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']

dictionary = dict(zip(keys, values))

print("Created dictionary:", dictionary)

Output:
Created dictionary: {'name': 'Alice', 'age': 30, 'city': 'New York'}
Question:
Write a program that checks if two given words are anagrams (words made by rearranging the
letters of another). The program should prompt the user to enter two words and display whether
they are anagrams.

# Program to check if two words are anagrams


Output:
word1 = input("Enter the first word: ").lower()
word2 = input("Enter the second word: ").lower() Enter the first word: listen
Enter the second word: silent
if sorted(word1) == sorted(word2): listen and silent are anagrams.
print(f"{word1} and {word2} are anagrams.")
(If you enter "hello" and
else: "world", the output will be "hello
print(f"{word1} and {word2} are not anagrams.") and world are not anagrams.")
Question:
Write a program that calculates the average of a list of numbers. The program should prompt
the user to enter a list of numbers separated by spaces and then display the average.

# Program to calculate the average of a list


numbers = input("Enter numbers separated by spaces: ")
number_list = [float(num) for num in numbers.split()]
average = sum(number_list) / len(number_list)

print(f"The average is: {average}")

Output:
Enter numbers separated by spaces: 10 20 30
The average is: 20.0
Question: Count Vowels in a String

# Program to count vowels in a string


string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:


if char in vowels:
count += 1

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

Output:
Enter a string: Hello, World!
Question: Merge Two Lists

# Program to merge two lists


list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
merged_list = list1 + list2
unique_list = list(set(merged_list))

print("Merged list with unique elements:", unique_list)

Output:
Merged list with unique elements: [1, 2, 3, 4, 5, 6]
Question: Count the Number of Words in a Sentence

# Program to count the number of words in a sentence


sentence = input("Enter a sentence: ")
word_count = len(sentence.split())
print(f"The number of words in the sentence is: {word_count}")

Output:
Enter a sentence: Hello world, how are you?
The number of words in the sentence is: 6

You might also like