python 3的范围和输入?



我在编写一个程序时遇到了麻烦,该程序要求一个月中的天数,只接受28到31之间的值;然后继续请求,直到接收到可接受的值。然后询问每天的最高温度(以华氏度为单位)。只接受-50和110之间的值;继续请求每天的值,直到收到一个可接受的值。

这是我目前所知道的。我得到一个TokenError: EOF in multi-line statement on line 11错误。我在如何提示用户输入每天的高温范围上卡住了——我拥有的最后一行。

totalnumberofday=0
totalDayHighTemp=0
num = int(input("Enter the number of days in a month:"))
if num <=28 or num>=31:
num=int(input("please reenter an acceptable value:"))
for i in range(1, num+1):
DayHighTemp=float(input("Please enter the daily high temperature"+ format(i+"d"))

这里有几个问题,让我们一个一个地来演示如何解决:

File "a.py", line 12

^
SyntaxError: unexpected EOF while parsing

SyntaxError表示脚本的语法或语法有问题。该消息告诉我们,它到达文件结束时,它正在等待更多的代码。查看代码,在关闭DayHighTemp=float(...语句的最后一行缺少)。添加)可以解决此问题。

再次运行文件,我们得到这个问题:

Enter the number of days in a month:30
Traceback (most recent call last):
File "a.py", line 10, in <module>
DayHighTemp=float(input("Please enter the daily high temperature"+ format(i+"d")))
TypeError: unsupported operand type(s) for +: 'int' and 'str'

这里,它说我们不能把整数和字符串加在一起。看起来format(i+"d")应该是format(i,"d")


现在,我们终于可以解决你的核心问题了:"继续询问,直到它收到一个可接受的值"。

询问有效日期的解决方案是只检查一次,但不检查是否第二次输入:

num = int(input("Enter the number of days in a month:"))
if num <=28 or num>=31:
num=int(input("please reenter an acceptable value:"))
相反,最好继续问问题,直到收到有效的响应——或者,更确切地说,当响应中有效时,继续问

。虽然有多种方法可以做到这一点,但这里有一种方法:

num = int(input("Enter the number of days in a month:"))
while num <=28 or num>=31:
num=int(input("please reenter an acceptable value:"))

我将把它留给你作为练习来调整它以确保有效的温度。

最新更新