Python Programming Homework: Basic Operations and Algorithms

This homework covers fundamental Python programming concepts, including basic input/output, string manipulation, arithmetic operations, and elementary algorithms. Each question provides a clear problem statement and a sample Python code solution.

Question 1: Sum of Two Numbers

Problem: Write a program that prompts the user to enter two numbers and then outputs their sum.

num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))

sum = num1 + num2

print('The sum of', num1, 'and', num2, 'is', sum)

Question 2: String Length

Problem: Write a program that prompts the user to enter a string and then outputs the length of the string.

string = input('Enter a string: ')

length = len(string)

print('The length of the string is', length)

Question 3: Even or Odd

Problem: Write a program that prompts the user to enter a number and then outputs whether the number is even or odd.

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

if num % 2 == 0:
    print(num, 'is even')
else:
    print(num, 'is odd')

Question 4: Factorial

Problem: Write a program that prompts the user to enter a number and then outputs the factorial of that number.

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

factorial = 1

for i in range(1, num + 1):
    factorial *= i

print('The factorial of', num, 'is', factorial)

Question 5: Prime Number Check

Problem: Write a program that prompts the user to enter a number and then outputs whether the number is prime or not.

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

is_prime = True

if num <= 1:
    is_prime = False

for i in range(2, int(num ** 0.5) + 1):
    if num % i == 0:
        is_prime = False
        break

if is_prime:
    print(num, 'is prime')
else:
    print(num, 'is not prime')

Question 6: Reverse a Number

Problem: Write a program that prompts the user to enter a number and then outputs the reverse of that number.

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

reverse = 0

while num > 0:
    digit = num % 10
    reverse = reverse * 10 + digit
    num = num // 10

print('The reverse of', num, 'is', reverse)

Note: The reverse of a number is obtained by reversing the order of its digits. For example, the reverse of 123 is 321.

Python Programming Homework: Basic Operations and Algorithms

原文地址: https://www.cveoy.top/t/topic/pbGi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录