Print menu after selection - python

I want to print the menu again after someone enters a number (selects an option) on the same menu except for 5 which means quit. How can I do this? It has to print whatever it is in that option plus the menu again.
def main():
choice = '0'
while choice == '0':
print("Welcome to the Game!")
print("1) Sort by Value")
print("2) Sort by ID")
print("3) Find Card")
print("4) New Hand")
print("5) Quit")
choice = input("Please make a selection: ")
if choice == "5":
print("Thanks for Playing!")
elif choice == "4":
pass
elif choice == "3":
pass
elif choice == "2":
for i in range(1, 31):
myCard = Card(i)
print(myCard)
elif choice == "1":
myDeck = Deck()
print(myDeck)
else:
print("I don't understand your choice.")

You should put your if-statements in while-loop. And your while-loop condition should not be '0' if you intend to make '5' be quitting the game.
How about you create a function called print_menu(), and call it every time when you need it?
def print_menu():
print("1) Sort by Value")
print("2) Sort by ID")
print("3) Find Card")
print("4) New Hand")
print("5) Quit")
def main():
print("Welcome to the Game!")
print_menu()
while True:
choice = input("Please make a selection: ")
if choice == '5':
print("Thanks for Playing!")
break
elif choice == '4':
print_menu()
# something
elif choice == '3':
print_menu()
# something
elif choice == '2':
print_menu()
# something
elif choice == '1':
print_menu()
# something
else:
print("I don't understand your choice.")
print_menu()

Related

My function doesn't recognise variables that were created before it is called

I'm new to python and having trouble with my def's. I un-nested them because all my functions were nested in eachother, but now the function "percentified" is unable to find the variables "wins" "losses" and "ties". I'm new to python so any help is appreciated and the definition has to be a definition so that I can repeat the question if the user enters and incorrect value for an input.
Here is the code:
# Importing the random module
import random
import time
# The title of the game is printed
print("Rock, Paper, Scissors! - By Max Pearson")
# All user defined functions apart from code() are defined here
# Defining the first Rock Paper Scissors
def rps1():
# Take the users input of RPS
user_choice = input("What is your choice? Rock, Paper, or Scissors?: ")
# Strips and lowers user input
user_choice = user_choice.lower()
user_choice = user_choice.strip()
RPS = ["Rock", "Paper", "Scissors"]
computer_names = ["Computer", "Robot", "Android", "A.I", "PC", "Algorithm", "Laptop", "Alexa", "Windows"]
computer_name = random.choice(computer_names)
# Selecting the computer's choice
computer_choice = random.choice(RPS)
computer_choice = computer_choice.lower()
computer_choice = computer_choice.strip()
# Sets the parameters for when the user inputs Rock
if user_choice == "rock":
print("You have chosen Rock")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "paper":
print("You lose...")
else:
print("You win!")
# Sets the parameters for when the user inputs Paper
elif user_choice == "paper":
print("You have chosen Paper")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You win!")
else:
print("You lose...")
# Sets the parameters for when the user inputs Scissors
elif user_choice == "scissors":
print("You have chosen Scissors")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You lose...")
else:
print("You win!")
# Fallback for an invalid input
else:
print("Please enter a valid choice")
rps1()
# Defining the option for a new round
def newround():
# Take user input
playagain = input("Would you like to play again?(Yes/No): ")
# Stripping and lowering the variable
playagain = playagain.strip()
playagain = playagain.lower()
if playagain == "yes":
rps1()
elif playagain == "no":
print("Okay!")
else:
print("Please enter a valid input(Yes/No)")
newround()
# Defining the function to turn numbers into percentages
def percentage(x):
x = (x / num_sims) * 100
return x
# Gives the user the option to view statistics
def percentified():
# Take user input
percentages = input("Would you like these results in a statistic?: ")
percentages = percentages.lower()
percentages = percentages.strip()
if percentages == "yes":
# Printing and formatting the results
print(
"Here are the percentages to one decimal point:\nWins = {:.1f}%\nLosses = {:.1f}%\nTies = {:.1f}%".format(
percentage(wins), percentage(losses), percentage(ties)))
elif percentages == "no":
print("Okay, enjoy the results")
else:
print("Please enter a valid choice (Yes/No)")
percentified()
# The second gamemode of Rock Paper Scissors
def rps2():
# Defining a list for the random choice
RPS = ["Rock", "Paper", "Scissors"]
results = []
try:
# Takes an input from the user, to define the number of games
num_sims = int(input("Please enter the number of simulated games you would like: "))
# Loops for the number the user entered
if num_sims > 0:
for i in range(0, num_sims):
choice1 = random.choice(RPS)
choice2 = random.choice(RPS)
# Runs a check on every possible choice and adds the result to a list
if choice1 == choice2:
results.append("tie")
elif choice1 == "Rock" and choice2 == "Paper":
results.append("loss")
elif choice1 == "Rock" and choice2 == "Scissors":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Paper":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Rock":
results.append("loss")
elif choice1 == "Paper" and choice2 == "Rock":
results.append("win")
elif choice1 == "Paper" and choice2 == "Scissors":
results.append("loss")
else:
print("Please enter a valid choice")
rps2()
# Count the results and store them in a variable
wins = results.count("win")
losses = results.count("loss")
ties = results.count("tie")
# Print the user their results
print("Here are the results:\nWins = {}\nLosses = {}\nTies = {}".format(wins, losses, ties))
percentified()
else:
print("Please enter a valid number above 0")
rps2()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid number")
rps2()
try:
# Defining the entirety of the body of the code
def code():
time.sleep(0.5)
# Takes the users input
playstyle = int(input("Would you like to play RPS, or simulate a number of games? (1,2): "))
if playstyle == 1:
rps1()
newround()
# Checks if the user wants to simulate games
elif playstyle == 2:
rps2()
else:
print("Please enter a valid choice (1/2)")
code()
code()
# Fallback incase user enters a string to the integer input
except ValueError:
print("Please enter a valid choice (1/2)")
code()
And here is the error:
NameError: name 'wins' is not defined
percentified does not have access to variables defined in rps2. There are many ways to make wins available outside of the rps2 function —, best practice would be to either pass the local variable into the percentified function, or use object oriented programming to share instance variables (ie: self.wins).
Consider brushing up on Python variable scoping.
References
https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces

