1. 题目:写一个函数,计算给定列表中所有偶数的和。
defsum_even_numbers(lst):
return sum(num for num in lst if num % 2 == 0)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = sum_even_numbers(numbers)
print(result)
2. 题目:实现一个简单的计算器程序,要求支持加、减、乘、除四则运算。
def calculator(operator, num1, num2):
ifoperator == '+':
return num1 + num2
elif operator == '-':
return num1 - num2
elif operator == '*':
return num1 * num2
elif operator == '/':
return num1 / num2
else:
return"Invalid operator"
result = calculator('+', 10, 5)
print(result)
3. 题目:编写一个函数,接受一个字符串,并返回该字符串的反转字符串。
defreverse_string(s):
return s[::-1]
text = "Hello, World!"
reversed_text = reverse_string(text)
print(reversed_text)
4. 题目:写一个程序,打印出斐波那契数列的前20项。
deffibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(20):
print(fibonacci(i))
5. 题目:实现一个简单的购物车程序,用户可以添加商品、查看购物车、计算总价等功 能。
classShoppingCart:
def__init__(self):
self.items = {}
defadd_item(self, item, price):
if item inself.items:
self.items[item] += price
else:
self.items[item] = price
defcalculate_total(self):
return sum(self.items.values())
defdisplay_cart(self):
for item, price inself.items.items():
print(f"{item}: ${price}")
cart = ShoppingCart()
cart.add_item("Apple", 2.5)
cart.add_item("Banana", 1.5)
cart.add_item("Orange", 3.0)
cart.display_cart()
total_price = cart.calculate_total()
print(f"Total Price: ${total_price}")
6. 题目:编写一个函数,接受一个整数 n,计算并返回从 1 到 n 的所有整数的平方和。
defsum_of_squares(n):
return sum([i**2for i in range(1, n+1)])
n = 5
result = sum_of_squares(n)
print(result)
7. 题目:实现一个简单的猜数字游戏,程序随机生成一个1到100之间的整数,用户通过输入来猜这个数字,直到猜对为止。
import random
target_number = random.randint(1, 100)
whileTrue:
guess = int(input("Guess the number (1-100): "))
if guess == target_number:
print("Congratulations! You guessed the correct number.")
break
elif guess < target_number:
print("Try a higher number.")
else:
print("Try a lower number.")
8. 题目:编写一个函数,接受一个字符串,返回该字符串中每个单词首字母大写的新字符串。
defcapitalize_words(s):
return' '.join(word.capitalize() for word in s.split())
text = "hello world, how are you?"
result = capitalize_words(text)
# print(result)
9. 题目:实现一个简单的学生信息管理系统,包括添加学生、查看学生信息等功能。
classStudent:
def__init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
classStudentDatabase:
def__init__(self):
self.students = []
defadd_student(self, student):
self.students.append(student)
defdisplay_students(self):
for student inself.students:
print(f"Name: {student.name}, Age: {student.age}, Grade: {student.grade}")
db = StudentDatabase()
student1 = Student("Alice", 18, "A")
student2 = Student("Bob", 19, "B")
db.add_student(student1)
db.add_student(student2)
db.display_students()
10. 题目:编写一个程序,接受用户输入的两个整数,然后输出它们的最大公约数。
defgcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = gcd(num1, num2)
print(f"The greatest common divisor of {num1} and {num2} is: {result}")