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().
CodePudding user response:
This is not possible with the built-in input
function. You will need a more fully-featured CLI library like readline
or prompt-toolkit
.
CodePudding user response:
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