If an invalid input is entered, when it attempts to re-ask the input it seems to auto answer it with the previous answer

My code uses a lot of inputs, and to ensure replay-ability I have used functions to replay the code if they provide an invalid input. However if the user enters an invalid input, and the function runs, it seems to auto answer the input with the previous input.
(I apologize if this question is framed poorly, I am new to coding)
Here is the code:
# Importing the random module
import random
import time
# Take the playstyle input from the user
print("Rock, Paper, Scissors! - By Max Pearson")
try:
def code():
time.sleep(0.5)
playstyle = int(input("Would you like to play RPS, or simulate a number of games? (1,2): "))
if playstyle == 1:
def rps1():
# Take the users input of RPS
user_choice = input("What is your choice? Rock, Paper, or Scissors?: ")
# Strips and lowers user input
user_choice = user_choice.lower()
user_choice = user_choice.strip()
RPS = ["Rock", "Paper", "Scissors"]
computer_names = ["Computer", "Robot", "Android", "A.I", "PC", "Algorithm", "Laptop", "Alexa", "Windows"]
computer_name = random.choice(computer_names)
# Selecting the computer's choice
computer_choice = random.choice(RPS)
computer_choice = computer_choice.lower()
computer_choice = computer_choice.strip()
# Sets the parameters for when the user inputs Rock
if user_choice == "rock":
print("You have chosen Rock")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "paper":
print("You lose...")
else:
print("You win!")
# Sets the parameters for when the user inputs Paper
elif user_choice == "paper":
print("You have chosen Paper")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You win!")
else:
print("You lose...")
# Sets the parameters for when the user inputs Scissors
elif user_choice == "scissors":
print("You have chosen Scissors")
print("{} chose... {}".format(computer_name, computer_choice.title()))
if user_choice == computer_choice:
print("It's a tie!")
elif computer_choice == "rock":
print("You lose...")
else:
print("You win!")
# Fallback for an invalid input
else:
print("Please enter a valid choice")
rps1()
def newround():
playagain = input("Would you like to play again?(Yes/No): ")
playagain = playagain.strip()
playagain = playagain.lower()
if playagain == "yes":
rps1()
elif playagain == "no":
print("Okay!")
else:
print("Please enter a valid input(Yes/No)")
newround()
newround()
rps1()
# Checks if the user wants to simulate games
elif playstyle == 2:
def rps2():
def percentage(x):
x = (x / num_sims) * 100
return x
RPS = ["Rock", "Paper", "Scissors"]
results = []
try:
# Takes an input from the user, to define the number of games
num_sims = int(input("Please enter the number of simulated games you would like: "))
# Loops for the number the user entered
if num_sims > 0:
for i in range(0, num_sims):
choice1 = random.choice(RPS)
choice2 = random.choice(RPS)
# Runs a check on every possible choice and adds the result to a list
if choice1 == choice2:
results.append("tie")
elif choice1 == "Rock" and choice2 == "Paper":
results.append("loss")
elif choice1 == "Rock" and choice2 == "Scissors":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Paper":
results.append("win")
elif choice1 == "Scissors" and choice2 == "Rock":
results.append("loss")
elif choice1 == "Paper" and choice2 == "Rock":
results.append("win")
elif choice1 == "Paper" and choice2 == "Scissors":
results.append("loss")
else:
print("Please enter a valid choice")
# Count the results and store them in a variable
wins = results.count("win")
losses = results.count("loss")
ties = results.count("tie")
# Print the user their results
print("Here are the results:\nWins = {}\nLosses = {}\nTies = {}".format(wins, losses, ties))
def percentified():
percentages = input("Would you like these results in a statistic?: ")
percentages = percentages.lower()
percentages = percentages.strip()
if percentages == "yes":
print(
"Here are the percentages to one decimal point:\nWins = {:.1f}%\nLosses = {:.1f}%\nTies = {:.1f}%".format(
percentage(wins), percentage(losses), percentage(ties)))
elif percentages == "no":
print("Okay, enjoy the results")
else:
print("Please enter a valid choice (Yes/No)")
percentified()
percentified()
else:
print("Please enter a valid number above 0")
rps2()
except ValueError:
print("Please enter a valid number")
rps2()
else:
print("Please enter a valid choice (1/2)")
code()
code()
except ValueError:
print("Please enter a valid choice (1/2)")
code()

