在python中输入变量

时间:2018-05-01 22:07:16

标签: python python-3.x

我是python的新手,需要一些帮助,我正在尝试创建一个简单的if / else脚本。

我以前的版本按原样运行,我必须对用户输入变量而不是预先确定的变量进行唯一更改。但是我在最后一行遇到语法错误,任何人都可以告诉我哪里出错了。

我的代码是

    hour = input('enter an hour')

if hour >= 0 and hour < 12:
    clock = hour, 'pm' # assigning the variable here as necessary

elif hour >= 12 and hour < 23:
    clock = hour, 'pm' # assigning the variable here as necessary

else:
    clock = 'That is not a time on the clock.'
print(clock)

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

这里有多个问题:

  • 在Python缩进中(如果你愿意的话,来自一行或多个制表符的空格)对于区分代码的不同范围很重要,比如函数,if语句等。你的第一行有这样的无效缩进。
  • input('enter an hour')此函数读取用户的输入并将其作为字符串返回,无论您是否提供数值。您需要使用int()将其转换为实际数值,以便您可以执行范围检查,如&#34;如果大于0且小于10&#34;例如。显然,如果你没有将它转换为整数并且你正在使用字符串,则不能进行这样的范围检查,因为该值不被视为数值。

这是一份工作副本:

hour = int(input('Enter an hour: '))

if hour >= 0 and hour < 12:
    clock = "{}am".format(hour)
elif hour >= 12 and hour < 23:
    clock = "{}pm".format(hour)
else:
    clock = 'That is not a time on the clock.'

print(clock)

答案 1 :(得分:1)

有3个错误:

  1. 您的第一行不应缩进。
  2. 将您的input转换为数字类型,例如floatint
  3. 0到12之间的小时应该是&#34; am&#34;而不是&#34; pm&#34;。
  4. 这将有效:

    hour = float(input('enter an hour'))
    
    if hour >= 0 and hour < 12:
        clock = hour, 'am' # assigning the variable here as necessary
    
    elif hour >= 12 and hour < 23:
        clock = hour, 'pm' # assigning the variable here as necessary
    
    else:
        clock = 'That is not a time on the clock.'
    
    print(clock)
    

答案 2 :(得分:0)

错误是IndentationError: unexpected indent这意味着你要编写缩进的代码行。那是不对的。要解决它,请删除第一行之前的空格。

您还必须指定输入类型。 hour = int(input('enter an hour'))