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

问题描述 投票:1回答:2

我正在尝试使用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语句之后执行,然后退出程序。有任何想法吗?

python-3.x if-statement nested sleep
2个回答
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

if-else梯子应在主块内缩进,因为要检查18至25岁年龄段的所有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

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


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")
© www.soinside.com 2019 - 2024. All rights reserved.