AttributeError: partially initialized module 'calculator' has no attribute 'select' (most likely due to a circular import)

I Am making a small project so i can learn python better, the project has 4 files (i could do this in one but well), 1 as main, 1 as the tool 1, the other as the tool 2 and the other as the tool 3.
i must import the main in the other 3 and the other 3 on the main, this creates a circular import. i cant find how to fix this. any help appreciated
Code:
main.py
import calculator
import texteditor
import textchecker
def start():
print("Operations:")
print("1) Calculator")
print("2) Text Editor")
print("3) Text Checker")
choice1 = input("Select operation: ")
if choice1 == "1":
calculator.select()
elif choice1 == "2":
texteditor.texthub()
elif choice1 == "3":
textchecker.textchub
start()
calculator.py
import main
def select():
while True:
print("Type the number of the operation you want in 'Select a calculation: '")
print("Calculations:")
print("1) Add")
print("2) Subtract")
print("3) Multiply")
print("4) Divide")
print("5) Back To Hub")
global calcinput
calcinput = input("Select a calculation: ")
if calcinput == "1":
global num1
global num2
num1 = int(input("First Number: "))
num2 = int(input("Second Number: "))
elif calcinput == "2":
num1 = int(input("First Number: "))
num2 = int(input("Second Number: "))
elif calcinput == "3":
num1 = int(input("First Number: "))
num2 = int(input("Second Number: "))
elif calcinput == "4":
num1 = int(input("First Number: "))
num2 = int(input("Second Number: "))
elif calcinput == "5":
main.start()
cont = input("Would you like to continue (Yes/No): ")
if cont == "Yes":
continue
elif cont == "No":
main.start()
else:
input("Invalid input. Try again (Yes/No): ")
if calcinput == "1":
print(num1 + num2)
elif calcinput == "2":
print(num1 - num2)
elif calcinput == "3":
print(num1 * num2)
elif calcinput == "4":
print(num1 / num2)
else:
print("Invalid Input!")
textchecker.py
import main
def textchub():
while True:
print("Text Checkers:")
print("1) LowerCase")
print("2) UpperCase")
print("3) Alphabetical")
print("4) Numerical")
print("5) AlNum (Alphabetical/Numerical")
print("6) Back to hub")
ci = input("Choose a checker (Number): ")
if ci == "1" and "2" and "3" and "4" and "5":
cia = input("Paste Text: ")
elif ci == "6":
main.start()
if ci == "1":
if cia.islower() == False:
print("Your text is not lowercase.")
elif cia.islower() == True:
print("Your text is lowercase.")
elif ci == "2":
if cia.isupper() == False:
print("Your text is not uppercase")
if cia.isupper() == True:
print("Your text is uppercase.")
elif ci == "3":
if cia.isalpha() == False:
print("Your text is not only alphabetical")
if cia.isalpha() == True:
print("Your text is only alphabetical.")
elif ci == "4":
if cia.isnumeric() == False:
print("Your text is not only numeric")
if cia.isnumeric() == True:
print("Your text is only numeric.")
elif ci == "5":
if cia.isalnum() == False:
print("Your text is not only AlphabeticalNumerical")
if cia.isalnum() == True:
print("Your text is only AlphabeticalNumerical.")
tcc = input("Would you like to continue Yes/No? ")
if tcc == "Yes":
continue
elif tcc == "No":
main.start
texteditor.py
import main
def texthub():
while True:
print("Editors:")
print("1) UpperCase Text (Every letter will be uppercase)")
print("2) LowerCase Text (Every letter will be lowercase)")
print("3) UpperCase Starting Letter (Every starting letter of every word will be uppercase)")
print("4) Back To Hub")
te = input("Select editor 1, 2, 3 or 4: ")
if te == "1":
t1 = str(input("Paste Text: "))
elif te == "2":
t1 = str(input("Paste Text: "))
elif te == "3":
t1 = str(input("Paste Text: "))
elif te == "4":
main.start()
else:
print("Invalid Input")
if te == "1":
print()
print("Here Is Your Text In UpperCase: " + t1.upper())
elif te == "2":
print()
print("Here Is Your Text In LowerCase: " + t1.lower())
elif te == "3":
print()
print("Here Is Your Text In Title Form: " + t1.title())
if te == "1":
tec = input("Would you like to edit another text Yes/No? ")
if te == "2":
tec = input("Would you like to edit another text Yes/No? ")
if te == "3":
tec = input("Would you like to edit another text Yes/No? ")
if tec == "Yes":
continue
elif tec == "No":
main.start()
error/traceback:
Traceback (most recent call last):
File "f:\Coding\Microsoft VS Code\CODES\Projects\Multi Tool\main.py", line 1, in <module>
import calculator
File "f:\Coding\Microsoft VS Code\CODES\Projects\Multi Tool\calculator.py", line 1, in <module>
import main
File "f:\Coding\Microsoft VS Code\CODES\Projects\Multi Tool\main.py", line 18, in <module>
start()
File "f:\Coding\Microsoft VS Code\CODES\Projects\Multi Tool\main.py", line 12, in start
calculator.select()
AttributeError: partially initialized module 'calculator' has no attribute 'select' (most likely due to a circular import)
Your code is almost right. __name__ is your friend.
According to the Official Python3 Documentation, there exist a couple of "Built-in relevant read-only attributes".
You will notice that if you make a small modification to main.py it will work fine (see below).
import calculator
import texteditor
import textchecker
def start():
print("Operations:")
print("1) Calculator")
print("2) Text Editor")
print("3) Text Checker")
choice1 = input("Select operation: ")
if choice1 == "1":
calculator.select()
elif choice1 == "2":
texteditor.texthub()
elif choice1 == "3":
textchecker.textchub
if __name__=='__main__':
# protect the "start()" with a __name__==__main__ guard
start()
To keep it simple just remember: when importing modules, __name__ is different from ___main___ so those lines won't be executed.
The only time __name__==__main__ yields true is when you run it yourself from command-line, i.e. >python3 main.py.
EDIT: as mentioned in another answer, this does not fix the circular import issue. This is a valid observation in terms of architecture, but please remember that Python is a very flexible and interpreted language, and there is nothing formally preventing you to import from main.py. Just note the power of discerning "who is importing you" by the built-in attributes (__name__), and keep acquiring the best-practices in design outside the scope of this question.
You are importing main from calculator.py, textchecker.py and texteditor.py. While also importing those in main. So, when it tries to resolve this:
in main.py:
--> load in calculator
in calculator.py
--> load in main
in main.py:
--> load in calculator
... you see what goes wrong.
there are 2 solutions to you problem:
in my opinion the best solution
in all the other files besides main replace main.start() with return None. I think your program will continue working as you intended. And remove the imports from those files.
If you want to keep you program running exaclty as it does now(not really good practice)
switch the order of the definition of imports and the function
def start(): ...
# ecapsulate everything in a while here, and add an else: return None
# every other input when choosing will break the loop and stop the program
import ...
then in the rest of the files:
from main import start
But I don't think this is ideal since you will nest function frames and thats memory expensive.
PS: also look add the other answer and add the __name__ == "__main__"
general advise: It's generally not a good idea to import from main. Try to design the calculator, ... keeping in mind you don't know how it's going to be used, just the bare bones functionality(in this case prompt some questions for calculations for example). then in main you can call those functions without them relying on the use case. Say you want a second interface to calculator, .. What are you gonna do then?

