I don't understand why my code doesn't work.
Expected behaviour:
Read what the user is inputting
Respond with an appropriate message like "you have choose to encrypt"
The code below prompts the user for input, but none of the lines given in the if block is run, even if the user enters 1, 2, or 3.
Here's my code:
print ("Press 1 to encrypt, 2 to decrypt and 3 to exit")
raw_input()
if raw_input == "1":
print ("you have choosen to encrypt")
elif raw_input == "2":
print ("you have choosen to decrypt")
elif raw_input == "3":
print ("you have choosen to exit, goodbye!")
I assume you are using the raw_input() function from Python. You should store the user input into a variable before proceeding to the if-else statement. Adding an "else" will be nice.
print ("Press 1 to encrypt, 2 to decrypt and 3 to exit")
user_input = raw_input()
if user_input == "1":
print ("you have choosen to encrypt")
elif user_input == "2":
print ("you have choosen to decrypt")
elif user_input == "3":
print ("you have choosen to exit, goodbye!")
else:
print("Please enter 1, 2, or 3.")
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.
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())
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 am trying to do one of the exercises from learn python the hard way and am stuck on something. I created a function and in case one of the statements is fulfilled I would like to put that in another function. This is the outline of how I'm trying to do it:
def room_1():
print "Room 1"
button_push = False
while True:
next = raw_input("> ")
if next == "1":
print "You hear a click but nothing seems to happen."
button_push = True
elif next == "2":
print "You enter room 2"
room_2()
def room_2():
print "Room 2"
while True:
next =raw_input("> ")
if next == "1" and button_push:
print "You can enter Room 3"
room_3()
If button_push is fulfilled then I would like to see that in room_2. Could anyone please help me with that?
You can pass button_push as an argument to the next room:
def room_1():
print "Room 1"
button_push = False
while True:
next = raw_input("> ")
if next == "1":
print "You hear a click but nothing seems to happen."
button_push = True
elif next == "2":
print "You enter room 2"
room_2(button_push) # pass button_push as argument
def room_2(button_push): # Accept button_push as argument
print "Room 2"
while True:
next =raw_input("> ")
if next == "1" and button_push: # button_push is now visible from this scope
print "You can enter Room 3"
room_3()