为什么if语句没有执行?

时间:2017-09-10 01:50:42

标签: python-3.x if-statement

我有一项任务,我必须询问用户是否要将新学生添加到某个程序中。 我设置一个变量来保存用户命令,然后: 如果是(1),程序将要求用户输入名称和ID,否则,程序将退出。

students = []

def get_students_titleCase():
    students_titleCase = []
    for student in students:
        students_titleCase = student["name"].title()
    return students_titleCase

def print_students_titlecase():
    students_titleCase = get_students_titleCase()
    print(students_titleCase)

def add_student(name , student_id = 000):
    student = {"name" : name , "student_id": student_id }
    students.append(student)

user_command = input("Do You Want to Add a Student Name?\n1- Yes\n2- No\n")
#user_command = 1
if user_command == 1:
    student_list = get_students_titleCase()
    student_name = input("Enter Student Name: ")
    student_id = input("Enter Student ID: ")
    add_student(student_name, student_id)
    print_students_titlecase()

1 个答案:

答案 0 :(得分:1)

如果在python2.7上执行,则行为将按预期执行,但由于其Python 3 input返回str类型raw_input类似python 2.7返回raw_input }。另请注意,python 3中引入了# Compare against string instead of int if user_command == '1':

因此,考虑到上述观点,您必须稍微更改一下代码才能使其正常工作。

int

但是,如果您仍想与if user_command.isdigit() and int(user_command) == 1: 类型的数量进行比较,那么

  cd usr
cd home
FOLDERS=*
L=".bash_login"
P=".bash_profile"
for f in $FOLDERS
do
 cd "$f"
 if [ -f ".bash_login" ]
 then 
 grep "/etc/runner" $L >/dev/null 
     if [ $? -eq 0 ]
     then
          #use swap ex
          ex $L <replace.ex
          echo "replaced"
     else
          ex $L <insert.ex
          echo "inserted"
          #use insert at end ex
     fi; 
 else 
    grep "/etc/runner" $P >/dev/null
    if [ $? -eq 0 ] 
    then
        # use swap ex
        ex $P <replace.ex
        echo "replaced"
    else 
        ex $P <insert.ex
        echo "inserted"

    fi; 
 fi;
 cd ..
 done