def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = str(input("Make a choice.."))
if user_choice in valid_answer:
def check_valid(user_choice):
if user_choice == 1: #Error section V
return("You started the game.")
else:
user_choice != 1
return("Credits to ____, created by ____")
check_valid(user_choice) #Error Section ^
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Okay, so the error should be labeled. That specific if/else statment shows up as "None" and I have tried every method to fix it. One method worked for the if/else statement on the outside, but not this one.
You're taking input as a string str(input()). Then, you're checking if user_input == 1; testing to see if it is an integer, even though it is a string. Instead, try converting to an integer using int(input()). Also, the line user_input != 1 is unnecessary, it's just the equivalent of writing True in your code. Furthermore, you define a function in your if statement, which shouldn't be there:
def main_menu():
print ("Three Doors Down Figurative Language Game")
print ("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*")
print ("NOTE: TO SELECT, TYPE NUMBER OF OPTION")
print ("")
print (" 1) Begin Game")
print ("")
print (" 2) Options")
print ("")
print ("")
menu_selection()
def menu_selection():
valid_answer = ["1","2"]
user_choice = int(input("Make a choice.."))
if user_choice in valid_answer:
if user_choice == 1:
return("You started the game.")
else:
return("Credits to ____, created by ____")
check_valid(user_choice)
else:
print("Please use an actual entry!")
menu_selection()
def enterText():
print("ENTER ANSWER!")
print (main_menu())
Related
I'm new to Python and coding in general, and ran into a bit of a bug in my code. Whenever i type in the wrong input in my Try/Except code block, the console prints "Invalid input" However, whenever i type in the correct phrase in the console, it still says "Invalid input". I looked online to try to fix this issue (notated with ##) with these lines of code, but i still get the same issue.
For example, I would type in "Mad Libs" with correct case and everything, and still get "Invalid input" from my != command. Could this be easily fixed by formatting in a different way? This happens with all 3 games.
How can this issue be addressed? Thanks in advance!
def game_selection(): ##
pass ##
while True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
game_selection() ##
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
Because you asked it to answer invalid input anyway in this code
While True: ##
try:
playerChoice = input("So, which game would you like to play?: ")
if playerChoice != "Mad Libs":
print("Invalid input")
elif playerChoice != "Guessing Game":
print("Invalid input")
elif playerChoice != "Language Maker":
print("Invalid input")
continue ##
except:
print("Invalid Input")
The thing is, this code will not work because if I enter "Mad Libs" the first if will not pass and so it will pass to all the others elif. So you can't take this approach.
What I advice you to do is to check if the playerChoice string is in an array
from time import sleep
while True:
playerChoice = input("So, which game would you like to play?:")
allowedGames = ["Mad Libs", "Guessing Game", "Language Maker"]
if playerChoice not in allowedGames:
print('Invalid input!')
else:
break
print("Got it! " + playerChoice + " it is!")
sleep(2)
if playerChoice == "Mad Libs":
print("Initializing 'Mad Libs'.")
sleep(.5)
print("Welcome to MadLibs, " + playerName + "! There are a few simple rules to the game.")
print("All you have to do is enter in a phrase or word that is requested of you.")
playerReady = input("Ready to begin? Y/N")
my program confuse between integer value and string
import random
def test():
num=random.randrange(100,1000,45)
while True:
ans=run(num)
print ans
ss=raw_input("if you want to exit press t: ")
if ss=='t':
break
def run(userinput2):
first = int(userinput2/20)
print "i will send it in %s big pack"%str(first)
userinput2=userinput2%20
second =int(userinput2/10)
print "i will send it in %s med pack"%str(second)
third =userinput2%10
print "i will send it in %s med pack"%str(third)
def main():
print "the began of pro"
print "#"*20
userinput=raw_input("test or run: ")
if userinput.lower()=='test':
test()
else:
while True:
userinput2=int(raw_input("press t to exit or chose a number:"))
if userinput2 =='t':
break
else:
answer=run(userinput2)
if __name__ == "__main__":
main()
this piece of code i has error in it
userinput2=int(raw_input("press t to exit or chose a number:"))
if userinput2 =='t':
if i change it to string i had it not accept string and if make it string it not accept integers
I think that this covers the cases you need:
while True:
userinput2=raw_input("press t to exit or chose a number:")
if userinput2 =='t':
break
try:
userinput2 = int(userinput2)
except ValueError:
print('That was neither a number nor a "t". Try again.')
continue
answer=run(userinput2)
I want to know how I can make this code without global variables.
I have tried myself but it seems like it involves return, but then It won't go back to the "menu" (main_list). The point of this code is to always return to the menu except when pressing "3" (exit program).
Sorry for the big (and bad) code, I appreciate all the help I can get.
import sys
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = raw_input()
print "Choose alternative: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
sys.exit()
else:
print "Error: Not a valid choice \n", main_list()
else:
print "Error: Not a valid choice \n", main_list()
def insert():
ins = raw_input("Word to insert: ")
if ins not in word:
word.append (ins)
else:
print "Error: Word already exist \n", main_list()
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
if up not in word:
print "Error: Word not found \n", main_list()
i = 0
while up != word[i]:
i += 1
if up == word[i]:
print "Description of word: ", desc[i]
main_list()
As Xeno said, you need a while loop to continually loop over the input. For your case, I would suggest a do-while loop, but Python does not have a built-in do-while, so you will need to emulate one, possibly something like this:
while True:
# do stuff
if condition:
break
To get rid of the global variables, you will need to pass variables into your methods and return out of them.
def insert(word, desc):
# do stuff
Now, I noticed you call main_list() at the end of insert() and look(). Do not do this. You do not need a new instance every time, you need to return back to the current instance. So, set up something like this:
def main_list():
# do stuff
while True:
# do more stuff
if condition:
break
# do more stuff
def insert():
# do stuff - return any new value; otherwise, just let it auto-return
def look():
# do stuff - return any new value; otherwise, just let it auto-return
It looks like you should use a while loop in your main function, so that it will only exit when you want it to:
So something like this:
while choice != 3:
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
sys.exit()
else:
print "Error: Not a valid choice \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit Program"
choice = int(raw_input("choose alternative")
Edit: As Prune so nicely stated below, I did not give any reasoning for my answer, so here goes:
The reason your code wasn't going back to the loop you wanted to, is that you are using an if-statement to run your loop. A while loop will allow you to repeat the desired process until you need to break. And if you want a reason not to use the main_list() function called from your other functions, look at Hosch250's answer
First of all, clean up that main loop as the previous "answer" suggests: delete the exit clause and just leave the while loop when you're done.
Second, pass word and desc in the parameter list. Add them to the "def" lines in your functions.
Third, remove the calls to main_list from your print statements; you'll return to the main program when you run off the bottom of the function.
Does this get you moving?
word = []
desc = []
menu = \
"\nMenu for list \n" \
"1: Insert\n" \
"2: Lookup\n" \
"3: Exit program"
choice = raw_input(menu)
while choice != 3:
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert(word, desc)
elif choice == 2:
look(word, desc)
else:
print "Error: Not a valid choice \n", main_list()
else:
print "Error: Not a valid choice \n", main_list()
Probably the simplest thing to do with your existing code would be to restructure it something like this, which makes main_list() drive the whole process by adding a while loop to it, and have it just pass the shared variables to each of the other functions as arguments.
def main_list():
word = []
desc = []
print "\nMenu for list"
print " 1: Insert"
print " 2: Lookup"
print " 3: Exit program"
while True:
choice = raw_input()
print "Alternative chosen: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
insert(word, desc)
elif choice == 2:
look(word, desc)
elif choice == 3:
break
else:
print "Error: Not a valid choice"
else:
print "Error: Not a valid choice"
def insert(word, desc):
ins = raw_input("Word to insert: ")
if ins not in word:
word.append(ins)
else:
print "Error: Word already exist"
desc.append(raw_input("Description of word: "))
def look(word, desc):
up = raw_input("Word to lookup: ")
if up not in word:
print "Error: Word not found"
i = 0
while up != word[i]:
i += 1
if up == word[i]:
print "Description of word: ", desc[i]
main_list()
Encapsulate it in a class. This way the word list can be held within the class instance. It's not global and you don't need to pass it around.
class main_list(object):
def __init__(self):
self.words = {}
def run(self):
while(True):
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = raw_input()
print "Chose alternative: ", choice
if choice.isdigit():
choice = int(choice)
if choice == 1:
self.insert()
elif choice == 2:
self.look()
elif choice == 3:
break
else:
print "Error: Not a valid choice"
else:
print "Error: Not a valid choice"
def insert(self):
ins = raw_input("Word to insert: ").lower()
if ins not in self.words:
desc = raw_input("Enter description of word: ")
self.words[ins] = desc
else:
print "Error: Word already exist"
def look(self):
up = raw_input("Word to lookup: ").lower()
if up in self.words:
print "description of `%s` is `%s`" % (up, self.words[up])
else:
print "Error: Word %s not found" % up
ml = main_list()
ml.run()
Note that I changed to code to use a dictionary. This will avoid needing two separate lists to hold word and description and give faster look ups.
from sys import exit
def start():
print "You woke up in a dungeon"
print "There is three weapon in front of you"
print "A sword, a staff and dagger"
print "Which one do you choose"
choice = raw_input("")
if choice == "dagger":
print "A rogue huh?"
elif choice == "staff":
print "A wizard how interesting..."
elif choice == "sword":
print "A warrior."
else:
print "..."
dungeon_path()
def dungeon_path():
if choice == "dagger":
print "Which way you choose rogue"
start()
I wanna print the last line if I choosed dagger in first function but I can't seem to get it work I tried to give choice a value and then used "if" but it didn't work that way either so what do I do...
You could pass the choice variable as an argument to the dungeon_path function:
...
print "..."
dungeon_path(choice)
def dungeon_path(choice):
if choice == "dagger":
print "Which way you choose rogue"
I have this code, but I'm not sure how to make it loop, so that after you finish encoding or decoding it brings the menu back up. It's working well right now, just no idea how to loop it.
import string
key = "qetuoadgjlxvnw ryipsfhkzcbm"
abc = "abcdefghijklmnopqrstuvwxyz "
abc_key = string.maketrans(abc, key)
key_abc = string.maketrans(key, abc)
def encode():
"""Encodes input text"""
text = raw_input ("Please enter text to be encoded: ")
text_lower = string.lower(text)
text_lower;
print text_lower.translate(abc_key);
def decode():
"""decyphers code"""
code = raw_input ("Please enter code to be decyphered: ")
code_lower = string.lower(code)
code_lower;
print code_lower.translate(key_abc);
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
any help is appreciated!
Wrap it in a while statement. Something like this:
# Welcome message
print "Welcome to Jake's Cryptography program!"
# Print menu
while True:
print "SECRET DECODER MENU"
print "0) Quit"
print "1) Encode"
print "2) Decode"
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
break
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."
Notice the break statement!
The above will print the menu each time. If you just want to print the prompt, move the while True: line down after the menu (but before the raw_input line), and then fix your indentation.
# Welcome message here
option = -1
while option != 0:
# Print menu
# Raw input for the next option
# Processing of the options
option = 13
while (int(option) > 0):
option = raw_input ("What do you want to do?")
if option == "0":
print "Thank you for during secret spy stuff with me!"
print "and good night"
elif option == "1":
encode()
elif option == "2":
decode()
else:
print "Sorry, that is not an option."