I have a program that is executed. After that, the user has an option to load back their previous input() answers or to create a new one (just re-execute the program). The program is based on user input and so if I wanted to reload the user's previous inputs, is there a way to pre code an input with the user's previous answer? As a crude example of what my program does I just made this:
def program():
raw_input=input()
print("Would you like to reload previous program (press 1) or create new? (press 2)")
raw_input2=input()
if raw_input2==2:
program()
elif raw_input2==1:
#And here is where I would want to print another input with the saved 'raw_input' already loaded into the input box.
else:
print("Not valid")
For any confusion this is my original code:
while True:
textbox1=input(f" Line {line_number}: ")
line_number+=1
if textbox1:
commands.append(textbox1)
else: #if the line is empty finish inputting commands
break
print("\033[1m"+"*"*115+"\033[0m")
for cmd in commands:
execute_command(cmd)
line_numbers+=1
I tried creating a Python-like coding program using Python which generates new inputs (new lines) until you want to end your program by entering in nothing. This is only a snippet of my code of course. The problem I'm having is that after the user finished writing their basic program, whether you got an error because your code didn't make send or if it actually worked, I want there to be a 'cutscene' where it asks the user if they want to reload their previous program (because rewriting you program everytime there's an error is hard). I'm just asking whether I can do something like this: If my program was print("Hi"), and I wanted to reload it, I want to get an input; raw_input=input() but I want print("Hi") already inside the input().
This is not possible with the built-in input function. You will need a more fully-featured CLI library like readline or prompt-toolkit.
Some notes:
The input function always returns strings.
The while True keeps going until either 1 or 2 is entered
You can pass a string with the input-function call to specify what input is expexted.
If you put this in a loop you could re-ask the question, and you should then update the prev_answer variable each iteration.
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
user_input = prev_answer
if raw_input2 in ('1','2'):
break
print(user_input)
Based on edit:
prev_answer = 'abc'
while True:
raw_input2=input("Would you like to reload previous program (press 1) or create new? (press 2)")
if raw_input2=='2':
user_input = input('Please give your new input')
elif raw_input2=='1':
print(prev_answer)
user_input = prev_answer + ' ' + input()
if raw_input2 in ('1','2'):
break
Related
I am using python3.7
I wrote a script which takes some inputs (e.g. a=input("enter a value")
it runs smoothly if i go to its path and run it on command prompt.
I can give input also and run .
If i give wrong input it shows an error or exception(traceback)
So i converted it to .exe using pyinstaller
when i run .exe , it asks for input as expected ,it runs and vanishes , i can't see any output.
if i give a wrong input it suddenly vanishes without showing any traceback
I read many questions regarding this on stackoverflow and google , so i added an input statement at end to make program wait before exiting,
but it doesn't works in case of wrong input or if i use sys.exit("test failed") in some cases it just vanishes ,how to resolve and keep cmd window open?
Adding script for e.g.:
import sys
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
if x>100 or y > 100 :
sys.exit("ERROR :value out of range")
z=x+y;
print(z)
input('press enter to exit')
if inputs are less than 100 and integer then script(.exe file) runs smoothly and i get message "press enter to exit"
but if input number greater than 100 or if i put a "string or float" in input , cmd window vanishes without display any traceback
whereas if i run py file from cmd then i get proper traceback for wrong input.
You could use try-except and input() function, so that when there is any error, it will wait for the user to interact.
Look at this example -
a = input('Please enter a number: ')
try:
int(a) # Converts into a integer type
except ValueError as v:
# This will run when it cannot be converted or if there is any error
print(v) # Shows the error
input() # Waits for user input before closing
For your e.g code, try this -
import sys
try:
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
except ValueError as v:
print(v)
input('Press any key to exit ')
sys.exit()
if x>100 or y > 100 :
try:
sys.exit("ERROR :value out of range")
except SystemExit as s:
print(s)
input('Press any key to exit ')
sys.exit()
z=x+y
print(z)
You will see that the command prompt does not close immediately
You're not waiting for input.
When you run a .exe that's set up to run in the Windows console, unless you've already opened the console and if your program through that using console commands, and it was set up to just run all the way through to the end, you'll just see the window pop up and then close itself unless your program is doing something that requires user input or a lot of computational time.
This is fairly common sight when programming with languages like C# that natively run as .exes; presumably, this behaviour would also be fairly common in Python. The way to fix this is to add in a line at the end of your program to ask the user for input, so that the console will wait for the user before closing.
In your case, you mention that you have added to the end of your program; the problem is that the program isn't getting to that stage because it's hitting an exception and then exiting. You'll need to handle your exceptions and add a prompt for user input to prevent this behaviour.
Use while loop so if you gave wrong input then it will return to input again so you can give any input. and for example if you want to use only integer value then input must be convert as integer or string depend on you. example below now I think you can
ask = "" #ask variable empty here because I want to use in while condition
print("YOU LOVE ME")
while ask != 'Ok Son':
ask = input("Why? : ")
print("OK THANKS DAD")
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
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
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.')
I am working on a simple Python program where the user enters text and it says something back or executes a command.
Everytime I enter a command, I have to close the program. Python doesn't seem to have a goto command, and I cannot enter more than one "elif" without an error.
Here is the part of the code that gives me an error if I add additional elif statements:
cmd = input(":")
if cmd==("hello"):
print("hello " + user)
cmd = input(":")
elif cmd=="spooky":
print("scary skellitons")
Here's a simple way to deal with different responses based on user input:
cmd = ''
output = {'hello': 'hello there', 'spooky': 'scary skellitons'}
while cmd != 'exit':
cmd = input('> ')
response = output.get(cmd)
if response is not None:
print(response)
You can add more to the output dictionary, or make the output dictionary a mapping from strings to functions.
Your program is only coded to execute once from what you've posted. If you want it to accept and parse the user input multiple times, you'll have to explicitly code that functionality it.
What you want is a while loop. Take a look at this page for a tutorial and here for the docs. With while, your program would have the general structure of:
while True:
# accept user input
# parse user input
# respond to user input
while statements are part of the larger flow control.