Reputation: 11
I am doing CS105 on saylor academy and i'm on the unit 3 quiz and one of the questions asks for:
Write a Python code snippet use 'if-elif' (i think that they mean if-else, because it later asks to use a if-elif-else statment, so if theres any confusion they meant if else instead of "if-elif") flow control along with a 'while' loop that will:
Instruct a user to input a number that is greater than 0 and less than or equal to 10 and store the input as a floating-point value in a variable
If the input number is greater than 0 and less than or equal to 10, use a 'while' loop in order to add the number to itself until the sum exceeds a value of 100.
After the sum has exceeded a value of 100, use the print statement to output the sum Otherwise, output the message 'You did not enter a value between 1 and 10'
I have only been able to get this code down and think the overall structure of the if-else and the while loop with another if-else inside.
Could anyone more experienced maybe recommend me some tweaks to the code so it functions and meets the requirements. I kept getting infinite while loops even though I tried using the break function so I resorted to using true and false but this doesn't work either.
here what I have so far:
inval=float(input('Input a number greater than zero and less than or equal to 10: ')) if(inval>0)and(inval<=10): while True: if(inval<100): inval+inval else: inval=False print(inval) else: print('You did not enter a value between 1 and 10')
I tried to make a for-else loop so that if the input was in the constraints then it would preform the while loop but I got confused when I had to add another conditional statement (which was supposed to stop the while loop when it added the digit to its self enough times where it was greater than 100) but I was unable to do so and this is where I became stuck.
Upvotes: 1
Views: 319
Reputation: 437
There a few issues due to which your code isn't working.
A working code would look something like this:
inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if (inval > 0) and (inval <= 10):
running = True
result = 0
while running:
if (result < 100):
result = result + inval
else:
running = False
print(result)
else:
print('You did not enter a value between 1 and 10')
A few more improvements that I'd suggest would be that you could check the condition in the while loop instead of having an if statement within it. Python also supports chaining conditions, you could simplify your first if condition as well. This would make your code look something like this:
inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if 0 < invalid <= 10:
result = 0
while result < 100:
result = result + inval
print(result)
else:
print('You did not enter a value between 1 and 10')
Upvotes: 0