“NameError:Python3.8中未定义名称“day\u time”错误

2024-05-13 00:32:34 发布

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

我正在制作一个程序,根据输入的时间显示一天中的部分时间

我的代码:

user_day = input("What's the time? ")

if user_day >= 20 and user_day <= 24:
    day_time = "Night"

elif user_day >= 24 and user_day <= 12:
    day_time = "Morning"

elif user_day >= 12 and user_day >= 17:
    day_time = "Noon"

elif user_day >= 17 and user_day >= 20:
    day_time = "Evening"

但我得到了这个错误:

if day_time == 1 and user_weather == plus:
NameError: name 'day_time' is not defined

请帮帮我


Tags: andthe代码程序inputiftime时间
3条回答

如果希望以后使用它,则需要在if块的上下文之外声明day_time

比如说:

user_day = input("What's the time? ")

day_time = None

if user_day >= 20 and user_day <= 24:
    day_time = "Night"

elif user_day >= 24 and user_day <= 12:
    day_time = "Morning"

elif user_day >= 12 and user_day >= 17:
    day_time = "Noon"

elif user_day >= 17 and user_day >= 20:
    day_time = "Evening"
  • 问题是,user_day作为输入输入时是一个字符串。
    • 因为它是一个字符串,所以不满足任何条件,因此day_time仍然未定义。
      • 将输入包装在try-except块中,以检查输入是否为正确的数据类型。在本例中,str类型,可以转换为intfloat
    • 它必须转换为intfloat,这取决于您只接受小时还是分数小时
  • user_day应处于while True循环中,以继续请求时间,直到收到有效的数字输入
  • 最后,在这种情况下,通过将条件从最小到最大进行适当排序,可以更有效地编写代码。
    • user_day将逐步下降到正确的状态
while True:
    try:
        user_day = int(input("What's the hour on a 24-hour scale? "))
    except ValueError:  # checks for the correct data type; maybe someone will spell the hour
        print('Please enter the hour as a numeric value')
    
    if (user_day >= 24) or (user_day < 0):  # 24 and over or less than 0 are invalid times
        print('Please enter a valid time')
    else:
        break  # break when there's valid input

if user_day < 12:
    day_time = 'Morning'
elif user_day < 17:
    day_time = 'Noon'
elif user_day < 20:
    day_time = 'Evening'
else:
    day_time = 'Night'
    
print(day_time)

使用^{}

  • 返回每个输入值所属的存储箱的索引
  • 使用np.digitize返回的值为day_time中的正确值编制索引
import numpy as np

while True:
    try:
        user_day = int(input("What's the hour on a 24-hour scale? "))
    except ValueError:  # checks for the correct data type; maybe someone will spell the hour
        print('Please enter the hour as a numeric value')
    
    if (user_day >= 24) or (user_day < 0):  # 24 and over or less than 0 are invalid times
        print('Please enter a valid time')
    else:
        break  # break when there's valid input

day_time = ['Morning', 'Evening', 'Noon', 'Night']
idx = np.digitize(user_day, bins=[12, 17, 20])
    
print(day_time[idx])

您需要在else语句中定义day_time,这样当两个现有条件都不满足时,day_time仍将有一个值

此外,您需要将用户的输入转换为整数,然后才能对其使用带有字符串的<>等运算符:

user_day = int(input("What's the time? "))

if user_day >= 20 and user_day <= 24:
    day_time = "Night"

elif user_day >= 24 and user_day <= 12:
    day_time = "Morning"

elif user_day >= 12 and user_day >= 17:
    day_time = "Noon"

elif user_day >= 17 and user_day >= 20:
    day_time = "Evening"

else:
    day_time = "Unknown"

相关问题 更多 >