How do i make this program re-run from the beginning after the input "yes" - python-3.3

print("1, Rice")
print("2, Amala")
print("3, Semolina")
print("4, Chicken")
Mainchoice=int(input("Select a number of choice:"))
if(Mainchoice==1):
print("1, Rice and Beans with meat/fish.")
print("2, Jollof Rice and chicken wings.")
print("3, Fried Rice and Beef.")
Rice=int(input("Select a Rice of choice:"))
if(Rice==1):
print("You selected Rice and Beans with meat/fish.")
elif(Rice==2):
print("You selected Jollof Rice and Chicken wings.")
elif(Rice==3):
print("You selected Fried Rice and Beef.")
else:
print("Please select a valid number from the list above.")
elif(Mainchoice==2):
print("1, Amala and ewedu with beef.")
print("2, Amala and efo riro with assorted meat.")
print("3, Amala and egusi soup with meat.")
Amala=int(input("Select an Amala of choice:"))
if(Amala==1):
print("You selected Amala and ewedu with beef.")
elif(Amala==2):
print("You selected Amala and efo riro with assorted meat.")
elif(Amala==3):
print("You selected Amala and egusi with meat.")
else:
print("Please select a valid number from the list.")
elif(Mainchoice==3):
print("1, Semolina and Ogbono soup with meat.")
print("2, Semolina and efo riro with beef.")
print("3, Semolina with egusi soup and draw.")
Semolina=int(input("Select Semolina of choice:"))
if(Semolina==1):
print("You selected Semolina and Ogbono soup with meat.")
elif(Semolina==2):
print("You selscted Semolina and efo riro with beef.")
elif(Semolina==3):
print("You selected Semolina with egusi soup and draw.")
else:
print("Plese select a valid command from the list.")
elif(Mainchoice==4):
print("1, Grilled Chicken breast and laps.")
print("2, Roasted Full Chicken with tomato ketchup sauce.")
print("3, Chicken Barbeque.")
Chicken=int(input("Select a Chicken of choice:"))
if(Chicken==1):
print("You selected Grilled Chicken braest and laps.")
elif(Chicken==2):
print("You selected Roasted Full Chicken with tomato ketchup sauce.")
elif(Chicken==3):
print("You selected Chicken Barbeque.")
else:
print("Please select a valid command from the list.")
else:
print("Please select a valid number.")
def Canteen():
return str (Mainchoice)
def Loop():
r=(input("Would you like to re-select the options again?:"))
if (r=="yes"):
Loop()
if (r=="No"):
print("Goodbye")
Loop()
The code helps a user pre-order food at a canteen.
It displays the food item after the user enters the selected food item. Please what python code line do I add to make the program re-run from the beginning after the user enter "yes".
I have been able to figure out the "No" option.
Any solution would be appreciated.
Thank you.

Just edit your last line.
if __name__ == "__main__":
while True:
Loop()
If you need to quit from here, use Control + C

Related

i want to print dictionary keys and values separately with given string in python for my project

I'm not able to finish the project given below if someone help me with the particular function paasenger_login ...help me out
The project is flight reservation system with basic pyhton programming
a. Passenger
1. sign in
2.check availability and fare
3.book ticket
b. Cashier
1.approve
2.issue ticket
the code is below
s=[]
class passenger:
pass
class book:
d={}
f={}
pact=1-000-000
new=0
class cashier:
def caslogin():
while True:
print("\t1.Filling Tickets\n\t2.passenger Info\n\t3.Approve Tickets\n\t4.Logout")
x=input()
if x=='1':
if (book.new==0):
flight=int(input("Enter the no of flights: "))
for i in range(flight):
print("Enter name of the flights: ")
q=input()
print("Enter the price for to travel:\n")
op=[]
op.append(input())
book.d[q]=op
print("Successfully loaded:\n")
book.new=1
else:
print("\n\tAlready loaded")
elif x=='2':
if book.pact<=1-000-000:
print("NO user found!................")
else:
for i in range(len(s)):
print(s[i].name,i+1-000-000,s[i].history,s[i].report)
elif x=='3':
if book.pact<=1-000-000:
print("NO record found!................")
else:
for i in s:
print(i.name,i.report)
else:
break
def passenger_login(rn):
while True:
print("Successfully logged in... \n\t1.Book Tickets\n\t2.Approval\n\t3.Logout")
n=input()
if n=='1':
if len(book.d):
for i in book.d:
print(str(i),str(book.d[i]))
else:
break
def __main__():
print("Air Asia\n")
while True:
print("Login as\n\t1.Cashier\n\t2.passenger\n\t3.Exit")
n=input()
if n=='1':
cashier.caslogin()
elif n=='2':
while True:
print("Passenger Info\n\t1.Sign in\n\t2.Sign up\n\t3.Logout")
x=input()
if x=='1':
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Enter the serial no:")
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Try after few minutes")
if reg != len(s):
print("NO account found")
else:
if s[reg-1-000-000].ps==Pass:
passenger_login(reg-1-000-000)
elif x=='2':
s.append(passenger())
s[book.pact - 1-000-000].name=input("Enter your name:\n")
s[book.pact - 1-000-000].ps=input("create password:\n")
s[book.pact - 1-000-000].history=0
s[book.pact - 1-000-000].report="New user"
print("Your serial no is : ",book.pact)
book.pact+=1
else:
break
else:
break
__main__()

