[英]How can I ask for input based on items in a list?
I'm trying to make a loop that asks for the rainfall of each month, with the months stored into a list. 我正在尝试制作一个循环,要求每个月的降雨量,并将月份存储在列表中。 How can I make 1 loop that will ask for input of the rainfall for each month by pulling each month from the list?
如何通过从列表中拉出每个月来制作1个循环,要求每个月输入降雨?
example: 例:
months = ["January", "February", "March"]
rainfall = input("What is the rainfall for ", months[0])
how can i do that for each month with 1 loop? 我该如何每月进行1次循环?
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
rainfall = []
for month in months:
answer = int(input("What was the rainfall in {}?".format(month)))
rainfall.append(answer)
I think you are asking about string formatting. 我认为您正在询问字符串格式。 There are several ways (
%
, .format()
, and f-strings), but my favorite would be .format()
which would look like: 有几种方法(
%
.format()
和f字符串),但我最喜欢的是.format()
,它看起来像:
months = ["January", "February", "March"]
rainfall = input("What is the rainfall for {}".format(months[0]))
Then to repeat the process for all months would could look something like this: 然后,重复整个月的过程可能看起来像这样:
months = ["January", "February", "March"]
rainfall = [input("What is the rainfall for {}?\n>>>".format(month)) for month in months]
Where I added some nice formatting with a \\n
newline character, and an obvious prompt of >>>
我在其中添加了一些不错的格式,其中带有
\\n
换行符,并且明显提示>>>
You can use a for loop and a list that will keep taken rainfall answers from user. 您可以使用for循环和列表,该列表将保留用户的降雨答案。 This will loop for all elements in months list.
这将循环显示月份列表中的所有元素。
months = ["January", "February", "March"]
rainfalls = []
for month in months:
rainfall = input("What is the rainfall for " + month+ "\n")
rainfalls.append(rainfall)
print(rainfalls) #python3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.