How to Make Program Go Back to the Top of the Code Instead of Closing

How to make program go back to the top of the code instead of closing

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

1. Loops

An example of how you could do exactly what your SmallBasic example does is as follows:

while True :
print "Poo"

It's that simple.

2. Recursion

def the_func() :
print "Poo"
the_func()

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

Edited to Answer Question More Specifically

#Alan's Toolkit for conversions

invalid_input = True
def start() :
print ("Welcome to the converter toolkit made by Alan.")
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
#stuff
invalid_input = False # Set to False because input was valid

elif op == "2":
#stuff
invalid_input = False # Set to False because input was valid
elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
#stuff
invalid_input = False # Set to False because input was valid
else:
print ("Sorry, that was an invalid command!")

while invalid_input: # this will loop until invalid_input is set to be False
start()

How to loop back to the beginning of a programme - Python

Wrap the whole code into a loop:

while True:

indenting every other line by 4 characters.

Whenever you want to "restart from the beginning", use statement

continue

Whenever you want to terminate the loop and proceed after it, use

break

If you want to terminate the whole program, import sys at the start of your code (before the while True: -- no use repeating the import!-) and whenever you want to terminate the program, use

sys.exit()

How do I get my program to loop back and restart in Python?

Your problem here is all about the indentation levels, Laura. Python knows that something is inside a block of code if the consecutive lines have all the same indentation(differently from C or Java, where blocks are delimited by opening and closing brackets).

Your code should look something like this:

while True:
print("BMI Calculator")

weight = float(input("\nPlease enter your weight in KG: "))
height = float(input("\nPlease enter your height in metres: "))
bmi = weight/(height*height)

if bmi <= 18.5:
print("Your BMI is", bmi,"which means you are underweight.")

elif bmi > 18.5 and bmi < 25:
print("Your BMI is: ", bmi, "which means you are normal")

elif bmi > 25 and bmi < 30:
print("Your BMI is: ", bmi, "which means you are overweight")

elif bmi > 30:
print("Your BMI is: ", bmi, "which means you are obese")

else:
print("There was an error with your input, Sorry.")

answer = input("Would you like to enter another? key y/n: ")

if answer not in ("y", "n"):
print("Invalid Input")
break

if answer == "y":
continue
else:
input("\nPress the enter key to exit")
break

In this snippet of code I have changed the boolean test and the instruction order from:

if answer in ("y", "n"):
break
print("Invalid Input")

to

if answer not in ("y", "n"):
print("Invalid Input")
break

If you break from a loop, the following lines of code in that loop are not executed. Also, the comparison you were doing would always return True because the answer would be in ("y", "n"). I also removed the last loop because it makes more sense that way.

As for the second code, the only thing that function start() is doing, is print("\nBMI Calculator"), again because of indentation levels.

Hope that helps :)

How can I loop back to the start of the code

You want to wrap everything in a function, like this anytime you need some sort of functionality you can simply invoke the function and here you have it!

This is what you should do:

def runProgram():
while(True):
playGame() # after this is done we will ask the user if they want to go again
if doesUserWantToPlayAgain() == True:
continue
else:
break

def playGame():
# All your code here

def doesUserWantToPlayAgain():
yes_or_no = input("would you like to start the quiz again?")
if yes_or_no == "yes":
return True
return False

runProgram() # call this as an entry point for your program

I hope you get the idea, feel free to ask questions :)

How to loop back a few lines?

user_unhappy = True
while user_unhappy:
#do stuff
#do stuff
user_input = input("ask question")
#do stuff
ask_user_happy = input("happy with choice?")
if ask_user_happy.casefold() == "y" or ask_user_happy.casefold() == "ye" or ask_user_happy.casefold() == "yes":
user_unhappy = False

How do I reset to the beginning of the code after it runs?

Yes, a loop is needed:

import re    
import requests

while True:
search = input('What word are you looking for?: ')
# per comment, adding a conditional stop point.
if search == "stop":
break

first = re.compile(search)

source = input ('Enter a web page: ')
r = requests.get(source)
ar = r.text

mo = first.findall(ar)
print (mo)

print('Frequency:', len(mo))

How to loop python script over at end

If you know how many times you want to run this code, use for loops ; if it mainly depends on a condition, use while loop. To run your code forever, do while True:.

Restarting code in Python 3.1

There are many ways, but this seems to be the shortest path:

Answer2 = "Yes"
while Answer2 == "Yes":
...
Answer2 = input("Do you want to restart? (Yes/No): ")

Typically you might want to .lower ().strip () Answer2 too.

How do I restart a program based on user input?

Try this:

while True:
# main program
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break

The inner while loop loops until the input is either 'y' or 'n'. If the input is 'y', the while loop starts again (continue keyword skips the remaining code and goes straight to the next iteration). If the input is 'n', the program ends.



Related Topics



Leave a reply



Submit