Python Programming Questions
### Conditional Statements:
1. Write a Python program to check if a number is positive, negative, or
zero.
# Get input from the user
number = float(input("Enter a number: "))
# Check if the number is positive, negative, or zero
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
2. Write a Python program that asks the user for their age and checks if
they are eligible to vote (18 or older).
# Get the user's age
age = int(input("Enter your age: "))
# Check if the user is eligible to vote
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
3. Write a Python program to find the largest of two numbers entered by
the user.
# Get two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Find and display the largest number
if num1 > num2:
print("The largest number is:", num1)
else:
print("The largest number is:", num2)
4. Write a Python program that checks whether a given number is even
or odd.
# Get input from the user
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
5. Write a Python program to check if a character entered by the user is a
vowel or a consonant.
# Get a character from the user
char = input("Enter a single character: ")
# Check if it is a vowel or a consonant
if char in 'aeiouAEIOU':
print("The character is a vowel.")
else:
print("The character is a consonant.")
### Loops:
5. Write a Python program to print numbers from 1 to 10 using a `for`
loop.
for num in range(1, 11):
print(num)
6. Write a Python program to print the first 5 multiples of 3 using a
`while` loop.
count = 1
while count <= 5:
print(count * 3)
count += 1
7. Write a Python program to calculate the sum of all numbers from 1 to
`n`, where `n` is provided by the user.
# Get the value of n from the user
n = int(input("Enter a number: "))
# Calculate the sum
total = 0
for num in range(1, n + 1):
total += num
print("The sum of numbers from 1 to", n, "is:", total)
8. Write a Python program to print all the even numbers between 1 and
20 using a `for` loop.
for num in range(1, 21):
if num % 2 == 0:
print(num)
10. Write a Python program to calculate the factorial of a given number
using a `while` loop.
# Get the number from the user
num = int(input("Enter a number: "))
# Initialize variables
factorial = 1
count = 1
# Calculate the factorial
while count <= num:
factorial *= count
count += 1
print("The factorial of", num, "is:", factorial)
### Relational Operators:
11. Write a Python program to check if two numbers entered by the user are
equal.
# Get two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Check if the numbers are equal
if num1 == num2:
print("The two numbers are equal.")
else:
print("The two numbers are not equal.")
12. Write a Python program that accepts three numbers and checks if the
first is greater than or equal to both the second and third.
# Get three numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
# Check if the first number is greater than or equal to both
if num1 >= num2 and num1 >= num3:
print("The first number is greater than or equal to both the second and
third.")
else:
print("The first number is not greater than or equal to both the second and
third.")
13. Write a Python program to determine whether a number is between 10
and 50 (inclusive).
# Get the number from the user
num = float(input("Enter a number: "))
# Check if the number is between 10 and 50
if 10 <= num <= 50:
print("The number is between 10 and 50 (inclusive).")
else:
print("The number is not between 10 and 50.")
14. Write a Python program to compare two numbers and print the smaller
one.
# Get two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Find and print the smaller number
if num1 < num2:
print("The smaller number is:", num1)
else:
print("The smaller number is:", num2)
15. Write a Python program to check if a number is divisible by both 2 and
5.
# Get the number from the user
num = int(input("Enter a number: "))
# Check divisibility by 2 and 5
if num % 2 == 0 and num % 5 == 0:
print("The number is divisible by both 2 and 5.")
else:
print("The number is not divisible by both 2 and 5.")
### Combined Topics:
16. Write a Python program to print all numbers from 1 to 50 that are
divisible by 7.
for num in range(1, 51):
if num % 7 == 0:
print(num)
17. Write a Python program that uses a loop to find the largest number in a
list of numbers entered by the user.
# Get a list of numbers from the user
numbers = input("Enter numbers separated by space: ").split()
# Convert the input to a list of integers
numbers = [int(num) for num in numbers]
# Find the largest number using a loop
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
print("The largest number is:", largest)
18. Write a Python program to print all odd numbers from 1 to 10 using a
`while` loop.
num = 1
while num <= 10:
if num % 2 != 0:
print(num)
num += 1
19. Write a Python program that asks the user for a password and keeps
prompting them until they enter the correct one.
# Define the correct password
correct_password = "password123"
# Ask for password and keep asking until it's correct
user_password = input("Enter the password: ")
while user_password != correct_password:
print("Incorrect password. Try again.")
user_password = input("Enter the password: ")
print("Password correct!")
20. Write a Python program to display the multiplication table for a number
entered by the user using a `for` loop.
# Get the number from the user
num = int(input("Enter a number: "))
# Display the multiplication table
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
### Additional Combined Questions:
21. Write a Python program that prompts the user to enter a series of
numbers. Stop when the user enters a negative number, and then print the
largest even number entered.
largest_even = None
while True:
num = int(input("Enter a number: "))
if num < 0:
break
if num % 2 == 0:
if largest_even is None or num > largest_even:
largest_even = num
if largest_even is None:
print("No even number was entered.")
else:
print("The largest even number is:", largest_even)
22. Write a Python program to find all numbers between 1 and 100 that are
divisible by 3 but not by 5. Use a loop and conditional statements to solve
this.
for num in range(1, 101):
if num % 3 == 0 and num % 5 != 0:
print(num)
23. Write a Python program that asks the user to input a number. Use a loop
to check whether the number is prime (a number greater than 1 that is only
divisible by 1 and itself).
# Get the number from the user
num = int(input("Enter a number: "))
# Check if the number is prime
if num > 1:
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print("The number is prime.")
else:
print("The number is not prime.")
else:
print("The number is not prime.")
24. Write a Python program that repeatedly asks the user to guess a secret
number. Use a `while` loop to give hints like "Too high" or "Too low" and
stop the loop when the user guesses correctly.
secret_number = 7 # You can change this to any secret number
while True:
guess = int(input("Guess the secret number: "))
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
else:
print("Correct! You've guessed the secret number.")
break
Write a program to calculate the factorial of a positive integer input by the
user. Recall that the factorial function is given by
X! = X(X - 1) (x - 2) ... (2)(1) so that 1! = 1, 2!= 2, 3!= 6, 4! = 24,
5! = 120, ...
Write the factorial function using a Python while loop.
Write the factorial function using a Python for loop
Check your programs to make sure they work for 1, 2, 3, 5, and beyond, but
especially for the first 5 integers.
# Factorial using a while loop
def factorial_while(n):
if n < 0:
return "Please enter a positive integer!"
result = 1
while n > 1: # Loop until n is 1
result *= n # Multiply result by n
n -= 1 # Decrease n by 1
return result
# Factorial using a for loop
def factorial_for(n):
if n < 0:
return "Please enter a positive integer!"
result = 1
for i in range(1, n + 1): # Loop from 1 to n
result *= i # Multiply result by i
return result
# Test the functions
print("Factorial using a while loop:")
for i in range(1, 6): # Test for numbers 1 to 5
print(f"{i}! = {factorial_while(i)}")
print("\nFactorial using a for loop:")
for i in range(1, 6): # Test for numbers 1 to 5
print(f"{i}! = {factorial_for(i)}")
Write a user defined function in matlab that takes an input array of number
and calculates the sum of square of elements. The function should accept the
input argument (thearray)and return the sum of the squares of the elements
in the array
function result = sumOfSquares(thearray)
% Calculate the square of each element in the array
squaredElements = thearray .^ 2;
% Sum up the squared elements
result = sum(squaredElements);
end
example
arr = [1, 2, 3, 4];
result = sumOfSquares(arr);
disp(result);
Write a Python program that takes a user's score as input and prints the
corresponding grade based on the following criteria:
If the score is 80 or above, print "Grade: A"
If the score is 70 to 79, print "Grade: B"
If the score is 60 to 69, print "Grade: C"
If the score is below 60, print "Grade: F"
# Input: Get the user's score
score = int(input("Enter your score: "))
# Determine and print the grade
if score >= 80:
print("Grade: A")
elif 70 <= score <= 79:
print("Grade: B")
elif 60 <= score <= 69:
print("Grade: C")
else:
print("Grade: F")
Fibonacci numbers are the numbers in a sequence in which the first two
elements are 0 and 1, and the value of each of subsequent element is the sum
of the previous two elements: 0, 1, 1, 2, 3, 5, 8, 13
Write a Python program in a script file that determines and displays the first
20 Fibonacci numbers.
# Fibonacci sequence generator
def generate_fibonacci(n):
# Initialize the first two Fibonacci numbers
fibonacci_sequence = [0, 1]
# Generate the Fibonacci sequence up to the nth number
for i in range(2, n):
next_number = fibonacci_sequence[i-1] + fibonacci_sequence[i-2]
fibonacci_sequence.append(next_number)
return fibonacci_sequence
# Number of Fibonacci numbers to generate
num_fibonacci = 20
# Generate and display the Fibonacci sequence
fibonacci_numbers = generate_fibonacci(num_fibonacci)
print("The first 20 Fibonacci numbers are:")
print(fibonacci_numbers)