如何用PYTHON制作猜随机数字游戏

2024-11-10 14:29:33

1、打开JUPTER NOTEBOOK,新建一个PY文档。

如何用PYTHON制作猜随机数字游戏

2、import randomguess = int(input("Please guess the number: "))machine = random.randint(1, 9)if guess > machine: print("Too high")elif guess < machine: print("too low")else: print("exactly right")用random和input,然后进行比较,这样方法很简单。

如何用PYTHON制作猜随机数字游戏

3、import randomguess = int(input("Please guess the number: "))machine = random.randint(1, 9)count = 0if guess > machine: print("Too high") count += 1elif guess < machine: print("too low") count += 1else: print("exactly right") count += 1 print(count)如果要计算用户输入了多少次,加入变量来计算。

如何用PYTHON制作猜随机数字游戏

4、import randomguess = int(input("Please guess the number: "))machine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": if guess > machine: print("Too high") count += 1 elif guess < machine: print("too low") count += 1if guess == machine: print("exactly right") count += 1 print(count)else: print("Try again!")我们可以用while来不断重复程序,但是这里有个错误。

如何用PYTHON制作猜随机数字游戏

5、import randomguess = int(input("Please guess the number: "))machine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": count += 1 if guess > machine: print("Too high") elif guess < machine: print("too low")if guess == machine: print("exactly right") count += 1 print(count)else: print("Try again!")我们先简化一下流程,重复的删掉。

如何用PYTHON制作猜随机数字游戏

6、import randomguess = int(input("Please guess the number: "))machine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": if guess == "exit": break count += 1 if guess > machine: print("Too high") elif guess < machine: print("too low") else: print("you win with {} times".format(count))尝试一下转换一下条件的位置,但是还是出现错误,这个时候要找到错误的地方。

如何用PYTHON制作猜随机数字游戏

7、import randommachine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": guess = int(input("Please guess the number: ")) if guess == "exit": break count += 1 if guess > machine: print("Too high") elif guess < machine: print("too low") else: print("you win with {} times".format(count))把用户输入的变量放在while里面,这样就正确了。

如何用PYTHON制作猜随机数字游戏

8、import randommachine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": guess = int(input("Please guess the number: ")) if guess == "exit": break count += 1 if guess > machine: print("Too high") elif guess < machine: print("too low") else: print("you win with {} times".format(count))如果输入exit就会发现错误,因为我们提前把用户输入的变为整型了。

如何用PYTHON制作猜随机数字游戏

9、import randommachine = random.randint(1, 9)count = 0while guess != machine and guess != "exit": guess = input("Please guess the number: ") if guess == "exit": break guess = int(guess) count += 1 if guess > machine: print("Too high") elif guess < machine: print("too low") else: print("you win with {} times".format(count))这里只需要修改一下位置就可以得到正确的结果了。

如何用PYTHON制作猜随机数字游戏
猜你喜欢