python中的简单if..else逻辑不起作用

时间:2018-11-02 03:37:31

标签: python

下面的“你好”是确定某人是否有投票资格的简单逻辑。

下面的python脚本无论输入内容如何,​​都将显示为"you can vote"

age=raw_input("Enter age:")

if age < 18:
        print "cant vote"
elif age >= 18:
        print "you can vote"

python脚本o / p:

[root@localhost ~]# python test.py
Enter age:12
you can vote

[root@locahost ~]# python test.py
Enter age:23
you can vote

相同的逻辑在以下perl脚本中起作用

#!/usr/bin/perl

print"Enter age\n";
$age=<>;
chomp($age);

if($age < 18)
{
        print "cant vote\n";
}
elsif($age >=18)
{
        print "you can vote\n"
}

per scrit o / p:

[root@locahost ~]# perl perl.pl
Enter age
12
cant vote

[root@locahost ~]# perl perl.pl
Enter age
18
you can vote

if..else将如何在python中工作

2 个答案:

答案 0 :(得分:3)

是的,就像您在代码中看到的那样,您正在使用raw_input,它将把您作为参数传递的任何内容转换为字符串。所以基本上你的逻辑是

age=raw_input("Enter age:")


if age < 18: # i.e. '19' < 18 which is true
        print "cant vote"
elif age >= 18:
        print "you can vote"

我建议您使用输入法或将年龄转换为整数。

age=int(raw_input("Enter age:"))

age=input("Enter age:")

好运哥们.. !!

答案 1 :(得分:1)

您需要先将输入年龄转换为整数,然后再进行比较,如下所示:

age=int(raw_input("Enter age:"))

if age < 18:
        print "cant vote"
elif age >= 18:
        print "you can vote"