gpt4 book ai didi

python - 如何在python中集成一个简单的菜单

转载 作者:太空宇宙 更新时间:2023-11-04 04:17:21 26 4
gpt4 key购买 nike

这是我当前的 HiLo 游戏,我想集成一个包含 4 个选项的菜单,1. 读取 csv 文件 2. 玩游戏 3. 显示结果和 4. 退出,任何帮助都将不胜感激。因为我不知道从哪里开始。

 import\
random
n = random.randint(1,20)
print(n)
guesses = 0

while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)

guesses = guesses + 1

if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break

if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")`enter code here`

最佳答案

您可以将游戏循环放在菜单循环中,并将 csv 文件等的所有代码放在这些循环中...

但是,为了稍微组织一下代码,学习一点函数当然更可取:

在这里,我将您的游戏循环放在一个函数中,还为其他选项创建了函数;现在,它们只打印它们应该做的事情,但是当您添加功能时,您将用代码填充它。

import random


def read_csv():
print('reading csv')

def show_results():
print('showing results')

def play_game():
n = random.randint(1,20)
# print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)

guesses = guesses + 1

if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break

if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")


while True:

choice = int(input("1. read csv file 2. play game 3. show results and 4. exit"))
if choice == 4:
break
elif choice == 2:
play_game()
elif choice == 3:
show_results()
elif choice == 1:
read_csv()

关于python - 如何在python中集成一个简单的菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55173820/

26 4 0