Number correcting - python

Im writing code with a part that is confusing me.
while answer1 != 'a':
if answer1 == 'b':
print('\nWrong answer.\n')
answer1= input("\nEnter again.\nYou only have one more try!\n")
amount = amount+1
print(amount)#for testing
if amount == 1:
print("\nTry next question")
break
What I want to do is to have the tries to be two if the user said 'b' twice. I have put amount as 1 but if the user says a, then it will be two. What I want to do is to have the tries to two if 'b' is said twice but one if 'a' is said once.

So, the overall goal here is unclear. However, I think this may help you out:
First of all, drop the while answer != 'a', and go to while True, rely on the conditional inside the loop to handle break / continue.
amount = 1 # Initiate amount outside of the loop, otherwise it'll get reset on each loop.
while True: # Run until base condition is met.
print("I am the question")
ANSWER = input("Answer: ")
if ANSWER == 'a' or amount >= 2: # Base condition.
print(amount)
break
else: # This runs if answer isn't what you want.
print("Wrong, please try again.")
amount += 1
continue
Best

Related

How to display an integer many times

I'd like to create a function that add 2 to an integer as much as we want. It would look like that:
>>> n = 3
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No
Can anyone help me please ? I don't how I can print the sentence without recalling the function.
The idea is to use a while loop within your function that continues to add two each time you tell it to. Otherwise, it exits.
Given that knowledge, I'd suggest trying it yourself first but I'll provide a solution below that you can compare yours against.
That solution could be as simple as:
while input("Would you like to add a two to n ?") == "Yes":
n += 2
print(f"the new n is {n}")
But, since I rarely miss an opportunity to improve on code, I'll provide a more sophisticated solution as well, with the following differences:
It prints the starting number before anything else;
It allows an arbitrary number to be added, defaulting to two if none provided;
The output text is slightly more human-friendly;
It requires a yes or no answer (actually anything starting with upper or lower-case y or n will do, everything else is ignored and the question is re-asked).
def add_two(number, delta = 2):
print(f"The initial number is {number}")
# Loop forever, relying on break to finish adding.
while True:
# Ensure responses are yes or no only (first letter, any case).
response = ""
while response not in ["y", "n"]:
response = input(f"Would you like to add {delta} to the number? ")[:1].lower()
# Finish up if 'no' selected.
if response == "n":
break
# Otherwise, add value, print it, and continue.
number += delta
print(f"The new number is {number}")
# Incredibly basic/deficient test harness :-)
add_two(2)
You can use looping in your add_two() function. So, your function can print the sentence without recalling the function.
The above answer describes in detail what to do and why, if you're looking for very simple beginner-type code that covers your requirements, try this:
n = 3
while True:
inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
if inp == "yes":
n = n + 2
elif inp == "no":
None
elif inp == "end": # if the user wants to exit the loop
break
else:
print("Error in input") # simple input error handling
print("The new n is: ", n)
You can wrap it in a function. The function breaks once the yes condition is not met
def addd(n):
while n:
inp = input('would like to add 2 to n:' )
if inp.lower() == 'yes':
n = n + 2
print(f'The new n is {n}')
else:
return
addd(10)

Python While loop breakout issues

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.

How do I add different levels & a quit option to my guess a number game?

So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.

python looping with functions break and continue outside loop