How can I return my code to the start of the code?

I've been trying to return my code to the beginning after the player chooses 'yes' when asked to restart the game. How do I make the game restart?
I've tried as many solutions as possible and have ended up with this code. Including continue, break, and several other obvious options.
import time
def start():
score = 0
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurist to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
print("Type 1 to explore Atlantis alone.")
time.sleep(1.5)
print("Type 2 to talk to the resident merpeople.")
start()
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = -1
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
score = 1
print("To explore alone enter 5. To go to the surface enter 6.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 4
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
print("Type 3 to go to the castle or 4 to go to the surface.")
score = 5
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
score = 6
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
print("Wanna play again?If you do, type yes! If you wanna leave, type no!")
def choice_made():
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
def choice2_made():
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
elif choice2 == "3":
castle()
elif choice2 == "yes":
start()
elif choice2 == "no":
exit()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
def choice3_made():
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
def restart_made():
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
while True:
choice = input("Make your decision!\n ")
if choice == "1":
drowndeath()
elif choice == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice_made()
choice_made()
while True:
choice2 = input("What do you do?\n ")
if choice2 == "4":
surface()
if choice2 == "3":
castle()
else:
print("Please enter a valid answer.")
choice2_made()
choice2_made()
while True:
choice3 = input("Make up your mind!\n ")
if choice3 == "5":
alone()
if choice3 == "6":
famous()
if choice3 == "1":
drowndeath()
if choice3 == "2":
merpeople()
else:
print("Please enter a valid answer.")
choice3_made()
choice3_made()
while True:
restart = input("Type your answer!\n ")
if restart == "yes":
sys.exit()
elif restart == "no":
exit()
else:
print("Please choose yes or no!")
restart_made()
restart_made()
I want for my code to restart completely when 'yes' is typed after given the option.
In general, if you want to be able to 'go back to the beginning' of something, you want to have a loop that contains everything. Like
while True:
""" game code """
That would basically repeat your entire game over and over. If you want it to end by default, and only restart in certain situations, you would do
while True:
""" game code """
if your_restart_condition:
continue # This will restart the loop
if your_exit_condition:
break # This will break the loop, i.e. exit the game and prevent restart
""" more game code """
break # This will break the loop if it gets to the end
To make things a little easier, you could make use of exceptions. Raise a RestartException whenever you want to restart the loop, even from within one of your functions. Or raise an ExitException when you want to exit the loop.
class RestartException(Exception):
pass
class ExitException(Exception):
pass
while True:
try:
""" game code """
except RestartException:
continue
except ExitException:
break
break
You have two main options.
First option: make a main function that, when called, executes your script once. Then, for the actual execution of the code, do this:
while True:
main()
if input("Would you like to restart? Type 'y' or 'yes' if so.").lower() not in ['y', 'yes']:
break
Second, less compatible option: use os or subprocess to issue a shell command to execute the script again, e.g os.system("python3 filename.py").
EDIT: Despite the fact this is discouraged on SO, I decided to help a friend out and rewrote your script. Please do not ask for this in the future. Here it is:
import time, sys
score = 0
def makeChoice(message1, message2):
try:
print("Type 1 "+message1+".")
time.sleep(1.5)
print("Type 2 "+message2+".")
ans = int(input("Which do you choose? "))
print()
if ans in (1,2):
return ans
else:
print("Please enter a valid number.")
return makeChoice(message1, message2)
except ValueError:
print("Please enter either 1 or 2.")
return makeChoice(message1, message2)
def askRestart():
if input("Would you like to restart? Type 'y' or 'yes' if so. ").lower() in ['y', 'yes']:
print()
print("Okay. Restarting game!")
playGame()
else:
print("Thanks for playing! Goodbye!")
sys.exit(0)
def surface():
print("You return to the surface.")
print("When you go back to Atlantis it's gone!")
print("Your findings are turned to myth.")
print("The end!")
def castle():
print("The merpeople welcome you to their castle.")
print("It is beautiful and you get oxygen.")
print("Now that you have your oxygen, you can either go to the surface or explore Atlantis alone.")
def drowndeath():
print("You begin to explore around you.")
print("You avoid the merpeople who avoid you in return.")
print("But, OH NO, your oxygen begins to run out!")
print("You run out of air and die.")
def merpeople():
print("The merpeople talk kindly to you.")
print("They warn you that your oxygen tank is running low!")
print("You can follow them to their castle or go back to the surface.")
def alone():
print("You begin to explore alone and discover a secret caven.")
print("You go inside and rocks trap you inside!")
print("You die underwater.")
def famous():
print("You come back to land with new discoveries!")
print("Everyone loves you and the two worlds are now connected!")
print("You win!")
def playGame():
print("Welcome to Atlantis, the sunken city!")
time.sleep(1.5)
print("You are the first adventurer to discover it!")
time.sleep(1.5)
print("Do you explore or talk to the merpeople?")
time.sleep(1.5)
ans = makeChoice("to explore Atlantis alone", "to talk to the resident merpeople")
if ans == 1:
drowndeath()
askRestart()
merpeople()
ans = makeChoice("to go to the castle", "to return to the surface")
if ans == 2:
surface()
askRestart()
castle()
ans = makeChoice("to return to the surface", "to explore alone")
if ans == 1:
famous()
else:
alone()
askRestart()
playGame()

my first else condition jumps to the second else

So i am trying to NOT let the first ELSE proceed until it meets the condition to require an input that will include only 1 or 2 or 3... but it failes to do so... after 1 time print it goes on to the second ELSE... what am i doing wrong here ?
def line_func(): # line to separate
print("==========================================================================")
def vs1():
print("") # vertical space
def start1():
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
while True:
start = input("Answer: ")
vs1()
if start == "y" or start == "Y" or start == "yes" or start == "YES" or start == "Yes":
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
elif start == "n" or start == "N" or start == "no" or start == "NO" or start == "No":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose with yes or no...")
start1()
try the below code, working for me:
def line_func(): # line to separate
print("==========================================================================")
def vs1():
print("") # vertical space
def start1():
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
while not start:
start = input("Answer: ")
vs1()
if start == "y" or start == "Y" or start == "yes" or start == "YES" or start == "Yes":
start = True
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
elif start == "n" or start == "N" or start == "no" or start == "NO" or start == "No":
start = True
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose with yes or no...")
start = False
start1()
while True:
line_func()
vs1()
menu1 = input("How would you like to proceed?\n\n1)Find an enemy to crush\n2)Restart game\n3)Exit game\n\nodgovor: ")
if menu1 == "1":
vs1()
start_round()
elif menu1 == "2":
vs1()
print("================= RESTARTING GAME ===================")
vs1()
print("=====================================================")
print("Would you like to start? Choose with (y)yes or (n)no.\n=====================================================\n")
continue
start1()
elif menu1 == "3":
print("Ok see you next time... bye bye :)")
break
else:
print("You have to choose one of the options to proceed...")
What you need is another while loop.The break condition is up to your demand.

Categories