Having trouble with while loops, input and strings in python - python

I am learning python and practicing my skills my making a simple text based adventure game.
In the game, I want to ask the player if they are ready to begin. I did this by creating a begin() function:
def begin():
print(raw_input("Are you ready to begin? > "))
while raw_input() != "yes":
if raw_input() == "yes":
break
print(start_adventure())
else:
print("Are you ready to begin? > ")
print(begin())
below this in my code is the function start_adventure()
def start_adventure():
print("Test, Test, Test")
When I run the program it starts up and I get to the point where it asks if I am ready to begin. Then it just loops infinitely and I can only exit the program if I completely close Powershell and restart Powershell. What am I doing wrong? How can I get the loop to stop once the player inputs "yes"?

What do you expect this to do? The solution to your problem is to try to understand what the code does, instead of just throwing stuff together. (Don't worry; at least 80% of us were at that stage at one point!)
As an aside, I strongly recommend using Python 3 instead of Python 2; they made a new version of Python because Python 2 was full of really strange, confusing stuff like input causing security vulnerabilities and 10 / 4 equalling 2.
What do you want this to do?
Repeatedly ask the user whether they are ready to begin until they answer "yes".
Call start_adventure().
Ok. Let's put what we've got so far into a function:
def begin():
while something:
raw_input("Are you ready to begin? > ")
start_adventure()
There are a lot of gaps in here, but it's a start. Currently, we're getting the user's input and throwing it away, because we're not storing it anywhere. Let's fix that.
def begin():
while something:
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This is starting to take shape. We only want to keep looping while answer != "yes"...
def begin():
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
Hooray! Let's see if this works!
Traceback (most recent call last):
File "example", line 2, in <module>
while answer != "yes":
NameError: name 'answer' is not defined
Hmm... We haven't set a value for answer yet. In order to make the loop run, it has to be something that isn't equal to "yes". Let's go with "no":
def begin():
answer = "no"
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This will work!

Python 3 Solution
You should not be calling raw_input() multiple times. Simply instantiate x and then wait until the user inputs Y to call your start_adventure function. This should get you started:
def start_adventure():
print('We have started!')
#do something here
def begin():
x = None
while x!='Y':
x = input('Are you ready to begin (Y/N)?')
if x=='Y':
start_adventure()
begin()

Your Raw input function (I'm assuming it works correctly) is never assigned to a variable. Instead you call it in your print statement, print the result of it and then you call it again in your while loop condition.
You never actually satisfy the while loop condition because your input isn't assigned to a variable. Assign Raw_input("Are you ready to begin? >") to a variable to store the input. Then while loop with the variable. Make sure in your while loop when the condition is met you reset the variable to something else.
Your program flow is wrong too, you need to call your raw input function inside the while loop. This will change the while loop condition so that when the condition is met (user types "yes") it won't loop infinitely. Hope this helps!
Example of what you need in code form:
//initialize the condition to no value
condition = None;
#check the condition
while condition != "yes"
#change the condition here based on user input **inside the loop**
condition = raw_input("are you ready to begin? >")
if condition == "yes":
#condition is met do what you need
else:
#condition not met loop again
#nothing needs to go here to print the message again

Related

Handle invalid string input without breaking out of a "while" loop [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 10 months ago.
I'm working on a Python project to get better with passing parameters into functions, so built a small program that takes user input and appends it to a list.
I've got most of that working, but I'm stuck on trying to allow a user to add another input if they want. The program asks if they'd like to add another input, with an if/else to handle a "Y" or "N" answer. That's working for the most part. The problem comes when a user enters an invalid response (anything other than a non-case sensitive 'y' or 'n'). At this point, the program is just displaying the goodbye message and ending. I think it has to do with my while loop, since it's supposed to break out when the new_input() function isn't resolving to true anymore. I want that function to continue to cycle through until the user enters a valid response, which would then cause it to continue and take another input or end appropriately.
Is there a way to get this to work with my combination of an if/else statement or is there another method that would work better? I'll drop the relevant pieces of the program below.
def new_input():
answer = input("Would you like to add more wisdom?(y/n): ")
if answer == "y" or answer == "Y":
return True
elif answer == 'n' or answer == 'N':
return False
else:
print("Invalid input. Please try again!")
def main():
name = input('Please enter your name:')
take_input(name)
while new_input():
take_input(name)
print_lib()
print("Thanks for your brain cells, buddy! Bye bye!")
Thanks for your help!
You can always return True, unless N/n is pressed, this way the program will continue running:
def new_input():
answer = input("Would you like to add more wisdom?(y/n): ")
if answer == "y" or answer == "Y":
return True
elif answer == 'n' or answer == 'N':
return False
else:
print("Invalid input. Please try again!")
return True

Have the boolean value of var follow into another file

I have two files in my text-based game. The variable that is being assigned will be keep_note.
If you enter "Take" the boolean value True is assigned to the have_note-001
but in the next file when if have_note_001 == True I get an error saying
have_note-001 is undefined
If keep_note is == "Take":
have_note_001 = True
Then in the next file I want that True value to travel over to the next file.
If have_note_001 == True: print("This Value Is True")
keep_paper = input("Do you want to Leave the piece of paper or Take it? > ")
if keep_paper == "Take":
have_note_01 = True
if have_note_01 == True:
print("You have chosen to keep the piece of paper")
print("You leave the house with the note(" + note_001 + ")")
This is my next file
from intros.intro_001 import have_note_001
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
In the file, the import is working.
I am importing the have_note_001. It is just not transferring the value True over. It doesnt seem to remember when you give it that value you in the first file, to the second
How can I have the value assigned to a variable carry over to another file when imported?
I'm not sure what you are asking for is in your best interest. The values stored in variables are already carried over by default when you import the file they are from. However, this type of sporadic architecture is not really considered good practice. Let me give you some feedback on your program. First lets give it some input validation:
# start off setting keep_paper to nothing
keep_paper = ''
# As long as the player does not enter 'take' or 'leave' we are going to
# keep asking them to enter a proper response.
while keep_paper not in ['take', 'leave']:
# here we are going to "try" and ask the player for his choice
try:
# here we are getting input from the user with input(...)
# then converting it into a string with str(...)
# then converting it to lowercase with .lower()
# all together str(input(...)).lower()
keep_paper = str(input("Do you want to Leave the piece of paper or Take it? > ")).lower()
# if the player entered an invalid response such as "53" we will go back
# to the beginning and ask for another response.
except ValueError:
print("Sorry, I didn't understand that.")
# ask the user to provide valid input
continue
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
Now let's address the main topic of your question. Having the value assigned to a variable carry over on imports. As I've already mentioned, this is generally not something that you want, which is why most Python programs have code including:
if __name__ == "__main__":
# do xyz....
This ensures that xyz is only run if the file is being ran, and will not run if the file is imported.
For good measure, I recommend you checkout: https://github.com/phillipjohnson/text-adventure-tut/tree/master/adventuretutorial, reading over the code in this project will give you a better idea at how you might want to tackle your own project. (The basics of functions, classes and inheritance)

Python Function requesting input doesn't execute if statement - no error shown

I thoroughly searched for an answer to my question but couldn't find anything that would explain my results. I truly hope that anyone of you can point me in the right direction.
At the moment I am trying to program a text-based adventure game using Python 3 in order to better understand the language.
While doing so I created a function that should ask the user for input and print a specific statement depending on the users input. In case the users input is invalid the function should then keep asking for input until it is valid.
Unfortunately the function only seems to keep asking for input, without ever executing the if/elif statements within the function. Due to no errors being shown I am currently at a loss as to why this is the case...
print("If You want to start the game, please enter 'start'." + "\n" +
"Otherwise please enter 'quit' in order to quit the game.")
startGame = True
def StartGame_int(answer):
if answer.lower() == "start":
startGame = False
return "Welcome to Vahlderia!"
elif answer.lower() == "quit":
startGame = False
return "Thank You for playing Vahlderia!" + "\n" + "You can now close
the window."
else:
return "Please enter either 'r' to start or 'q' to quit the game."
def StartGame():
answ = input("- ")
StartGame_int(answ)
while startGame == True:
StartGame()
You fell into the scoping trap: you are creating a new variable startGame inside the function that is discarded after you leave it. You would instead need to modify the global one:
def StartGame_int(answer):
global startGame # you need to specify that you want to modify the global var
# not create a same-named var in this scope
# rest of your code
This other SO questions might be of interest:
Python scoping rules
Asking the user for input until they give a valid response
Use of global keyword
and my all time favorite:
How to debug small programs (#1) so you enable yourself to debug your own code.
The last one will help you figure out why your texts that you return are not printed and why the if does not work on 'r' or 'q' and whatever other problems you stumble into. It will also show you that your if are indeed executed ;o)
Other great things to read for your text adventure to avoid other beginner traps:
How to copy or clone a list
How to parse a string to float or int
How to randomly select an item from a list

converting logic tests into try statements (python3)

I have been trying to convert some code into a try statement but I can't seem to get anything working.
Here is my code in pseudo code:
start
run function
check for user input ('Would you like to test another variable? (y/n) ')
if: yes ('y') restart from top
elif: no ('n') exit program (loop is at end of program)
else: return an error saying that the input is invalid.
And here is my code (which works) in python 3.4
run = True
while run == True:
spuriousCorrelate(directory)
cont = True
while cont == True:
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
cont = False
elif choice == 'n':
run = False
cont = False
else:
print('This is not a valid answer please try again.')
run = True
cont = True
Now what is the proper way for me to convert this into a try statement or to neaten my code somewhat?
This isn't a copy of the mentioned referenced post as I am trying to manage two nested statements rather than only get the correct answer.
If you want to make your code neater, you should consider having
while run:
instead of
while run == True:
and also remove the last two lines, because setting run and cont to True again isn't necessary (their value didn't change).
Furthermore, I think that a try - except block would be useful in the case of an integer input, for example:
num = input("Please enter an integer: ")
try:
num = int(num)
except ValueError:
print("Error,", num, "is not a number.")
In your case though I think it's better to stick with if - elif - else blocks.
Ok so as a general case I will try to avoid try...except blocks
Don't do this. Use the right tool for the job.
Use raise to signal that your code can't (or shouldn't) deal with the scenario.
Use try-except to process that signal.
Now what is the proper way for me to convert this into a try statement?
Don't convert.
You don't have anything that raises in your code, so there is no point of try-except.
What is the proper way to neaten my code somewhat?
Get rid of your flag variables (run, cont). You have break, use it!
This is prefered way of imlementing do-while, as Python docs says; unfortunately, I cannot find it to link it right now.
If someone finds it, feel free to edit my answer to include it.
def main()
while True: # while user wants to test variables
spuriousCorrelate(directory) # or whatever your program is doing
while True: # while not received valid answer
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
break # let's test next variable
elif choice == 'n':
return # no more testing, exit whole program
else:
print('This is not a valid answer please try again.')

How to loop back to the beginning of a programme - Python [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Closed 8 years ago.
I've written a BMI calculator in python 3.4 and at the end I'd like to ask whether the user would like to use the calculator again and if yes go back to the beginning of the code. I've got this so far. Any help is very welcome :-)
#Asks if the user would like to use the calculator again
again =input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")
while(again != "n") and (again != "y"):
again =input("Please type a valid response. Would you like to try again? Please type y for yes or n for no-")
if again == "n" :
print("Thank you, bye!")
elif again == "y" :
....
Wrap the whole code into a loop:
while True:
indenting every other line by 4 characters.
Whenever you want to "restart from the beginning", use statement
continue
Whenever you want to terminate the loop and proceed after it, use
break
If you want to terminate the whole program, import sys at the start of your code (before the while True: -- no use repeating the import!-) and whenever you want to terminate the program, use
sys.exit()
You just need to call the function if the user wants to start again:
def calculate():
# do work
return play_again()
def play_again():
while True:
again = input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")
if again not in {"y","n"}:
print("please enter valid input")
elif again == "n":
return "Thank you, bye!"
elif again == "y":
# call function to start the calc again
return calculate()
calculate()

Categories

Resources