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
""")
但我想让用户选择一个
答案 0 :(得分:0)
对于Python来说,显然没有切换/案例循环,所以你可以做的一件事是构建一些if语句。如果您使用的是2.7,那么您将使用raw_input进行用户输入,如果是3.x,则您只需使用输入。\ n \ n
if input == 0:
print ("You picked zero\n")
...
等等。另外,我认为如果你输入int(输入)或你输入的任何内容,它都会起作用,因为输入需要一个字符串,所以你必须转换它。
答案 1 :(得分:0)
1)您可以将range()
与for循环一起使用,例如:
for i in range(0, 12):
print(i)
2)您可以为多个可能的值使用一系列if
和elif
语句,例如:
if a == 0:
print("something")
elif a == 1:
print("something else")
elif a == 2:
print("another something")
这些操作是什么,首先它检查第一个语句是否为True,然后如果它不是True则转到下一个语句,直到没有语句或其中一个语句为True。 希望这会有所帮助。
答案 2 :(得分:0)
试试这个:
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