how to integrate a simple menu in python

心已入冬 提交于 2019-12-24 01:27:38

问题


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`

回答1:


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()


来源:https://stackoverflow.com/questions/55173820/how-to-integrate-a-simple-menu-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!