python游戏代码(Python编写简单猜数游戏)
下面是一个使用Python编写的简单猜数游戏,游戏会随机生成一个1到100之间的整数,然后让玩家尝试猜测这个数。
根据玩家的猜测,程序会给出提示(猜测太高或太低),直到玩家猜对为止。
import random def main(): number_to_guess = random.randint(1, 100) attempts = 0 print("猜数游戏:我想了一个1到100之间的整数。") while True: try: guess = int(input("请输入你的猜测:")) except ValueError: print("请输入一个有效的整数。") continue attempts += 1 if guess number_to_guess: print("太高了!") else: print(f"恭喜你,猜对了!这个数是 {number_to_guess}。") print(f"你总共尝试了 {attempts} 次。") break if __name__ == "__main__": main()
运行此脚本,然后按照提示输入你的猜测。游戏会根据你的猜测给出相应的提示,直到你猜对为止。