My problem is that my Random function doesn't get called from the Menu function. I've tried everything, but it still doesn't work. It's weird, because i think that i have structured the functions correctly, and everything should work fine, but it doesn't call Random.
def Menu():
name = raw_input("What's your name?\n:")
print "Hello, %s!\nWeclome to the Guessing Game!" % name
print "Select an option:"
print "1- Guess a number between 1-100."
print "2- Guess a number between 1-1000."
print "3- Guess a number between 1-10,000."
print "4- Guess a number between 1-100,000."
print "5- Exit."
try:
selection = raw_input("Enter your selection:")
if selection == 1:
Random(100)
elif selection == 2:
Random(1000)
elif selection == 3:
Random(10000)
elif selection == 4:
Random(100000)
elif selection == 5:
exit()
except:
os.system("clear")
print "Sorry, that wasn't an option. Enter your selection again."
Menu()
raw_input() retuns a string so you have to cast the input to int or compare the input with strings. Either this way:
selection = raw_input("Enter your selection:")
if selection == "1":
Random(100)
elif selection == "2":
Random(1000)
elif selection == "3":
Random(10000)
elif selection == "4":
Random(100000)
elif selection == "5":
exit()
or this way:
selection = raw_input("Enter your selection:")
if int(selection) == 1:
Random(100)
elif int(selection) == 2:
Random(1000)
elif int(selection) == 3:
Random(10000)
elif int(selection) == 4:
Random(100000)
elif int(selection) == 5:
exit()
Furthermore you can avoid try by kicking out elif int(selection) == 5: and using else:" instead. So the game will be ended with any other input than 1,2,3 or 4. There will be no possibility to "enter your selection again" after calling except in your code anyway because the script stops.
The function Random is not very optimal. See this:
def Random(select):
range = "1-" + str(select)
Correct_Guess = random.randint(1,select+1)
Difficulty()
It is the same but shorte and more readable ;)
Related
I have simplified it to this:
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
def two_player_word():
print("2")
elif gameinput == "1":
def one_player_word():
print("1")
def hangman():
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman()
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
I had previously defined gameinput in the 'hang()' it collects the user input and so on.
My problem is in the 'hangman()' I need gameinput again to make the variable word (its made so a user can either make a word (two_player_word) or one player when it generates a random word (one_player_word()
It works perfectly without gameinput being in a function but after the player either wins or loses I want it to let the user decide if they want to change gamemode or not as shown in main().
There is a lot more code but figured it would be easier to try figure out the problem using just this.
Just pass the gameinput from hang into hangman as an argument.
def hang():
while True:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput not in ("1", "2"):
continue
hangman(gameinput)
break
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
There are two problems that cause your code to fail (besides indentation).
You are defining nested functions (one/two_player_word) which you then try to call from outside the function (where they are not defined). You can change this by defining the functions outside the function hang().
hangman() uses the gameinput variable but it's not defined nor provided. You can change this by adding it as a parameter to the function call.
Your adjusted code could work like this:
import time
def one_player_word():
print("1")
def two_player_word():
print("2")
def hang():
p = 1
while p == 1:
gameinput = input("Please select a gamemode, Type [1] for one player or Type [2] for two player: ")
if gameinput == "2":
two_player_word()
elif gameinput == "1":
one_player_word()
def hangman(gameinput):
if gameinput == "2":
word = two_player_word()
elif gameinput == "1":
word = one_player_word()
print("Word")
def main():
gamerestart = 1
while gamerestart == 1:
print()
print("Would you like to play again?")
gameoverinput = input("Press [1] to play again, Press [2] to exit program. ")
if gameoverinput == "1":
for i in range(0, 25):
print()
hangman(gameoverinput)
elif gameoverinput == "2":
print("Thank you for playing, goodbye....")
time.sleep(2)
quit()
else:
print("Invaild option.")
if __name__ == "__main__":
main()
I'm currently making a main menu for my scoring system that will take the user to different parts of code by using while loops as a simple form of validation but it causes a never ending while loops because some of my definition also have while loops as well. Here's what I've done
def menu():
print("""\n Main Menu \n
1) Join the Event as a Team
2) Join the Event by Yourself
3) Score Screen""")
menuchoice_option = ["1","2","3"]
menuchoice = ""
while menuchoice not in menuchoice_option:
menuchoice = input("Please enter your choice here:")
if menuchoice == "1":
team_menu()
menuchoice = True
elif menuchoice == "2":
individual()
menuchoice = True
elif menuchoice == "3":
#scorescreen()
menuchoice = True
else:
menuchoice = False
print("Please enter a value between 1-3")
menuchoice = input("Please enter your choice here:")
Here's my other functions that the menu def causes to do an infinite whille loops
def team_menu():
global teamS
team_player = ""
while team_player != "":
team_player = input("What is your name:")
print("""\n Available Teams \n
1) Team Ahab
2) Team Ishmael
\n 3) Go back to Main Menu\n""")
team_choice = ""
team_choice_option = ["1","2","3"] # all valid choices on team menu
while team_choice not in team_choice_option:
team_choice = input("Enter your choice here:")
if team_choice == "1":
teamS["Team 1"]["Team Ahab"].append(team_player)
print(teamS["Team 1"])
print("Thank You for Joining Team Ahab")
team_choice = True
elif team_choice == "2":
teamS["Team "+ team_choice]["Teeam Ishmael"].append(team_player)
print(teamS["Team 2"])
print("\nThank You for Joining Team Miller\n")
team_choice = False
elif team_choice == "3":
menu()
team_choice = True
else:
print("Enter a value between 1-3")
team_choice = False
My ideal output would be for it stop causing infinite while loops from different defs in my code. I'm a beginner so please execuse me
Old:
Well... True will never be one of your menuchoice_option, they are 1,2,3.
Make menuchoice="1" (instead of True), for example, if the user select "1".
Edit:
Try to simplify your code: ideally, data should be atomic, and code should work around the data to extract and act as best/smart as possible. And use a better indentation (helps seeing the blocks).
Something like the following would be much, much better to maintain/develop:
def menu():
options = {
1: "Join the Event as a Team",
2: "Join the Event by Yourself",
3: "Score Screen"
}
funcs = {
1: team_menu,
2: individual,
3: scorescreen
}
print("\n Main Menu \n")
for k,v in options.items():
print(f"{k}) {v}")
choice = None
while choice not in options:
# notice that if a value invalid for "int()" casting,
# the code will blow. Wrap this with try/except to avoid it.
choice = int(input("Please enter your choice here:"))
# By now, you know a valid option was chosen.
# Let's use to select the corresponding function from "funcs" dict
funcs[choice]()
I did not test it. But looks like working.
How about using some recursion for the menu, I share my idea:
options = """
Main Menu
1) Join the Event as a Team
2) Join the Event by Yourself
3) Score Screen
4) Exit
>>> """
def menu(menuchoice):
if menuchoice == "1":
team_menu()
elif menuchoice == "2":
individual()
elif menuchoice == "3":
#scorescreen()
pass
elif menuchoice == "4":
exit()
else:
print("Please enter a value between 1-5")
decision = str(input(">>> "))
menu(decision)
if __name__ == "__main__":
decision = str(input(options))
menu(decision)
I hope I give you an idea.
How can I return from a sub menu to a main menu?
Also I want to keep the data generated in the submenu.
Main menu:
1. Load data
2. Filter data
3. Display statistics
4. Generate plots
5. Quit
On option 2 I have a submenu:
1. S. enterica
2. B. cereus
3. Listeria
4. B. thermosphacta
5. Quit
def mainMenu():
menuItems = np.array(["Load data", "Filter data", "Display statistics", "Generate plots", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria", "B. thermosphacta", "Quit"])
while True:
choice = displayMenu(menuItems)
if choice == 1:
data = data[data[:,2] == 1] # 1 - S. enterica
elif choice == 2:
data = data[data[:,2] == 2] # 2 - B. cereus
elif choice == 3:
data = data[data[:,2] == 3] # 3 - Listeria
elif choice == 4:
data = data[data[:,2] == 4] # 4 - B. thermosphacta
elif choice == 5:
return data
continue
if choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
I implemented the break statement in the submenu and placed the menuItems inside the loops. This worked and data created in the submenu (subchoice) can be used in the mainMenu options 3 & 4.
import numpy as np
from displayMenu import *
from dataLoad import *
from dataStatistics import *
from dataPlot import *
from bFilter import *
def mainMenu():
while True:
menuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
choice = displayMenu(menuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
menuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta", "Back to main menu"])
subchoice = displayMenu(menuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
if subchoice == 5:
break
continue
elif choice == 3:
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
Replace your code with this:
def mainMenu():
mainMenuItems = np.array(["Load data", "Filter data", "Display statistics",
"Generate plots", "Quit"])
subMenuItems = np.array(["S. enterica", "B. cereus", "Listeria",
"B. thermosphacta"])
while True:
choice = displayMenu(mainMenuItems)
if choice == 1:
filename = input("Please enter filename: ")
data = dataLoad(filename)
elif choice == 2:
while True:
subchoice = displayMenu(subMenuItems)
if subchoice in (1, 2, 3, 4):
data = data[data[:,2] == subchoice]
break
# The answer is not a correct one
continue
elif choice == 3: # instead of if
statistic = input("Please enter statistic: ")
print (dataStatistics(data, statistic))
elif choice == 4:
dataPlot(data)
elif choice == 5:
break
You donĀ“t need a "Quit" option in your submenu - you want to repeat the nested loop (the submenu) only in the case of wrong answer (other as 1, 2, 3 or 4).
No action is needed to save the contents of your data variable as all action you perform are inside of your mainMenu() function. But if you need it outside of your function, use the return data statement as the very last in your function, outside of any loop.
I'm wondering if this is the right approach to looping back to the main menu in python. After selecting a choice and completing a task, the script needs to return back to the main menu instead of exiting.
#!/usr/bin/python
def mainmenu():
print ('1. Scan')
print ('2. Ping')
print ('3. Exit')
print
choice = int(raw_input('> Enter your choice: '))
if choice == 1:
print ('Starting Scan\n')
mainmenu()
elif choice == 2:
print ('Starting Ping\n')
mainmenu()
elif choice == 3:
print ('Exiting\n')
exit(0)
mainmenu()
This kind of works, but don't think it's the right way.
I would suggest putting the whole function in a while loop to repeat the process.
#!/usr/bin/python
def mainmenu():
while(True):
print ('1. Scan')
print ('2. Ping')
print ('3. Exit')
print
choice = int(input('> Enter your choice: '))
if choice == 1:
print ('Starting Scan\n')
elif choice == 2:
print ('Starting Ping\n')
elif choice == 3:
print ('Exiting\n')
exit(0)
mainmenu()
Using recursion is not recommended for such programs.
New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])