Second loop, game not working and Sublime Text problems

I am working on a very simple 'game' where the player gets 5 guesses to guess a random number.
It's not done yet but I have run into a couple of problems.
This is the code that generates a random number and allows the player to guess
Relevant code:
def GuessLoopFunc(guess):
import random
import sys
import time
sum_guesses = 0
rand_num = random.randrange(1, 21)
print(rand_num)
#This is just for test purposes to know the correct number and see what happens when I guess the correct number
while True:
if guess == rand_num:
print("You got it right!")
else:
sum_guesses += 1
if sum_guesses == 4:
guess = input("That's incorrect...final guess: ")
continue
elif sum_guesses == 5:
print("Oh no! You lost!")
while True:
replay = input("Do you want to play again: ")
if replay == "yes" or replay == "Yes":
pass #Temporary while I figure out how to loop back to very start (new random number)
elif replay == "no" or replay == "No":
print("Goodbye")
break
else:
print("I do not understand what you mean...")
continue
else:
guess = input("You got it wrong, guess again: ")
continue
As you can see by the comments I made, I want the game the return to the very start of the program if the player indicates they want to play again (so they get a new random number.
Also, for some reason, the game doesn't register when the correct answer was given and keeps on telling the player that his answer was incorrect...this is the code of the game where the above module is called:
import sys
import random
import time
from GuessLoop import GuessLoopFunc
print("Hello! Welcome to the guess the number game!")
name_player = input("Please enter your name: ")
print("Hello " + str(name_player) + "!")
play = input("Are you ready to play? ")
if play == "Yes" or play == "yes":
print("Great! Let's get started...")
elif play == "No" or play == "no":
print("Too bad...")
sys.exit()
else:
print("I do not understand your response...")
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
else:
print("I do not understand your response...quitting.")
sys.exit()
print("I am going to think of think of a number between 1 and 20...")
print("You will get 5 guesses to guess the number...")
time.sleep(1)
print("Okay, I have a number in mind")
guess = input("What is your guess? ")
GuessLoopFunc(guess)
time.sleep(1)
sys.exit()
Finally, when I try to run the program in Sublime Text it doesn't run further than the "Please enter your name: " part. If I fill in my name and press enter, nothing happens...but no error message displays either. So I have resorted to testing the program in the Python IDLE every time, but it's a bit tedious...anyone know what's up.
Your main problem is that you compare your userinput (a string) with a random number (integer) - they will never be the same as string != int.
Solution:
You need to convert the user input to a number via the int(text) function.
def getInt(text):
while True:
try:
n = input(text)
return int(n)
except ValueError: # if the input is not a number try again
print(f"{n} is not a number! Input a number")
....
guess = getInt("What is your guess?") # now that is an int
....
You have lots of duplicate "yes/no" codeparts that you can streamline:
def YesNo(text):
'''Ask 'test', returns True if 'yes' was answerd else False'''
while True:
answer = input(text).strip().lower()
if answer not in {"yes","no"}:
print("Please answer 'yes' or 'no'")
continue # loop until yes or no was answered
return answer == "yes"
This reduces
quit1 = input("Do you want to quit? ")
if quit1 == "yes" or quit1 == "Yes":
sys.exit()
elif quit1 == "no" or quit1 == "No":
print("Great! Let's get started!")
to
if YesNo("Do you want to quit? "):
sys.exit()
else:
pass # do somthing
and use that in all yes/no questions.
To play again I would move the "Do you want to play again" question out of the game loop:
# do your name questioning and greeting here
# and then enter an endless loop that you break from if not playing again
while True:
GuessLoopFunc() # move the guess input inside the GuessLoopFunk as it has
# to be done 5 times anyhow. If you spend 5 guesses or
# guessed correctly, print some message and return to here
if YesNo("Play again? "):
continue
else:
break # or sys.exit()
To fix the sublime problem: Issue with Sublime Text 3's build system - can't get input from running program

Why Am I Getting ELIF Invalid Syntax Error?

When i went from python 2.7 to python 3.5 I started having problem with ELIF statement.
I am using PyCharm so when i enter elif statement it shows an error and this1
this is what jumps up as error solution
and when I press it this happens but code still doesn't works...
doesn't let me post this pic, it will be in comments
Anyways, i cant post code for some reason so it will be in comments if you need him and please help me if you can because this is not first time happening, I can't find help anywhere and well it's really annoying...
Your first error is not having an initial if statement as well as having game = '1': instead of game == '1':. If you look at my code I have fixed these errors and fixed the indentation as it was causing some bugs
import os
print("\nWelcome, enter Your name please")
name = input("--> ")
def username(name): #NAME
while len(name) < 2:
print("There was an error")
name = input("\nPlease enter Your name again -->")
else:
print("Hello,", name)
username(name)
def menu(): #MENU
print("\nWelcome to the menu")
print("From here You can chose the game")
print("For now, we have only 3 game but there will be plenty more!")
print("Chose game by it's number ")
print("1 - Coin flip| 2 - Horse racing| 3 - Loto|")
menu()
game = int(input("--> "))
def choice(game): #CHOOSING GAME
while game > 3 or game < 1:
print("\nSomething went wrong, enter game you want again (only numbers 1, 2, 3!")
game = int(input("--> "))
if game == '1': #if statement first and two "=" signs
print("You chose Coin flip game")
os.system('python coinflip.py')
elif game == '2': #use tab to indent properly
print("You chose Horse racing game")
os.system('python horseracing.py')
elif game == '3': #keep indentations the same throughout
print("You chose Loto game")
os.system("python loto.py")
choice(game)
You need to firstly type "if" and the "elif". So it should be something like that:
def choice(game): #CHOOSING GAME
while game > 3 or game < 1:
print("\nSomething went wrong, enter game you want again (only numbers 1, 2, 3!")
game = int(input("--> "))
if game == '1': #bug here
print("You chose Coin flip game")
os.system('python coinflip.py')
elif game == '2': #and here
print("You chose Horse racing game")
os.system('python horseracing.py')
elif game == '3': #and here
print("You chose Loto game")
os.system("python loto.py")

Can anyone see why i get UnBoundLocal Error for my score varible

Can anyone see why I get "UnBoundLocal Error" for my score varible?
import random
Score=0
def Main_Menu(Score):
print("=============================")
print("WELCOME TO MY QUIZ")
print("=============================")
while True:
Username=input("What is your name?")
if Username.isalpha():
if len(Username)>11:
print("You are only a maximum of 11 characters")
else:
Username=Username.title()
break
else:
print("Letters only")
while True:
while True:
Option=input("What do you want to do?\n1 For Quiz\n2 To Quit.")
if Option.isdigit():
Option=int(Option)
break
else:
print("Numbers Only.")
if Option==1:
for x in range(10):
Quiz(Username)
print("You have scored",Score,"point out of 10!!\n")
elif Option==2:
input("Press Enter to quit the program")
break
else:
print("You only have 2 options")
Quiz(Username)
def Quiz(Username):
Tries=3
Number_One=random.randint (0,10)
Number_Two=random.randint (0,10)
Arithmetic_Operator=random.choice(["+","-","*",])
if Arithmetic_Operator=="+":
print(Username,"\nWhat is",Number_Two,"+",Number_One,"?")
Answer=Number_Two+Number_One
elif Arithmetic_Operator=="-":
print(Username,"\nWhat is",Number_Two,"-",Number_One,"?")
Answer=Number_Two-Number_One
elif Arithmetic_Operator=="*":
print(Username,"\nWhat is",Number_Two,"*",Number_One,"?")
Answer=Number_Two*Number_One
while Tries!=0:
while True:
Guess=input("Answer: ")
if Guess.isdigit():
Guess=int(Guess)
break
else:
print("Numbers Only.")
if Guess==Answer:
print("Well Done.You got it right.\nYou have a point")
Score=Score+1
break
elif Guess!=Answer:
Tries=Tries-1
print("You have",Tries,"tries left")
if Tries==0:
print("The answer is",Answer)
Main_Menu(Score)
You are getting the UnboundLocalError: local variable 'Score' referenced before assignment error because the Quiz method doesn't have a local variable Score but is trying to read from it. You probably meant to use the the global variable Score, but it's not available in the method scope without using the global statement. You can fix this by adding global Score in the beginning of the Quiz method.
However, using globals in python code is another discussion, I would strongly recommend avoiding them, unless there's really a proper reason to use them. Please see this SO for more details and discussion.

Python 3 : Global name 'inSet' is not defined

I've just began learning Python 3 about 2 weeks ago. I decided to make a basic text game However, I've run into a bug in the code that I can't seem to fix, and that I can't find anywhere else. When I run my game (code incoming), I get this error:
Welcome to the room. This is the room in which this game takes place
Press enter to continue.
What would you like to do? Type HELP for your options
HELP
Traceback (most recent call last):
File "C:/Users/Michael/Desktop/mess.py", line 35, in <module>
inputFunc()
File "C:/Users/Michael/Desktop/mess.py", line 7, in inputFunc
inputExam()
File "C:/Users/Michael/Desktop/mess.py", line 9, in inputExam
if (inSet == "LOOK"):
NameError: global name 'inSet' is not defined
Here is the code for my game:
# functions:
def youLose():
print("You lost.")
def inputFunc():
print("What would you like to do? Type HELP for your options")
inSet = input()
inputExam()
def inputExam():
if (inSet == "LOOK"):
print("You are in a room. There is a door in front of you. You have a key in your hand. There is a slip of paper on the ground.")
inputFunc()
elif (inSet == "HELP"):
print("Use LOOK to examine your surroundings. Use OPEN to open things. Use EXAMINE to examine things. Use QUIT to quit the game. Remember to use ALL CAPS so the processor can understand you")
inputFunc()
elif (inSet == "EXAMINE PAPER"):
print("The paper reads: 'There is only one winning move'")
inputFunc()
elif (inSet == "OPEN DOOR"):
print("You open the door using your key. There is a bright light on the other side, blinding you. You feel a familiar feeling as you realize that you have died.")
input("Press enter to continue.")
youLose()
elif (inSet == "EXAMINE DOOR"):
print("A simple oaken door.")
inputFunc()
elif (inSet == "QUIT"):
print("You hear a clicking of gears. You realize that the only winning move is not to play. You Win!")
elif (inSet == "EXAMINE KEY"):
print("A small, brass key that looks to fit the lock on the door.")
inputFunc()
else:
print("Syntax Error")
# base:
print("Welcome to the room. This is the room in which this game takes place")
input("Press enter to continue.")
inputFunc()
Your problem is variable scope:
def inputFunc():
print("What would you like to do? Type HELP for your options")
inSet = input()
inputExam()
def inputExam():
if (inSet == "LOOK"):
...
inSet is defined in inputFunc. It doesn't exist outside of inputFunc, so you cannot use it in inputExam.
You can either make it a global:
inSet = ''
def inputFunc():
global inSet
print("What would you like to do? Type HELP for your options")
inSet = input()
inputExam()
def inputExam():
global inSet
if (inSet == "LOOK"):
...
Or pass it as an argument to inputExam:
def inputFunc():
print("What would you like to do? Type HELP for your options")
inSet = input()
inputExam(inSet)
def inputExam(inSet):
if (inSet == "LOOK"):
...
I would go with the latter.

Resources