Python Exercise Answer
Print "Hello, World!"
This Python program simply prints the message "Hello, World!" to the console.
print("Hello, World!")
Sum of Two Numbers
This Python program takes two numbers as input and prints their sum.
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print(f"The sum is: {sum}")
Odd or Even
This Python program checks if the number entered by the user is odd or even.
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Factorial of a Number
This Python program calculates the factorial of a given number entered by the user.
num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}")
Palindrome Checker
This Python program checks whether the given string is a palindrome, meaning it reads the same forwards and backwards.
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Fibonacci Sequence
This Python program prints the Fibonacci sequence up to a specified number of terms entered by the user.
n = int(input("Enter the number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
Prime Number
This Python program checks if a given number is prime. A prime number is a number greater than 1 that has no divisors other than 1 and itself.
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print("Not prime")
break
else:
print("Prime")
else:
print("Not prime")
Count Vowels in a String
This Python program counts the number of vowels (a, e, i, o, u) in a given string entered by the user.
string = input("Enter a string: ")
vowels = "aeiou"
count = 0
for char in string.lower():
if char in vowels:
count += 1
print(f"Number of vowels: {count}")
List Sorting
This Python program sorts a given list of numbers in ascending order.
numbers = [5, 3, 8, 6, 7]
numbers.sort()
print(f"Sorted list: {numbers}")
Find Largest Number in a List
This Python program finds the largest number in a given list of numbers.
numbers = [5, 3, 8, 6, 7]
largest = max(numbers)
print(f"The largest number is: {largest}")