简单的Python" if"," elif"," else"

时间:2014-10-30 23:15:36

标签: python if-statement

在课堂上用Python创造一个“疯狂的自由”风格的东西,这是我的第一天,我已经掌握了大部分我需要知道的东西,但我不知道如何使用“if” ,“elif”,“其他”的东西。到目前为止,这就是我所拥有的,基本上,当年龄输入时,我希望它选择这个人是成年人还是孩子。

print "welcome to your short story"

name = raw_input("Input your name: ")
age = raw_input("Input your age: ")

if age > 21:
    age = "adult"
elif age < 21:
    age = "kid"


print "My name is ",name,"and I am a " ,age,"year old ",age

4 个答案:

答案 0 :(得分:0)

正如foxygen所建议的那样,需要使用int函数将输入从字符串转换为int

age = int(raw_input("Input your age: "))

字符&#34; 1&#34;,&#34; 2&#34;,&#34; 3&#34;之间存在差异。依此类推,以及数字1,2,3等。有些语言试图为你转换,但是python不会这样做,所以你最终会比较&#34; 32&#34;到21,这是一个苹果与橘子的比较。

此外,虽然您在这个特定情况下非常安全,但在您仍然根据其原始值进行计算时,您会注意到您重新分配年龄的方式。这通常不安全,你最好分配一个新的变量:

if age > 21:
    age_label = "adult"
elif age < 21:
    age_label = "kid"
else:
    age_label = "person" # in case a 21 year old uses your program

在这种情况下你是安全的,因为if / else构造只会执行一个分支,但最好不要养成在你还没有重写输入值的习惯咨询它。

答案 1 :(得分:0)

我意识到我需要一个不同的值并且已经改变了它。

print "welcome to your short story"

name = raw_input("What is your name?: ")
age = raw_input("How old are you?: ")
sex = raw_input("Are you a boy or a girl?: ")

if age > 21:
    targetAge = "adult"
elif age < 21:
    targetAge = "kid"


print "My name is ",name,"and I am a " ,age,"year old ",targetAge,"."

所以,基本上,当它被打印时,它应该是“我的名字是_____,我是一个__年的孩子/成年人”。取决于他们输入的数量。我没有使用int()函数的原因是因为从未提及过,这实际上是课程的第一天,所以我将按照教师的说法进行操作。

答案 2 :(得分:0)

1)你用孩子的成人字符串覆盖输入的年龄。 2)当年龄等于21岁时,你必须处理这个案子。 3)年龄输入需要转换为整数。

让我们重写您的代码,看看我们如何改进:

print "welcome to your short story"

name = raw_input("Input your name: ")
# Convert the input to an integer.
age = int(raw_input("Input your age: "))

# This is the status variable being either adult or child
# before you were overriding age variable with adult or kid
status = ""

# Also, you have to handle the case where the age equals 21, before 
# you were just checking if it is less or greater than 21
if age >= 21:
    status = "adult"
elif age < 21:
    status = "kid"

print "My name is ", name ," and I am a " , age ," year old " , status

答案 3 :(得分:0)

print "Welcone to your Story"
name = raw_input("Please enter yout name: ")
    age = int(raw_input("please enter your age: "))
    if age >= 21:
        status = "an adult"
    else:
        #enter code here
        status = "a kid"
    print "My name is %r , I am  %r and I am %r years old" %(name,status,age)