以下是几个Python练手小程序代码示例:
猜数字游戏
import random secret_number = random.randint(1, 100) print("猜数字游戏开始!") while True: guess = int(input("请输入一个数字:")) if guess == secret_number: print("猜对了!") break elif guess < secret_number: print("猜小了,再试试") else: print("猜大了,再试试")
石头、剪刀、布游戏
import random print("石头、剪刀、布游戏开始!") print("请出拳:(石头:1,剪刀:2,布:3)") player = int(input("玩家出拳:")) computer = random.randint(1, 3) if player == computer: print("平局") elif (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1): print("玩家获胜!") else: print("电脑获胜!")
斐波那契数列
def fibonacci(n): if n <= 0: return [] elif n == 1: return [1] elif n == 2: return [1, 1] else: fib = [1, 1] for i in range(2, n): fib.append(fib[i-1] + fib[i-2]) return fib n = int(input("请输入要生成斐波那契数列的个数:")) print(fibonacci(n))
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): return x / y print("计算器程序开始!") 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("输入有误,请重新运行程序")
这些小程序可以帮助你练习Python的基础语法和流程控制语句,同时提高你的编程思维和解决问题的能力。
评论