首页 > 解决方案 > 在while循环中看不到Python嵌套的If Then语句

问题描述

我正在开发一个菜单应用程序 (CLI),当用户从菜单中选择一个数字选项时,该应用程序会为每个选项执行不同的操作。但首先我想确保他们输入一个有效的数字然后做一些事情。如果不是有效数字,则循环菜单。如果选择了数字 9,则退出应用程序。问题是它似乎无法识别我的嵌套 if then 条件语句。它只看到第一个 if then 条件,然后再次循环菜单而不“做某事”。我如何让它识别嵌套的 if thens?

import datetime
import os
import pyfiglet

def main():
    Banner()
    menu()


def menu():
    choice =int('0')
    while choice !=int('9'):
        print("1. Show the banner again")
        print("2. View just a selected date range")
        print("3. Select a date range and show highest temperature")
        print("4. Select a date range and show lowest temperature")
        print("5. Select a data range and show the highest rainfall")
        print("6. Make a silly noise")
        print("7. See this menu again")
        print("9. QUIT the program")

        choice = input ("Please make a choice: ")

        if choice.isdigit():
          print(int(choice))
          if choice == 1:
            result = pyfiglet.figlet_format("P y t h o n  R o c k s", font = "3-d" )
            print(result)
          elif choice == 2:
            getWeather()
            choice == 0
          elif choice == 3:
            print("Do Something 3")
          elif choice == 4:
            print("Do Something 4")
          elif choice == 5:
            print("Do Something 5")
          elif choice == 6:
            os.system( "say burp burp burp burpeeeeee. I love love love this menu application")
          elif choice == 7:
            print("Do Something 7")
          elif choice == 8:
            print("Do Something 8")
          elif choice == 9:
            print("***********************************************************************")
            print("Goodbye! Program exiting.....")
            print("***********************************************************************")
            exit()
        else:
          print("Your choice is not an integer. Please try again")
          print("")
          continue

def Banner():
  result = pyfiglet.figlet_format("P y t h o n  R o c k s", font = "3-d" )
  print(result)

def getWeather():
  weatherdata1 = print(input("What date would you like to start your weather data query with? Please    enter the date in this format YYYYMMDD"))
  weatherdata2 = print(input("What date would you like to end your weather data query with? Please enter the date in this format YYYYMMDD"))
  print(weatherdata1)
  print(weatherdata2)


main()

标签: python-3.xloopsif-statementnested

解决方案


您必须将输入转换为int

choice = int(input ("Please make a choice: "))

或者,您需要int在比较时将选择转换为。像这样:

if int(choice) == 1:
    result = pyfiglet.figlet_format("P y t h o n  R o c k s", font = "3-d" )
    print(result)
elif int(choice) == 2:
    getWeather()
    choice == 0
...

推荐阅读