Python是一种非常强大的编程语言,几个Python小案例:
1. 石头、剪子、布游戏:
这是一个简单的游戏,玩家和计算机交替选择石头、剪子或布。程序随机选择计算机的选择,然后根据规则确定谁赢了。
import random
def get_computer_choice():
choices = ['石头', '剪子', '布']
return random.choice(choices)
def get_user_choice():
user_input = input("请输入您的选择(石头、剪子、布):")
while user_input not in ['石头', '剪子', '布']:
print("输入有误,请重新输入!")
user_input = input("请输入您的选择(石头、剪子、布):")
return user_input
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "平局!"
elif (user_choice == "石头" and computer_choice == "剪子") or \
(user_choice == "剪子" and computer_choice == "布") or \
(user_choice == "布" and computer_choice == "石头"):
return "您赢了!"
else:
return "计算机赢了!"
def play_game():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("您选择了:", user_choice)
print("计算机选择了:", computer_choice)
print(determine_winner(user_choice, computer_choice))
play_game()
2. 简单的计算器:
这个程序会提示用户输入两个数字,然后执行他们选择的操作(加、减、乘、除)。
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:
print("错误:除数不能为0")
return
return x / y
print("选择操作:")
print("1.加法")
print("2.减法")
print("3.乘法")
print("4.除法")
while True:
choice = input("输入你的选择(1/2/3/4): ")
if choice in ('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))
break
else:
print("无效输入")
#java 编程# #分享编程技巧#