I am new to programming and so i'm practicing a bid. At this point i'm practicing with functions. In the code below break and continue are outside the loop i can not see why. I've tryed out different ways but the only thing i get to work is the last block of code. Why are break and continue outside the loop here?
import random
again = 'y'
while again == "y" :
def main():
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
main()
again = raw_input('would you like to play again press y to play again press n yo exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
#main()
Because you are new to programming, I will get a few basic tips in my answer too.
INFINITE LOOP
You are trying to start an infinite loop by first settingagain = 'y' and afterwards you are using this variable to evaluate a while loop. Because you are not changing the value of y, it is better to not use a variable to create this infinite loop. Instead, try this:
while True:
(some code)
DEFINE FUNCTION IN LOOP
You're defining the function main() inside of the while loop. As far as I can tell, there is no use for that. Just leave out the first while loop. If you define a function, it is permanent (much like a variable), so no need to redefine it everytime. Using your code, you won't even get to call the function, because you never end the first loop.
CONTINUE/BREAK NOT IN LOOP
The error is quite self-explanaitory, but here we go. If you would ever end the first loop (which in this case, you won't), the next thing you do is call your function main(). This will generate a number and make the user guess it until he got it right. When that happens, you get out of that function (and loop).
Next, you ask if the user would like to play again. This is just an input statement. You store the answer in the variable 'again'. You check, with an if statement (note that this is not a loop!) what the answer is. You want the user to play again if he typed 'y', so instead of using again != 'y', you could use the following:
if again == 'y':
main() # you call the function to play again
If 'n' was typed in, you want to exit the script, which you do not by typing break, because you are not in a loop, just in an if-statement. You can either type nothing, which will just go out of the if-statement. Because there is nothing after the if, you will exit the script. You could also useexit(), which will immediately exit the script.
Lastly, you want to repeat the question if neither of these two things were answered. You can put the if-statement inside of a loop. You can (if you want) use your break and continue when doing this, but you mostly want to avoid those two. Here is an example:
while True:
again = raw_imput('y for again or n to stop')
if again == 'y':
main()
exit() # use this if you don't want to ask to play again after the 2nd game
elif again == 'n':
print('bye!')
exit()
# no need for an 'else' this way
# every exit() can be replaced by a 'break' if you really want to
BASIC BREAK/CONTINUE USAGE
Finally, here is some basic usage of break and continue. People generally tend to avoid them, but it's nice to know what they do.
Using break will exit the most inner loop you are currently in, but you can only use it inside of a loop, obviously (for-loops or while-loops).
Using continue will immediately restart the most inner loop you are currently in, regardless of what code comes next. Also, only usable inside of a loop.
EVERYTHING TOGETHER
import random
again = 'y'
def main():
print ("gues a number between 0 - 10.")
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print ('Your the man')
found = True
else:
print ('to bad dude try again')
main()
while True:
again = input('would you like to play again press y to play again press n yo exit')
if again == 'n':
print ('bye!')
exit() # you could use break here too
elif again == 'y':
main()
exit() # you can remove this if you want to keep asking after every game
else:
print ('oeps i don\'t know what you mean plz enter y to play again or n to exit')
I hope I helped you!
You loops and def are all muddled, you want something more like:
import random
again = 'y'
while again == "y" :
print "gues a number between 0 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = input("your gues?")
if usergues == nummer:
print 'Your the man'
found = True
else:
print 'to bad dude try again'
while True:
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break
elif again != 'y':
print 'oeps i don\'t know what you mean plz enter y to play again or n to exit'
else:
break
You may want to refer to instructional material because you seem to misunderstand the general purpose of functions and the order of your logic.
Your function should be at the outer scope, e.g.:
def main():
again = 'y'
while again == "y" :
Your question for again needs to be indented into the while loop:
while again == "y":
[snip]
again = raw_input('would you like to play again press y to play again press n to exit')
if again == 'n':
break #here it says it is outside the loop
elif again != 'y':
print 'oops i don\'t know what you mean plz enter y to play again or n to exit'
else:
continue #this is outside loop as well
The else: continue is unnecessary because you are at the end of the loop.
However, this only asks the question once, and you probably want this in a while loop. You also don't need to check the again == "y" in the outer while loop, because you are controlling the flow here:
while True:
[snip]
again = raw_input("would you like to play again press y to play again press n to exit")
while again not in ('y', 'n'):
again = raw_input("oops i don't know what you mean plz enter y to play again or n to exit")
if again == 'n':
break
I would recommend against using a bare input() because any code could be executed, receiving a string and casting to an int would be safe (and you probably do some error checking):
usergues = int(raw_input("your guess?"))
Putting it all together it looks like:
def main():
while True:
print "guess a number between 1 - 10."
nummer = random.randint(1,10)
found = False
while not found:
usergues = int(raw_input("your guess?"))
if usergues == nummer:
print 'You're the man'
found = True
else:
print 'Too bad dude try again'
again = raw_input('would you like to play again press y to play again press n to exit')
while again not in ('y', 'n'):
again = raw_input('oops i don\'t know what you mean plz enter y to play again or n to exit')
if again == 'n':
break
main()

Does raw_input() stop an infinite while loop?

There is a small code below containing of while-loop.
question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"
while True:
if question == "good":
print "Ok. Your mood is good."
state = False
question_2 = raw_input("How are you 2? > ")
elif question == "normal":
print "Ok. Your mood is normal."
elif question == "bad":
print "It's bad. Do an interesting activity, return and say again what your mood is."
else:
print "Nothing"
If I type in "normal", the program prints Ok. Your mood is normal. an infinite number of times.
But if I type in "good", the program prints Ok. Your mood is normal. and prints the contents of question_2.
Why is the question in question_2 = raw_input("How are you 2? > ") not repeated an infinite number of times?
Is it reasonable to conclude that raw_input() stops any infinite while loop?
No. It's not stopping the loop; it's actively blocking for input. Once input is received, it will not be blocked anymore (and this is why you get infinite text from other selections); there is no blocking I/O in those branches.
The reason you're not getting a lot of text output from option 1 is due to the way it's being evaluated. Inside of the loop, question never changes, so it's always going to evaluate to "good" and will continually ask you the second question1.
1: This is if it is indeed while True; if it's while state, it will stop iteration due to state being False on a subsequent run.
Once you've answered "good, the value returned by the second raw_input will be stored in variable question_2 rather than question. So variable question never changes again, but will remain "good". So you'll keep hitting the second raw_input, no matter what you answer to it. It doesn't stop your loop, but rather pauses it until you answer. And I think you should also take a good look at the comment of Alfasin...
You can stop an infinite loop by having an else or elif that uses a break for output. Hope that helps! :D
Example:
while True:
if things:
#stuff
elif other_things:
#other stuff
#maybe now you want to end the loop
else:
break
raw_input() does not break a loop. it just waits for input. and as your question is not overwritten by the second raw_input(), your if block will always end up in the good case.
a different approach:
answer = None
while answer != '':
answer = raw_input("How are you? (enter to quit)> ")
if answer == "good":
print( "Ok. Your mood is good.")
elif answer == "normal":
print( "Ok. Your mood is normal.")
# break ?
elif answer == "bad":
print( "It's bad. Do an interesting activity, return and say again what your mood is.")
# break ?
else:
print( "Nothing")
# break ?

Categories

Resources