如何在python中集成一个简单的菜单 [英] how to integrate a simple menu in python
问题描述
这是我当前的HiLo游戏,我想集成一个包含4个选项的菜单:1.读取csv文件2.玩游戏3.显示结果并4.退出,感谢您的帮助. 因为我不知道从哪里开始.
This is my current HiLo game, I want to integrate a menu with 4 options, 1. read csv file 2. play game 3. show results and 4. exit, any help is appreciated. Because I don't know where to start.
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文件的代码等放置在这些循环中...
You could place your game loop inside a menu loop, and all the code for csv file, etc. inside these loops...
但是,一定要学习一些有关函数的知识,以便稍微组织一下代码,这绝对是可取的:
However, it is surely preferable to learn a little bit about functions, in order to organize your code a little bit:
在这里,我将您的游戏循环放置在一个函数中,并且还为其他选项创建了函数;现在,他们只打印他们应该做的事情,但是当您添加功能时,将用代码填充它.
Here, I placed your game loop inside a function, and also created functions for the other options; right now, they only print what they should be doing, but as you add features, you will fill this with code.
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中集成一个简单的菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!