How to repeat functionality in program - python

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.

Related

Pre-inputting information in an input() function

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

How do I take a user input that ends when the user presses Tab in Python?

I've been trying to find a way to take a user input that ends in the user pressing Tab. What I want to happen is for the user to type notes and it doesn't finish the input until they press Tab.
I was trying to use this method but not sure what to do.
text = input()
I want the user to type notes and be able to go to a new line by pressing Enter without finishing the input. Only if the user presses Tab will the input finish and the text get stored into the variable.
What you're asking for sounds straightforward, but unfortunately isn't very easy to do. The problem is that input from the command line to your program is line-buffered. That is, it only gets sent to the program one line at a time. There are some difficult ways to get around this, but they generally don't work very well.
If you clarify your question with what you are trying accomplish one level above this, people might be able to offer an even better solution. In the meantime, here's a simple version that ends the input if the user presses tab then enter:
def get_input_ending_with_tab():
inp = input() + "\n"
while not inp.endswith("\t\n"):
inp += input() + "\n"
return inp
And here's a more complicated version that does what you want, but will not work on Windows. This will also only work in an interactive execution of your program (when it's attached to a TTY).
import sys
import tty
import termios
def get_input_ending_with_tab_2():
buf = ""
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
while True:
buf += sys.stdin.read(1)
print(buf[-1], end="")
sys.stdout.flush()
if buf[-1] == "\t":
break
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
print()
return buf

What is CLI-Loop ? What's the difference with normal loop?

I was doing some research about Python.
And I saw something like this.
# Start CLI-Loop
while True:
try:
text = raw_input()
except:
text = error()
if text == condition_1:
do_Some_Other_Things_1()
break
elif text == condition_2:
do_Some_Other_Things_2()
Is CLI-Loop stands for "Command Line Interface Loop" ?
If not, what does it mean?
What's so special about it?
There is nothing special about the loop; the author simply introduces the code block, stating that it'll interpret commands.
Which is exactly what the loop does; using raw_input(), it asks for user input from the terminal, then executes functions based on the input. In other words, it takes commands, interfacing with the user.
CLI indeed stands for Command Line Interface. There's nothing special about this loop, it's just called "the CLI loop" to indicate it's a loop handling the input taken from the command line.

Optional input() statement

I'm creating an instant messenger program for my school's common drive. I have everything working except for on small detail. In the code below it checks for a new message from a friend and prints the last message they sent. If there are no messages it says so. The problem is when it moves to the next step of the code it waits for the user to put in an input. Until you give an input it won't let you receive any more messages because the program stops reading and searching the while loop and gets caught on the input statement. I want to know if there is anyway to make an input statement optional. To say that it doesn't require an input but if there is an input it will send it and do it's thing. I just can't seem to figure out a way to make the input statement optional. Any ideas or working code would be greatly appreciated. If you need the entire code I don't have a problem with sending it to you or posting it. This is the only bit of code that should really matter for this problem though.
LastMessage = ""
while Message:
Path = "Message"+SendTo+"-"+UserName+".txt"
if path.isfile(Path):
LoadMessage = open(Path, "rb")
NewMessage = pickle.load(LoadMessage)
LoadMessage.close()
else:
NewMessage = "Sorry, No messages found"
if LastMessage != NewMessage:
LastMessage = NewMessage
print(NewMessage)
print("")
SendMessage = raw_input() #--- This is where it gets caught up! ---
Save = open("Message"+UserName+"-"+SendTo+".txt", "wb")
pickle.dump(SendMessage, Save)
Save.close()
You have two main options as I see it:
Simultaneous input and checking (various options, search for e.g. threading or multiprocessing from the standard library); or
Input with timeout and loop (see e.g. How to set time limit on raw_input).
So it sounds like you want to do two separate things at the same time - look for input from a user and poll for new messages from other users. Jonrsharpe gives threading as his first option to solve this and I agree its the most straightforward. What you need to do is something like this:
import threading
class InputMessageThread(threading.Thread):
def run(self):
SendMessage = raw_input() # This thread will hang here for input but thats
# OK as original thread will keep going
Save = open("Message"+UserName+"-"+SendTo+".txt", "wb")
pickle.dump(SendMessage, Save)
Save.close()
inputthread = InputMessageThread()
inputthread.start()
# rest of your code here
While you are at it though you might want to look at some other issues. For example if I understand what you are trying to do correctly you are going to have a file containing a message from a source user to a destination user. But if the source user sends a second message before this file gets processed then the first message will be overwritten. In practice you may never see this but some sort of handshaking to make sure the message has actually been sent before you allow the next to be written would be a more robust approach.

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

Categories

Resources