应用“原始输入”时如何使用“if”?

2024-03-28 14:38:22 发布

您现在位置: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"

Tags: 代码you编码inputagerawif语句
2条回答

问题

您的代码有三个问题:

  • Python使用缩进来创建块。你知道吗
  • 您已经将输入赋给变量age,所以使用age。你知道吗
  • 在python3中,必须使用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

if int(raw_input) < 14:

应该是int(age),对于其他if也是一样的。raw_input是您调用的函数,但您将其结果存储在变量age中。你不能把一个函数变成整数。你知道吗

与其重复将年龄转换为整数,不如在输入时只执行一次:

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

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

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

相关问题 更多 >