I'm new to Python, and I was wondering if there was a way to loop back to a previous line of code?

command = input('Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: ')

if command == 'a': #Add fruit command
    #Loop back to Command Line
if command == 'd': #Delete fruit command
    #Loop back to Command Line
#etc...

If I am doing anything else wrong, I would greatly appreciate further pointers.

As I am still new to this, if possible, I would like the answer to be as simple as possible.

2 Answers

3
Devesh Kumar Singh On

When you say, Loop back to Command Line, I assume you mean call input again.
Well in python, we have something called a function in which you can define a piece of code, and that can be called when you need it.

So in your case, you want to call the command line again, which means taking an input.

Let's start by wrapping that statement in a function

def cmd():
    command = input('Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: ')
    return command

You can see that the function cmd takes the input from the user, and returns it, which means that whoever calls the function, will get the value back.

Now we can call the function by just doing cmd() as we do below

#Call cmd the first time and assign the value to variable command
command = cmd()
#Then we can use same function to call command again
if command == 'a': #Add fruit command
    command = cmd()
if command == 'd': #Delete fruit command
    command = cmd()

Some sample runs now will be

Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: a
Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: a

Or

Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: a
Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: d
Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: d

You can now build up your logic accordingly

0
Sazedul Islam Sazid On

I suppose what you want is a loop. Take your input and process within a loop.

while True:
   command = input('Choose [a]dd, [d]elete, [l]ist, [s]earch, [v]iew or [q]uit: ')
   if command == 'a': 
      #Add fruit command
   elif command == 'd': 
      #Delete fruit command
   elif command == 'q':
      exit()

In the above example I used a while loop. If you want to learn more about loops visit https://www.geeksforgeeks.org/loops-in-python/