while True:
n1 = int(input("Enter first number: "))
if n1>255:
print("Invalid input. Sorry the number should be less than 255.")
continue
elif n1<255:
print("The input is valid.")
n2 = int(input("Enter second number: "))
if n2>255:
print("Invalid input. Sorry the second number should be less than 255.")
continue
elif n2<255:
print("The input is valid.")
break
Whenever I enter 'n2' higher than 255, it shows enter first number. I want it to show enter second number.
continue starts the whole while loop over: it doesn't go back to before the last if statement or anything like that. So your second continue effectively starts your program over. You need to get rid of this continue, and use some other method to redo this input.
The problem is the continue statement in the first if. continue does not mean "go on". It means, "ignore the rest of the while/for loop, and repeat from its next iteration". So, actually, the next time you are at the input prompt, are not entering n2, you are again the the same line and entering n1 again. Remove the continue statement.
Take a look at how break and continue statements work, they are pretty much the same in all languages (that I know of at least)
Related
I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function
The question I have is about the flag I have here for the while loop. This works but not like I think it should. I assume I'm not understanding something so if someone is able to explain, that would be great.
From my understanding this should break out of the loop as soon as one of my conditionals is met. So if I input 'q' it should break out and stop the loop. But what happens is it keeps going through the loop and then it breaks out. so it goes through the last prompt and prints the exception.
(Python version is 3.8.5)
# Statement that tells the user what we need.
print("Enter two numbers and I will tell you the sum of the numbers.")
# Lets the user know they can press 'q' to exit the program.
print("Press 'q' at anytime to exit.")
keep_going = True
# Loop to make the program keep going until its told to stop.
while keep_going:
# Prompt for user to input first number and store it in a variable.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
# Exception for non integers being input "ValueError"
try:
# Convert input to integers and add them.
# storing the answer in a variable.
answer = int(first_number) + int(second_number)
except ValueError:
# Tell the user what they did wrong.
print("Please enter a number!")
else:
# Print the sum of the numbers
print(f"\nThe answer is: {answer}")
Using this code it breaks out right away like I expect it to.
while True:
first_number = input("First number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
if second_number == 'q':
break
I just would like to understand what the difference is and if thats how it should work. I feel like I'm missing something or misunderstanding something.
The condition of the while loop is only checked between iterations of the loop body, so if you change the condition in the middle of the loop, the current iteration will finish before the loop terminates. If you want to break a loop immediately, you need to either break (which automatically breaks the loop regardless of the condition) or continue (which jumps to the next iteration, and will therefore terminate the loop if the condition is no longer true).
Using while True: with a break when you want to stop the loop is generally much more straightforward than trying to control the loop by setting and unsetting a flag.
FWIW, rather than copying and pasting the code to input the two numbers, and have two different ways to break out of the loop, I might put that all into a function and break the loop with an Exception, like this:
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
def input_number(prompt: str) -> int:
"""Ask the user to input a number, re-prompting on invalid input.
Exception: raise EOFError if the user enters 'q'."""
while True:
try:
number = input(f"{prompt} number: ")
if number == 'q':
raise EOFError
return int(number)
except ValueError:
print("Please enter a number!")
while True:
try:
numbers = (input_number(n) for n in ("First", "Second"))
print(f"The answer is: {sum(numbers)}")
except EOFError:
break
This makes it easier to extend the program to handle more than two inputs; try adding a "Third" after where it says "First" and "Second"! :)
Once you run the program and type "q", Yes indeed keep_going will be set to False but it DOES NOT MEAN it will break the loop already, it will just make the keep_going be equal to False thus on the NEXT ITERATION will stop the loop. Why is that? because it would be like this while keep_going: -> while False: so since it is not True thus not executing the program anymore.
Now based on your goal as you mentioned. You can do it this way where you can add the break.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
second_number = input("Second number: ")
# Create a break when entering the second number.
if second_number == 'q':
keep_going = False
break
I'd also like to suggest have it this way, it's just more specific in terms of what is to happen on the code, but of course it is up to you.
first_number = input("First number: ")
# Create a break when entering the first number.
if first_number == 'q':
keep_going = False
break
# Prompt for user to input second number and store it in a variable.
# Create a break when entering the second number.
else:
second_number = input("Second number: ")
if second_number =='q':
keep_going = False
break
While loops execute until their given condition is false. A loop will only check its condition when required (program execution is moved to the top of the loop). In almost every case, this occurs when the full body of the loop has run. See here:
keep_going = True
while keep_going:
keep_going = False
# keep_going is False, but this will still print once
# because the loop has not checked its condition again.
print("Will execute once")
"Will execute once" prints a single time even after keep_going is set to False. This happens because the while loop does not re-check its condition until its entire body has run.
However, break statements are different. A break statement will cause a loop to exit immediately no matter what.
keep_going = True
while keep_going:
break # Exits the while loop immediately. The condition is not checked.
print("Will never print")
Here, nothing is printed even though keep_going is True the whole time. break made the loop exit regardless of the condition.
A continue statement will move program execution back to the start of the loop, and cause your condition to be checked again.
In this example, continue sends program execution back to the start of the loop. Since keep_going was set to False, nothing will print because the while loop will exit after realizing its condition evaluates to false.
keep_going = True
while keep_going:
keep_going = False
continue
print("Will never print")
First off, hope you have a great time learning Python!
Both ways will work and stop the loop, but there is a difference:
In the first method, you are changing the keep_going variable to false, therefore, the loop will stop when the the while loops finds out that keep_going had become False. However, the checking only happens at the end of the loop (In your case, it is after you have done your except or else part), the loop will not stop right away even when you entered q for your variable first_number.
In the second solution, you are using the break keyword in Python, to break away from the loop right away after you entered q for first_number.
Technically speaking, you will want to break if you want to break off from the loop right away when q is detected, otherwise, setting keep_going to False if you want the whole loop to be completed, but not run again for the next round.
In scenario 1 the result, even when you entered q,
Please enter a number!
Will always show, but not for scenario 2.
this is a little different approach to your script:
def main():
print("Enter two numbers and I will tell you the sum of the numbers.")
print("Press 'q' at anytime to exit.")
val = []
while True:
check_value = lambda x: 'quit' if x.lower() == 'q' or x.lower() == 'quit' else int(x)
if not val:
value = input("First number: ")
elif len(val) == 2:
answer = sum(val)
print(f"\nThe answer is: {answer}")
print('==='*15 + ' < ' + f'PROGRAM RESTARTING' + ' > ' + '==='*15)
val[:] = []
continue
else:
value = input("Second number: ")
try:
check_ = check_value(value)
val.append(check_)
except ValueError:
print("Please enter a number!")
continue
finally:
if check_ == 'quit':
print('Program is stopping....')
break
else:
pass
if __name__ == '__main__':
main()
It check at anytime the user's input, whether is a 'q' 'Q' or ('quit' or 'QUIT') or any combination or capital letter because run the check x.lower()
I suggest you to have a look at realpython.com especially the paragraph "he Python break and continue Statements."
Long story short:
Use Break to terminate the loop at any given time.
Use continue to roll back where you left and repeat the loop again (I used it in my code if the value is not a Int)
User pass to keep the loop running with no stop.
Python newbie. I am trying to print number after taking input from user using while loop.
my code takes int from user and then runs the loop. after printing the first number the code asks to continue after which the loop will continue.
My code is below:
i = 1
ans = 'n'
x = int(input("enter a number to loop: " ))
while(i<x):
print('\n')
print(i, end= " ")
ans = input('\ndo you want to print the next number? ')
if ans == 'y':
i += 1
else:
print('thanks')
The code is doing and extra loop and then after getting the answer terminates the loop. On top of that on the last loop if the answer is 'n' it keeps running.
You just have to add a break statement in your code, right before the print("thanks") line. That will exit the loop.
else:
break
print('thanks')
All loops will continue unless told to break or become false.
Break and continue are very important in programming. I suggest you read this https://www.tutorialspoint.com/python/python_loop_control.htm
I am currently attempting to solve a homework problem. The problem states to collect user inputted numbers and then arrange them using asterisks to display a graph, with the largest number having forty asterisks and the rest becoming smaller as the numbers decrease.
_NumberList= []
print("Please type 'quit' to stop entering numbers.")
print("Please type 'print' to view the list that has been entered so far.")
a= True
while a:
_number= input("Please enter a number or make a selection. ")
if _number.isdigit():
_number=int(_number)
_NumberList.append(_number)
elif _number.isalpha():
_number= _number.lower()
if _number== 'quit':
a= False
if _number== 'print':
print(_NumberList)
else:
print("Please use digits to enter a number.")
print("For exmaple: 'ten' should be typed at '10'")
else:
print("Invalid entry.")
_NumberList.remove(max(_NumberList))
for i in range(len(_NumberList)):
_NumberList.remove(max(_NumberList))
However, I am unsure as to how to find the given proportions utilizing the numerical data. Thus far, I have considered utilizing the .pop function, but it simply isn't making a ton of sense so far. I considered making them go up by one step, but again, that doesn't seem logical, and the program can run for more than forty numbers. I know I will need to utilize a loop, hence the for loop at the end, but I'm not sure as to how to continue from there.
Your variable name _NumberList makes my eyes hurt, so I'll call it number_list
largest_number = max(number_list)
scale_factor = 40 / largest_number
scaled_number_list = [int(x * scale_factor) for x in number_list]
for scaled_number in scaled_number_list:
print('*' * scaled_number)
I'm new to Python and I was wondering if I could get some help. I think everything is working, except for it outputing Guess higher/lower prompt and then printing out Enter a number: instead of asking for the second Guess higher/lower prompt. I want it to say the second Guess prompt, not Enter a number: I hope that's explained well enough. If not, I will update it.
from random import randint
N=randint(0,100)
i=1000
a=0
n=int(N)
while i!=n:
I=int(input('Enter a number: '))
i=int(I)
a=a+1
while i>n:
i=int(input('Guess lower: '))
a=a+1
while i<n:
i=int(input('Guess Higher: '))
a=a+1
while i==n:
print('Correct')
print('You took',a,'attempts.')
break
The behaviour that you want is not a work for while loops. While loops are used for iteratively executing a piece of code until a condition is met. While, stricly speaking, this is true for your code, the nesting that you have implemented and the overall structure of your code is not correct.
It would be much better if you used if and else statements. These are used for deciding about something and, based on whether it is true or false, executing a piece of code. If you think about it, this is exactly the inherent nature of the problem you are trying to solve. The code would look something like this:
from random import randint
N=randint(0,100)
i=1000
a=0
n=int(N)
#Ask for initial input
i=int(input('Enter a number: '))
a=a+1
#Start loop that loops until i == n
while i!=n:
if i>n:
i=int(input('Guess lower: '))
a=a+1
elif i<n:
i=int(input('Guess Higher: '))
a=a+1
else:
print('Correct')
print('You took',a,'attempts.')
If you are woindering about the elif, it is a statement that gets executed if the if statement is not true and if the condition following elif is true. You can have multiple elif's. Have a look at any beginner tutorial to learn more.
Remember the DRY principle (Don't Repeat Yourself) whenever you see duplication. Also, no need to comment obvious things.
First thing to notice is that there are things you are doing over and over like a=a+1 and input. Try not to repeat yourself.
The second thing to notice, is that in every loop the only thing that changes is the prompt. Try to isolate that change.
Last thing is to know is how while loops work. You only have one loop, so you only need 1 while. So the loop will stop when i == n and thus that is the only time that "Correct" will print.
My final code:
from random import randint
a = 0
i = -1
n = randint(0, 100)
prompt = "Enter a number: "
while i != n:
a += 1
i=int(input(prompt))
if i > n:
prompt = 'Guess Lower: '
elif i < n:
prompt = 'Guess Higher: '
print('Correct')
print('You took {} attempts.'.format(a))