在应用`raw_input`时如何使用`if`?

时间:2014-04-03 21:44:42

标签: python

我对Python和编码有点新手,我需要一些使用raw_inputif语句的帮助。我的代码如下;

    age = raw_input ("How old are you? ")
    if int(raw_input) < 14:
    print "oh yuck"
    if int(raw_input) > 14:
    print "Good, you comprehend things, lets proceed"

2 个答案:

答案 0 :(得分:3)

问题

您的代码有三个问题:

  • Python使用缩进来创建块。
  • 您已将输入分配给变量age,因此请使用age
  • 在Python 3中,您必须使用print(...)而不是print ...

正确的解决方案

age = raw_input("How old are you? ")

if int(age) < 14:
    print("oh yuck")
else:
    print("Good, you comprehend things, lets proceed")

请注意,这不等同于您的代码。您的代码会跳过案例age == 14。如果你想要这种行为,我建议:

age = int(raw_input("How old are you? "))

if age < 14:
    print("oh yuck")
elif age > 14:
    print("Good, you comprehend things, lets proceed")

学习Python

答案 1 :(得分:0)

if int(raw_input) < 14:

应为int(age),其他if应相同。 raw_input是您调用的函数,但您将结果存储在变量age中。你不能把一个函数变成一个整数。

当您进行输入时,您可以只执行一次,而不是将年龄重复转换为整数:

age = int(raw_input("How old are you? "))

然后你可以if age > 14等等,因为它已经是一个整数。

我假设缩进问题(每个if后面的行应缩进至少一个空格,最好是四个)只是格式化问题。

相关问题