让我们一起来编写几个简单的Python程序作为练习:
1. 计算器:
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y != 0:
return x / y
else:
return "除数不能为零"
print("选择运算:")
print("1.相加")
print("2.相减")
print("3.相乘")
print("4.相除")
choice = input("输入你的选择(1/2/3/4):")
num1 = float(input("输入第一个数字:"))
num2 = float(input("输入第二个数字:"))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("输入无效")
2. 猜数字游戏:
import random
target_number = random.randint(1, 100)
guess_count = 0
guess_limit = 10
print("猜数字游戏!我想了一个1到100之间的数字,你有10次机会猜对。")
while guess_count < guess_limit:
guess = int(input("请输入你猜的数字:"))
guess_count += 1
if guess < target_number:
print("你猜的数字太小了。")
elif guess > target_number:
print("你猜的数字太大了。")
else:
print("恭喜你,猜对了!")
break
if guess_count == guess_limit and guess != target_number:
print("很遗憾,你没有猜对。正确答案是:", target_number)
3. 简单的文本处理:
def count_words(text):
words = text.split()
return len(words)
def reverse_text(text):
return text[::-1]
input_text = input("请输入一段文本:")
word_count = count_words(input_text)
reversed_text = reverse_text(input_text)
print("单词数量:", word_count)
print("文本反转:", reversed_text)
这些是简单的Python程序示例,希望可以帮助练习编程和熟悉Python语法。通过不断练习和尝试更多的编程项目,逐渐提高自己的编程技能和解决问题的能力。祝编程愉快!