while循环的使用

2024-09-28 22:21:31 发布

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

我试图编写一个python程序,询问用户希望插入多少年,然后让他们插入一个该年每个月的温度,所以它看起来是这样的:


一共多少年?e、 g.3级

哪一年是第一年?e、 2015年

第1个月:25

第2个月:21

等等。。。你知道吗


用户想看多少年就看多少年。到目前为止,我的情况是:

years = int(input("How many years?: "))

i= 0

while i <= years:
    for i in range(0,13):
            input("Type in first year")
            input("Month 1:  ")
            input("Month 2:  ")
            input("Month 3:  ")
            input("Month 4:  ")
            input("Month 5:  ")
            input("Month 6:  ")
            input("Month 7:  ")
            input("Month 8:  ")
            input("Month 9:  ")
            input("Month 10: ")
            input("Month 11: ")
            input("Month 12: ")

这种方法很管用,但是有没有一种更简洁的方法让月数自动变成+1,并要求输入12次?第二,当我完成了整个第一年,在我输入了12个月的温度后,它仍然问我“哪一年是第一年”,但我希望它问第二年,第三年等等,比如:“哪一年是第二年?”)你知道吗

我试着这样做:


years = int(input("How many years?: "))

i= 0

monthnumber = 1 

while i <= years:

    for i in range(0,13):
            input("Which is the first year?: ")
            input("Month",monthnumber,": ")
            monthnumber += 1

这里我得到的错误消息是,input最多需要1个参数,得到3个

提前感谢:)


Tags: 用户inforinputrange温度yearmany
3条回答

试试这个:

years_num = int(input("How many years?: "))

for year_num in range(1, years_num + 1):
    input("year " + str(year_num) + "?: ")
    for month_num in range(1, 13):
        input("month " + str(month_num) +":")

然后您可以将输入的信息存储在列表或dict中

代码中没有什么问题。一个就像我在评论中说的,index变量对于两个循环都是相同的。同样,在你的内部循环中,你要求每个循环中每个月的温度。另外,你不能在任何地方保持温度。我推荐一个解决方案

years = int(raw_input("Enter number of years: "))
#dictionary to hold year and temperature for each month for that year
temp = {}

for i in range(0, years):
    curr_year = raw_input("Enter current year: ")
    temp[curr_year] = []
    for i in range(0, 12):
        temp[curr_year].append((int(raw_input("Enter temperature: "))))

Here是上面代码的工作版本

用逗号分隔会导致python将其解释为多个参数。你知道吗

您想要的是将字符串连接到单个字符串,这可以通过使用+运算符来实现。你知道吗

input("Month " + str(monthnumber) + ": ")

相关问题 更多 >