The while loop correctly stops when "no" is entered first for the "would you like to continue" question. When "no" is entered after "yes" or after several "yes" entries, then the user must answer "no" for however many "yes" entries came before it: e.g. "yes", "yes", "no" will produce two "would you like to continue" questions after the first "no" answer.
I am just beginning to learn Python, so any suggestions would be helpful.
Thank you.
def testing3():
def Grade(score):
if score >= 90:
letter = "A"
elif score >= 80:
letter = "B"
elif score >= 70:
letter = "C"
elif score >= 60:
letter = "D"
else:
letter = "F"
print(letter)
def main():
x = input("Enter Numerical Grade: ")
numGrade = int(x)
Grade(numGrade)
main()
def main2():
while True:
test = input("Would you like to continue?: ")
if test == 'Yes':
testing3()
else:
print("Done")
break
main2()
testing3()
Your testing3 call invokes the inner main2 def, but main2 invokes the testing3 def so you are ping-ponging between the two.
To get a sense of this you should look at your stack-frames and you should see a frame for testing3 followed by testing2 followed by testing3 etc for how ever many times you have entered yes.
Whether or not you meant to (I don't think you did) you created a recursive function. So the reason you are having to enter no multiple times is as you unwind up (popping frames off the stack)
The proper use of the while loop should something like:
finish = False
while not finish:
# do your stuff here
finish = evaluateLoopFinish()
Here, finish is a signal flag which you must evaluate at the end of each turn. The first time is set at False, so not False == True, hence enters the loop.
Another tip: use only one main like this
def main(args):
# do your stuff here
if __name__=="__main__":
main()
Every Python script has a name special variable which holds the name of the module except for the script which was given to Python to be executed which receives the special value main.
Related
I'm trying to make a pokémon text based journey in python.
I listed the starter pokémon in a tuple to call the number that the user typed in the input to then store the chosen starter pokémon.
It all works but when the user would type a different integer then availabe in the tuple, for example: writing 5 while there are only 3 indexs in the tuple. The program just stops when this happens.
Is there a way for me to just tell the program to not go into debugging mode when this happens; and recalling the "ChoseStarter" function instead?
Here is the code:
if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3):
ChosenPokInt = int(ChosenPok)
StarterPok = Starter[ChosenPokInt-1] #Here is the problem
Sure = f"You chose {StarterPok} are you sure? (y/n)"
YORN = input(Sure)
if(YORN == "Y" or YORN == "y"):
Congrats = f"Congratulations!! You just got a {StarterPok}!!"
WriteFast(Congrats)
print(Starter[ChosenPokInt-1])
else:
WriteFast(ERROR)
ChoseStarter()
No idea what the question is about or what logic you want to implement. See if the below code helps though. Seems like the "if condition" is buggy in your case. The following code repeatedly asks for the correct input using a while loop. Replace the while loop with an if statement if you don't want that.
starter = ["x", "y", "z"]
chosen_pok = int(input("Select a pok: "))
while not (1 < chosen_pok < 4):
print("Invalid pok. try again...")
chosen_pok = int(input("Select a pok: "))
starter_pok = starter[chosen_pok - 1]
yorn = input(f"You chose {starter_pok} are you sure? (y/n)")
if (yorn in ["Y", "y"]):
print(starter[chosen_pok - 1])
else:
print("Error")
You should just check for the len and if ChosenPokInt is in it's boundaries:
pokemon_index = ChosenPokInt - 1
if 0 <= pokemon_index < len(Starter)-1:
# everything is fine
else:
# handle the problem case
Besides that I advice you to look into pep8 :). You can find an awesome guide here: https://pep8.org
You can add a while loop before the condition that checks first if the input is in the correct range:
ChosenPok = ChoseStarter()
pokRange = [1, 2, 3]
while not (ChosenPok in pokRange):
print("Wrong input, try again")
ChosenPok = ChoseStarter()
New to stackoverflow, and new to python (python-3). Currently learning on edx.org and ran into the following error.
I created a function that checks a user-input str against the answer str and returns True or False.
When testing the function, I created a while loop to stop at the 3rd unsuccessful attempt. However, whenever there is an unsuccessful attempt, the function prints the error message twice when it should only print it once.
I fixed the error by storing the returning Bool value of the function into a variable rather than calling the function directly in the if condition within the while loop. However, I would like to understand the logic behind the error message printing twice. Here is the original code that prints the error message twice :
def letter_guess(letter, guess):
if len(guess) == 1 and guess.isalpha() and guess < letter:
print(guess,"is lower than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess > letter:
print(guess,"is higher than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess == letter:
print("Correct answer!")
return True
else:
print("Please only enter one alphabet for the letter. Try again.\n")
return False
answer2 = "m"
guess2 = input("Please enter a single alphabet : ")
i = 0
while i < 3:
if letter_guess(answer2, guess2):
break
elif letter_guess(answer2, guess2) == False and i == 2:
print("You have reached 3 guesses. Game over.")
break
else:
i += 1
guess2 = input("Please guess again : ")
You want to call input() inside the while loop:
# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...
Otherwise the user doesn't have a chance to change their answer, guess2 never changes and they get the same error message multiple times.
You call the function twice, in first if and in elif, with the same wrong guess. You fixed it right calling only once and storing the return value.
I try to explain it better: the function is always called by the first if, to evaluate its condition; if return value is false, is called again to evaluate the elif condition, with same arguments as before.
while True:
game = input("Would you like to play: Guess the integer(i) or true/false(t). **Case Senestive** ")
if not name.isalpha():
print (name, "Enter the correct values")
continue
if not game == "i" or game == "t" or game=="integer" or game=="true/false":
print ("Enter i, integer or true/false, t")
continue
else:
break
I want to make it if they don't type 'i' or 'integer' it goes to the part saying not game == "i" or game=="integer". Whenever I enter i it works, but not when I enter integer.
You'll need to put parentheses around your or conditions:
if not (game == "i" or game == "t" or game=="integer" or game=="true/false"):
otherwise Python sees this as (not game == "i") or ....
You'd be better off using not in on a set:
if game not in {"i", "t", "integer", "true/false"}:
Not only is this shorter, it is also faster; only one check constant-time check is made rather than separate == tests for each string.
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()
I started learning to code this week so I'm playing around with small programs that I'm creating to try to get a better understanding of how it work.
One of the programs I made is a Pig Latin translator that loops until the user exits. The program works but the logic isn't making any sense to me.
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
translate() #Don't forget to actually call the function after you define it.
#Set run to False.
#Can be set to True if while (run != True) is set to while (run == True).
run = False
#Defining cont(). Ask for imput and error handling.
def cont():
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
cont()
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
cont()
My question is, why does this program work? I set run to False and I set the loop to run as long as run != True. No problem there, however when I defined cont(), I set run to take on the value True if the user inputs "y". True != True should be False (if I understand correctly) and the loop should end, but instead it is working as I wanted it to.
Is this a coding mistake that I've made or am I just thinking about this the wrong way? Thank you in advance.
Edit: Thank you very much to everyone that answered. I hadn't learned about local and global variables yet.
To expand on what others have already stated, run on these lines
if loop == "y" :
run = True
elif loop == "n" :
run = False
are not referring to the same run defined by
#Can be set to True if while (run != True) is set to while (run == True).
run = False
run in the cont function is a local variable to your function, not the globaly defined run.
There are a couple (at least) ways to fix this. The preferred (imo) way to do it is have cont return a new value to be assigned to run. That would look like
#Defining cont(). Ask for imput and error handling.
def cont(_run):
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
return _run
elif loop == "n" :
return not _run
else :
print("You did not enter a valid response, please try again.")
return cont(_run)
...
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
run = cont(run)
The other (less preferred) way would be to use the global run variable inside of your cont function. This is achieved using the global keyword.
That would look like this:
#Defining cont(). Ask for imput and error handling.
def cont():
global run
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
** Couple side notes
In my first example I return _run when the value is y and not _run when the value is n. This allows you to change you initial run value to be True, and change the while condition without having to change the cont function itself.
You don't need to actually change the run value at all if you use the global and the user enters n since you exit before the function returns.
You might be better off changing your if conditional checks to
if loop in ("yes", "y"):
if loop in ("no", "n"):
since lots of people don't read full instructions :)
The run inside the cont function is a local variable. Changing its value has no effect on the global variable that the while loop refers to.
I think this is probably because of the scope of your run variable; because you're not returning run from your cont function. I believe what your != True check sees is always going to be False outside of that function, though obviously you can successfully end the program within the function.
The problem is that the run variable defined in cont() is not the same as the run variable defined in the global scope. (If you aren't sure what I mean by that you might want to look at https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces. Perhaps a better approach for your code would be to have cont() return True or False. It is also more intuitive and readable to use True for when you want to continue. Here's how I would rewrite it.
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
#Defining cont(). Ask for imput and error handling.
def cont():
while True:
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y":
return True
elif loop == "n":
print("Thank you for using this program, have a nice day!")
return False
else :
print("You did not enter a valid response, please try again.")
translate()
while cont():
translate()