Several functions without global variable - python

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.

Related

How to loop this code back to the beginning?

Could anyone help me with looping this code back to the beginning if the user inputs yes and ending the program if the user inputs no?
while True:
print ("Hello, this is a program to check if a word is a palindrome or not.")
word = input("Enter a word: ")
word = word.casefold()
revword = reversed(word)
if list(word) == list(revword):
print ("The word" ,word, "is a palindrome.")
else:
print("The word" ,word, "is not a palindrome.")
print ("Would you like to check another word?")
ans = input()
if ans == ("Yes") :
#here to return to beginning
else ans == ("No"):
print ("Goodbye")
Use continue to continue your loop and break to exit it.
if ans == ("Yes") :
continue
else ans == ("No"):
print ("Goodbye")
break
Or, you could just leave off the if ans == ("Yes") and just have this:
else ans == ("No"):
print ("Goodbye")
break
Or even better, you could change your while loop to check the ans variable instead of doing while True:
Change while True to while ans == "Yes". Before the loop, you have to define ans as "Yes" (ans = "Yes). That way, it will automatically run once, but will prompt the user to continue.
Alternatively, you could do this
ans = input()
if ans == "No":
break

Python If/Else Statement Assistance

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())

Trying to use raw_input from another function

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"

How do I get a function inside of a while loop in a function to work properly?

I have looked and looked for an answer, but I am new to python and the answers I find seem to be over my head or not quite what I need. I am trying to take my code and turn it into multiple functions to complete the simple task of receiving some grades from the user and displaying the input back to the user as they want it. Hopefully this will be more clear when you see my code.
import sys
gradeList = []
def validate_input():
try:
gradeList.append(int(grades))
except:
return False
else:
return True
def average(count, total):
ave = total / count
return ave
def exit(gradeList):
if gradeList == []:
print "You must enter at least one grade for this program to work. Good Bye."
sys.exit()
#def get_info():
while True:
grades = raw_input("Please input your grades.(or Enter once you have entered all of your grades): ")
if not grades:
break
elif validate_input() == True:
continue
else:
print "Please enter a number."
continue
def give_answers(gradeList):
while True:
print "\n",
print "Please select what you would like to do with your grades."
print "Press 1 for the Highest grade."
print "Press 2 for the Lowest grade."
print "Press 3 for the Average of the grades you entered."
print "\n",
print "Or you can press 'q' to quit."
choice = raw_input("> ")
if choice == 'q':
break
elif choice == '1':
print "\n",
print "The highest grade that you entered was %d.\n" % highest,
elif choice == '2':
print "\n",
print "The lowest grade that you entered was %d.\n" % lowest,
elif choice == '3':
print "\n",
print "Your average grade was %d.\n" % average,
else:
print "Please enter 1, 2, 3 or 'q'."
#get_info()
exit(gradeList)
gradeList.sort()
highest = gradeList[-1]
lowest = gradeList[0]
count = len(gradeList)
total = sum(gradeList)
average = average( count, total)
give_answers(gradeList)
Everything works correctly as I have pasted the code, but when I try to define get_info the nested validate_input() function stops working. It no longer populates the list so exit() catches and ends the program. The loop seems to just pass over the validate_input()function altogether because the else statement trips after each time through. My question is how do I get the validate_input() function to work properly while continuing to accept input until the user presses enter?
Pass grade to your function validate_input so it could add the grade to list like:
def validate_input(grades):

How to loop this cryptography program

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."

Categories

Resources