在python中创建操作菜单

2024-09-20 22:57:10 发布

您现在位置:Python中文网/ 问答频道 /正文

1)到目前为止,我有while循环的代码,但我只想循环12次:

print ("Please enter the 12 monthly figures")
input ("Enter a value in the range 0 to 300:")

我试过一个for循环,但没有成功

2)我想为我的代码创建一个菜单,到目前为止我有:

print ("Please choose one of the following options:")

ans=True
while ans:
    print ("""
    0. Quit
    1. Work out and display the total
    3. Work out and display the mean 
    4. Work out and display the standard deviation
    5. Work out and display the median 
    6. Work out and display the lowest and second lowest
    7. Work out and display the 3 month 
    8. Work out and display the months 
    9. Work out display  level
    """)

但我想让用户选择一个


Tags: andthe代码inputdisplayoutworkprint
3条回答

1)可以将range()与for循环一起使用,例如:

for i in range(0, 12):
    print(i)

2)可以对多个可能的值使用一系列ifelif语句,例如:

if a == 0:
    print("something")

elif a == 1:
    print("something else")

elif a == 2:
    print("another something")

它们所做的是,首先检查第一条语句是否为真,然后如果不是真,则转到下一条语句,直到没有剩下语句或者其中一条语句为真。 希望这有帮助。你知道吗

试试这个:

def get_monthly_rainfall_figures():
    rainfall_figures = []
    print("Please enter the 12 monthly rainfall figures")
    for month in range(12):
        in_ = int(input("Enter a value (0-300): "))
        if 0 <= in_ <= 300:
            rainfall_figures.append(in_)
        else:
            # handle invalid input
    return rainfall_figures

以及

def menu():
    print ("""
0. Quit
1. Work out and display the total
3. Work out and display the mean 
4. Work out and display the standard deviation
5. Work out and display the median 
6. Work out and display the lowest and second lowest
7. Work out and display the 3 month 
8. Work out and display the months 
9. Work out display level
""")
    user_in = input(">>")
    responses = {"0": quit_func,
                 "1": total_func,
                 "3": mean_func,
                ...etc...}
    # where quit_func, total_func, etc are functions that do the described
    # action
    # This design pattern is known as a hash table, and is very idiomatic
    # in Python. In other languages you might use a switch/case block.
    try:
        responses[user_in]()
    except KeyError:
        # handle invalid input

显然Python没有switch/case循环,所以可以构建一些if语句。如果您使用的是2.7,那么您将使用原始输入作为用户输入,如果是3.x,那么您将只使用输入。你知道吗

if input == 0:
    print ("You picked zero\n")
    ...

以此类推。另外,我认为如果你把int(input)或任何你分配给你的输入,它会工作,因为input需要一个字符串,所以你必须转换它。你知道吗

相关问题 更多 >

    热门问题