繁体   English   中英

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

[英]How do you use `if` when applying a `raw_input`?

我对 Python 和一般编码有点raw_input ,我需要一些帮助来处理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"

问题

您的代码存在三个问题:

  • 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")

请注意,这不等同于您的代码。 您的代码跳过 case 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后面的行应该缩进至少一个空格,最好是四个)只是一个格式问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM