如何循环if,elif else语句?

时间:2017-06-07 11:55:45

标签: python-3.x loops if-statement input

我正在为项目编写代码,我想要一些帮助。

当用户输入除男性或女性以外的其他内容时,会打印消息"错误!请输入有效的性别!",但它不会重新运行输入声明,因此不会让他们选择性别。我想知道在用户收到错误消息后如何重新运行输入行。请让我知道如何使用Python 3.0做到这一点!

这是我的代码:

Gender = input("Your Gender (Male / Female):")
gender = Gender.lower()
if gender == "male":
  heorshe = "he"
  hisher = "his"
  himher = "him"
  himselfherself = "himself"
  HeShe = "He"
elif gender == "female":
  heorshe = "she"
  hisher = "her"
  himher = "her"
  himselfherself = "herself"
  HeShe = "He"
else:
  print("Error Please enter a valid gender!")
  print('\n')
  gender = False

我将非常感谢给予我任何帮助!

1 个答案:

答案 0 :(得分:0)

封装在while循环中,然后在找到您正在寻找的内容时突破它!

while(True):
  gender = input("Your Gender (Male / Female):").lower()
  if gender == "male":
    heorshe = "he"
    hisher = "his"
    himher = "him"
    himselfherself = "himself"
    HeShe = "He"
    break
  elif gender == "female":
    heorshe = "she"
    hisher = "her"
    himher = "her"
    himselfherself = "herself"
    HeShe = "He"
    break
  else:
    print("Error Please enter a valid gender!")
    print('\n')