Reputation:
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)
I need to create a code which asks the user for a floating point number 'a' then an integer to use as the power of 'a' which is 'n'. I need to use a while loop and it must be valid for n>=0 only. If I don't have the elif statement then the code runs normally.
Upvotes: 0
Views: 93
Reputation: 530960
While technically you can put n >= 0
in the condition of the while
loop to skip the loop if n < 0
, it doesn't make sense to do so, because you never modify the value of n
in the loop. It would be clearer to put the entire loop in the body of another if
statement (which, incidentally, is the one which your elif
—or else
, as we'll see—would naturally belong to.)
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")
Upvotes: 1
Reputation: 734
You need to change the elif and if statement position
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")
Else if always comes after if
Upvotes: 0
Reputation: 493
It's invalid because you firstly need to add an if
statement and then follow it with an elif
.
if n < 0:
print("Integer value is less than 0")
elif n >=0 and n < count:
print(accum)
Upvotes: 0