首页 > 解决方案 > 我的代码返回了错误的 if 语句

问题描述

我正在尝试编写一个简单的代码,它将为 18 岁以上的学生打开一扇门,但无论我输入什么数字,它总是在 if 语句中返回错误的选项。请看下面。

Def checkStudentAge:
 Input("what is your name student?: ")

Age = 0

If int(age) < 18
 Print("this door only opens for students that are 18 are above")

elif int(age)  > 18
 Print(" you are welcome, please push the door and step in")

else int(age) ==18
 Print("congrats you can step in)

CheckStudentage()

每当我调用该函数并输入一个高于 18 的 int 时,它仍然说“这扇门只为 18 岁及以上的学生打开”。我是 python 新手,这是我的第一语言,不胜感激

我做了年龄= 0,因为我想为年龄分配一个值,以防没有输入

标签: python

解决方案


def checkStudentAge():
  age = int(input("age: "))

  if age < 18:
    print('This door opens for students who are 18 or above')
  else:
    print('Welcome! Please push the door and step in')

  """ The if-else can also be combined into one line like so:

print('This door opens for students who are 18 or above') if age < 18 else print('Your are welcome, please push the door and step in')

  """
checkStudentAge()

elifandelse可以合二为一,else因为年龄是 [小于 18] 或 [大于或等于]。


推荐阅读