Is there a way to loop back to the beginning of a certain part of the code in python
Two ways of doing it, using a while True
:
while True:
x=input("input a word: ")
if len(x) == 8:
break
print("word must have 8 characters")
Using recursion:
def get_input():
x=input("input a word: ")
if len(x) == 8:
return x
print("word must have 8 characters")
return get_input()
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 start of question in case of incorrect input in a yes/no game?
A good way to solve this would be error handling - create a custom Exception
and throw it whenever a wrong answer is given. Loop until you passed all questions without exception and then break.
I also modified your ask-function , there is no need for recursion in it, simply loop and return when a valid answer is given.
def askYesNoQuestion(question):
"""Asks a question, accepts only Y or N as answer. Repeats until given."""
while True:
YesNoAnswer = input(question).strip().upper()
if YesNoAnswer in ("Y,N"):
return YesNoAnswer
else:
print('Please enter Y or N!')
class WrongAnswer(Exception):
"""Custom exception, thrown (and caught) on bad answers"""
pass
while True:
try:
animal_answer1 = askYesNoQuestion("Is a parrot a bird? Y/N ")
if animal_answer1 == "Y":
print("Correct!")
else:
raise WrongAnswer()
animal_answer2 = askYesNoQuestion("Is a whale a mammal? Y/N ")
if animal_answer2 == "Y":
print("Correct! Move on")
else:
raise WrongAnswer()
animal_answer3 = askYesNoQuestion("Is a kangaroo a marsupial? Y/N ")
if animal_answer3 == "Y":
print("We will see... let us move on")
else:
raise WrongAnswer()
food_answer1 = askYesNoQuestion("Is a carrot a vegetable? Y/N ")
if food_answer1 == "Y":
print("Correct!")
else:
raise WrongAnswer()
food_answer2 = askYesNoQuestion("Is a tomato a vegetable? Y/N ")
if food_answer2 == "N":
print("Correct! Move on")
else:
raise WrongAnswer()
food_answer3 = askYesNoQuestion("Is a strawberry a berry? Y/N ")
if food_answer3 == "N":
print("We will see... let us move on")
else:
raise WrongAnswer()
except WrongAnswer:
print("Meeeep, wrong - go again.\n")
else:
break # executes if all questions passed without raising exception
print("Cool - all correct!")
Output:
Is a parrot a bird? Y/N y
Correct!
Is a whale a mammal? Y/N n
Meeeep, wrong - go again.
Is a parrot a bird? Y/N y
Correct!
Is a whale a mammal? Y/N y
Correct! Move on
Is a kangaroo a marsupial? Y/N y
We will see... let us move on
Is a carrot a vegetable? Y/N y
Correct!
Is a tomato a vegetable? Y/N n
Correct! Move on
Is a strawberry a berry? Y/N y
Meeeep, wrong - go again.
Is a parrot a bird? Y/N y
Correct!
Is a whale a mammal? Y/N y
Correct! Move on
Is a kangaroo a marsupial? Y/N y
We will see... let us move on
Is a carrot a vegetable? Y/N y
Correct!
Is a tomato a vegetable? Y/N n
Correct! Move on
Is a strawberry a berry? Y/N n
We will see... let us move on
Cool - all correct!
Delegating the question-correctness-testing also to askYesNoQuestion
leads to much shorter code:
def askYesNoQuestion(question, answer):
"""Asks a 'question', accepts only Y or N, loops until given.
Raises WrongAnswer exception if different from 'answer'"""
while True:
YesNoAnswer = input(question).strip().upper()
if YesNoAnswer in ("Y,N"):
if YesNoAnswer == answer:
return
else:
raise WrongAnswer()
else:
print('Please enter Y or N!')
while True:
try:
animal_answer1 = askYesNoQuestion("Is a parrot a bird? Y/N ", "Y")
print("Correct!")
animal_answer2 = askYesNoQuestion("Is a whale a mammal? Y/N ","Y")
print("Correct! Move on")
animal_answer3 = askYesNoQuestion("Is a kangaroo a marsupial? Y/N ","Y")
print("We will see... let's move on")
food_answer1 = askYesNoQuestion("Is a carrot a vegetable? Y/N ", "Y")
print("Correct!")
food_answer2 = askYesNoQuestion("Is a tomato a vegetable? Y/N ", "N")
print("Correct! Move on")
food_answer3 = askYesNoQuestion("Is a strawberry a berry? Y/N ", "N")
print("We will see... let's move on")
except WrongAnswer:
print("Meeeep, wrong - go again.")
else:
break
print("Cool - all correct!")
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()
Related Topics
How to Convert Datetime to Integer in Python
Best Way to Get the Max Value in a Spark Dataframe Column
Using Python, How to Access a Shared Folder on Windows Network
Python, Delete Json Element Having Specific Key from a Loop
How to Allocate Array With Shape and Data Type
Remove White Space from Entire Dataframe
How to Clear Your Printed Text in Python
Replacing Blank Values (White Space) With Nan in Pandas
Python Pandas Valueerror Arrays Must Be All Same Length
Regular Expression: Match Everything After a Particular Word
Export Pandas Dataframe into a Pdf File Using Python
Python: Fastest Way to Compare Arrays Elementwise
How to Check If Numbers Are in a List in Python
How to Run External Executable Using Python
How to Count Occurrences of Key in List of Dictionaries
Django: Check Whether an Object Already Exists Before Adding
How to Concatenate Multiple Column Values into a Single Column in Pandas Dataframe