嵌套if else语句未在Python中执行

时间:2020-02-13 02:06:52

标签: python-3.x if-statement nested sleep

我试图用Python 3编写一个程序,该程序将平均用户输入的睡眠时间,然后根据该平均值返回一条消息。该程序将不打印任何内容。没有显示错误。

这是我写的第一个if块。我的意思是让程序平均时间,然后根据年龄和平均时间打印一条语句。例如,如果用户是18岁并且平均睡眠8个小时,则它将打印|“睡眠太少”。

  import sys

  h1 = float(sys.argv[1]) 
  h2 = float(sys.argv[2])
  h3 = float(sys.argv[3])
  h4 = float(sys.argv[4])
  h5 = float(sys.argv[5])
  age = float(sys.argv[6])

  sleeph =(h1+h2+h3+h4+h5)/5

 if (age >18 and age < 25):
    if(sleeph>7 and sleeph<9):
        print(name,"  sleeps too little")
elif(sleeph>= 10 and sleeph<= 11):
    print(name,"sleeps enough")
else:
    print(name, " sleeps too much") `

我不知道自己在想什么。我认为它是在第一个if语句之后执行,然后退出程序。有任何想法吗?

2 个答案:

答案 0 :(得分:0)

您的第二个'if'语句检查是否小于9,而'elif'语句检查是否大于或等于10,这将完全排除9个。另外,您也忽略了少于7个小时的睡眠时间,这将是大多数18至25岁之间的人;)

name = 'Ranger Rick'
    sleeph = 9 
    age = 19
    if (age >18 and age < 25):
        if(sleeph<9):
            print(name,"  sleeps too little")
        elif(sleeph>= 9 and sleeph<= 11):
            print(name,"sleeps enough")
        else:
            print(name, " sleeps too much")

答案 1 :(得分:0)

您的缩进似乎是错误的。您应该先更正它。

h = [7.8, 4.5, 6.7, 10, 9]
age = int(input('Enter your age'))
sleeph = (h[0] + h[1] + h[2] + h[3] + h[4]) / 5
if age > 18 and age < 25:
    if sleeph > 7 and sleeph < 9:
        print('Sleeping too little')
    elif sleeph >= 10 and sleeph <= 11:
        print('Sleeping enough')
    else:
        print('Sleeping too much')

输出

Enter your age23
Sleeping too little

如果要检查年龄在18到25岁之间的所有if-else条件,则sleeph梯子应在主程序块中缩进。此外,如果还必须检查年龄条件,缩进会像

h = [7.8, 4.5, 6.7, 10, 9]
age = int(input('Enter your age'))
sleeph = (h[0] + h[1] + h[2] + h[3] + h[4]) / 5
if age > 18 and age < 25:
    if sleeph > 7 and sleeph < 9:
        print('Sleeping too little')
    elif sleeph >= 10 and sleeph <= 11:
        print('Sleeping enough')
    else:
        print('Sleeping too much')
elif age >= 25 and age <= 40:
    # if - else ladder for sleeph repeated
else:
    # Repeat the if - else ladder of sleeph for age > 40

希望这可以解决您的问题。