简体   繁体   English

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

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

I am somewhat new to Python and coding in general, and I require some help working with raw_input and an if statement.我对 Python 和一般编码有点raw_input ,我需要一些帮助来处理raw_inputif语句。 My code is as follows;我的代码如下;

    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"

Issues问题

There are three issues with your code:您的代码存在三个问题:

  • Python uses indentation for creating blocks. Python 使用缩进来创建块。
  • You've assigned the input to the variable age , so use age .您已将输入分配给变量age ,因此请使用age
  • In Python 3, you have to use print(...) instead of print ...在 Python 3 中,你必须使用print(...)而不是print ...

Correct solution正确的解决办法

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

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

Note that this is not equivalent to your code.请注意,这不等同于您的代码。 Your code skips the case age == 14 .您的代码跳过 case age == 14 If you want this behaviour, I suggest:如果你想要这种行为,我建议:

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

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

Learning Python学习 Python

if int(raw_input) < 14:

Should be int(age) , and same for the other if .应该是int(age) ,另一个if应该是一样的。 raw_input is the function you called, but you stored the result from it in the variable age . raw_input是您调用的函数,但您将其结果存储在变量age You can't turn a function into an integer.你不能把一个函数变成一个整数。

Rather than converting the age to an integer repeatedly, you could just do it once, when you do the input:而不是反复将年龄转换为整数,你可以只做一次,当你做输入时:

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

Then you can just do if age > 14 and so on, since it's already an integer.然后你可以做if age > 14等等,因为它已经是一个整数。

I assume the indentation problems (the line following each if should be indented at least one space, and preferably four) are just a formatting issue.我假设缩进问题(每个if后面的行应该缩进至少一个空格,最好是四个)只是一个格式问题。

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

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