为什么elif语句在此代码中无效?

时间:2019-10-26 14:33:21

标签: python

a = float(input("Insert a floating point number:"))
n = int(input("Insert an integer number >= 0 :"))
accum = 1
count = 1

while n >= count and n >= 0: 
  accum = accum * a
  count += 1
elif n < 0:
    print("Integer value is less than 0")
if n >=0 and n < count:
  print(accum)

我需要创建一个代码,要求用户输入浮点数“ a”,然后再使用一个整数作为“ a”的幂(n)。我需要使用while循环,并且它仅对n> = 0有效。如果我没有elif语句,则代码可以正常运行。

3 个答案:

答案 0 :(得分:1)

从技术上讲,您可以将n >= 0置于while循环的条件下,以在n < 0时跳过循环,但这样做是没有意义的,因为您永远都不会修改循环中n 的值。将整个循环放在另一个if语句的主体中会更清楚(顺便说一句,这是您的elifelse所要看到的那个语句自然地属于。)

a = float(input("Insert a floating point number:"))
n = int(input("Insert an integer number >= 0 :"))
accum = 1
count = 1

if n >= 0:
    while n >= count: 
        accum = accum * a
        count += 1

    # We already know n >= 0, and the only way
    # for the loop to exit is for n < count to be
    # true, so no additional testing needed before
    # we call print here.
    print(accum)
else:  # If n >= 0 is not true, n < 0 *must* be true
    print("Integer value is less than 0")

答案 1 :(得分:0)

这是无效的,因为您首先需要添加if语句,然后在其后加上elif

if n < 0:
    print("Integer value is less than 0")
elif n >=0 and n < count:
  print(accum)

答案 2 :(得分:0)

您需要更改elif和if语句的位置

while n >= count and n >= 0: 
  accum = accum * a
  count += 1
if n >=0 and n < count:
      print(accum)
elif n < 0:
    print("Integer value is less than 0")

否则,如果总是在之后,则