我的代码中存在变量问题。以下是我的部分代码:
import re
name = raw_input("Input the Character's name: ")
name = name.lower()
season = raw_input("Input the season: ")
rainyday = raw_input("Is it a rainy day? ")
total_time = raw_input("What time is it?(Input as e.g 1.30 am")
non_decimal = re.compile(r'[^\d.]+')
timel = non_decimal.sub('', total_time)
float(timel)
print timel
#ALEX
if name == "alex":
if rainyday == "yes":
if "am" in total_time:
if time > 8.00:
print("He's in the entryway of his house until 1:00 PM")
else:
print("He's in his room until 8:00 AM")
print("!")
elif timel < 1:
print("He's in the entryway of his room until 1:00 PM")
print("y")
elif timel < 4.2:
print("He's leaving his room to go to the dog pen until 6:30 PM")
elif timel < 6.3:
print("He's at the dog pen until 6:30")
elif timel < 8.0:
print("He's in the entryway of his house until 8:00 P.M")
elif timel < 10.0:
print("He's standing by the dresser in his room")
else:
print("He's sleeping")
每当我输入total_time作为一个带有“pm”的数字,我就会得到else语句“他在睡觉” 我在shell上运行的这些代码行说明了我的问题:
>>> print timel
2
>>> timel < 3
False
>>> 2 < 3
True
>>> timel < 1000000000
False
似乎timel始终是一个未定义的数字,它比其他任何东西都大,即使它已经被定义。我非常感谢您对这个问题的帮助
最后一行不会将
timel
转换为floatfloat
无法正常工作在此之后,
timel
仍然是一个字符串,并且比较时没有错误,但是在Python2中使用整数/浮点数会产生奇怪/意外的结果(在Python3中,它失败了,出现异常(unorderable types: str() < int()
),这至少指出了错误)修正:
您希望使用
float(timel)
将字符串转换为浮点数float( a )
返回转换为浮点的a
,但不接触原始参数因此,行应该是
timel = float(timel)
以实际转换timel
相关问题 更多 >
编程相关推荐