How to replicate functionality in a program

I am working on a simple Python program where the user enters text and he says something back or executes a command.

Every time I enter a command, I need to close the program. Python has no command goto

and I cannot enter more than one "elif" without errors.

Here is the piece of code that gives me the error if I add additional instructions elif

:

cmd = input(":")
if cmd==("hello"):
    print("hello   " + user)
    cmd = input(":")
elif cmd=="spooky":
    print("scary skellitons")

      

+3


source to share


2 answers


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 dictionary, output

or make the output dictionary match from strings to functions.

+1


source


Your program is only coded to execute once from what you've posted. If you want it to accept and parse user input multiple times, you will have to explicitly specify its functionality.

What you want is a loop while

. Check out this page for a tutorial and here for docs. With while,

your program will have a general structure:



while True:
    # accept user input
    # parse user input
    # respond to user input

      

Operators

while

are part of a larger flow control .

0


source







All Articles