How to end a definition of a function? - python

I have am trying to define a function but I don't know how to end it; it's causing my next function to be in the first function's body. Here's a chunk of the code:
def save(name):
if x['fname'] == 'ply.json':
save1(name)
else: write_data({'fname':'ply.json', 'name':name}, 'ply.json')
def incrace():
race=raw_input()
if race.lower() == "avian":
print "Great %s! So you would like to be an" % (name),
print race.lower(),
print "?"
elif race.lower() == "apex":
print "Great %s! So you would like to be an" % (name),
print race.lower(),
print "?"
elif race.lower() == "human":
print "Great %s! So you would like to be a" % (name),
print race.lower(),
print "?"
elif race.lower() == "floran":
print "Great %s! So you would like to be a" % (name),
print race.lower(),
print "?"
elif race.lower() == "glitch":
print "Great %s! So you would like to be a" % (name),
print race.lower(),
print "?"
elif race.lower() == "hylotl":
print "Great %s! So you would like to be a" % (name),
print race.lower(),
print "?"
else:
print "Sorry, what was that? You're what race?"
incrace()
Here's where I'm having issues:
>>>def save(name):
... if x['fname'] == 'ply.json':
... save1(name)
... else:
... write_data({'fname':'ply.json', 'name':name}, 'ply.json')
...
...def incrace():
File "<stdin>", line 6
def incrace()
^
SyntaxError: invalid syntax
I've been searching for a while but I've no idea how to end the function. I've had the problem previously but how I fixed it I've no idea to either. Thanks in advance.

If you're working in IDLE or the Python shell, hit Enter twice to get back to the >>> prompt, then begin your next function definition.
The only time you wouldn't do this is if you were working on a class definition, in that case you'd leave a single blank line between function defs.

I think you should use Vim editor and run with command..
In my view, I'm confidence with Vim to avoid such kind of errors

Related

Adding more than one line per case in a switch-case statement (python)

I'm new to programming and trying to understand how to use a switch-case statement in python. My problem is a syntax error that occurs when I try to use a statement that has more than one line per case. Is this possible? What am I missing? If it isn't possible, how is a switch-case statement useful?
This is the code I'm using to test this
drop = random.randint(1,3)
inventory = []
def randomDrop(i):
switcher ={
1:
"you got x"
inventory.append(x) #syntax error on this line
2:
"you got y",
inventory.append(y)
3:
"you got z",
inventory.append(z)
}
return switcher.get(i,"you got nothing")
randomDrop(drop)
Python doesn't support support switch case. The thing which you are using is dictionary. It is a key,value data structure.
Syntax of dict: {key1:value1, key2:value2}
but in place of value you are using multiple statement that's why the syntax error.
drop = random.randint(1,3)
inventory = []
def randomDrop(i):
switcher ={
1:
"you got x"
inventory.append(x) #multiple statement instead of value or reference
2:
"you got y",
inventory.append(y) #multiple statement instead of value or reference
3:
"you got z",
inventory.append(z) #multiple statement instead of value or reference
}
return switcher.get(i,"you got nothing")
randomDrop(drop)
Use if-else instead.
inventory = []
def randomDrop(i):
if i == 1:
inventory.append(x)
return 'you got x'
elif i == 2:
inventory.append(y)
return 'you got y'
elif i == 3:
inventory.append(z)
return 'you got z'
else:
return 'you got nothing'
drop = random.randint(1,3)
randomDrop(drop)
See:
https://docs.python.org/3/tutorial/controlflow.html
I believe you are trying to do this. Let me know if it helps.
inventory = []
def randomDrop(i):
if i == 1:
inventory.append(x)
print('you got x')
elif i == 2:
inventory.append(y)
print('you got y')
elif i == 3:
inventory.append(z)
print('you got z')
else:
print('you got nothing')
drop = random.randint(1,3)
randomDrop(drop)
Python doesn't support switch case. You will have to use if-elif-else insetad of switch case.
For a much more palatable and maintainable structure, you can use a helper function for the switch:
def switch(v): yield lambda *c: v in c
This will let you write the code in a C-like style:
for case in switch(i):
if case(1):
inventory.append(x)
return "you got x"
if case(2):
inventory.append(y)
return "you got y"
if case(3):
inventory.append(z)
return "you got z"
else:
return "you got nothing"

Python program does not behave as intended

I'm writing my first short programs with Python. This program should stop after the third wrong guess. The program works as expected with the first question, and stops itself after three wrong guesses.
However, I cannot understand why, with the second question, after the third wrong guess, the first question is repeated.
easy_text = '''Hello __1__!' In __2__ this is particularly easy; all you
have to do is type in: __3__ "Hello __1__!" Of course, that isn't a very
useful thing to do. However, it is an example of how to output to the user
using the __3__ command, and produces a program which does something, so it
is useful in that capacity..'''
def split_string():
global easy_text_splitted
easy_text_splitted = easy_text.split(" ")
return None
def level1():
print """You will get 3 guesses per problem
The current paragraph reads as such:"""
print easy_text
return first_question(3)
def first_question(guesses):
while guesses > 0:
split_string()
first_answer = raw_input("What should be substituted in for __1__?")
if first_answer.lower() == "world":
easy_text_splitted[1] = first_answer
easy_text_splitted[19] = first_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
second_question(3)
else:
guesses -= 1
print "That's not the answer I expected. You have " +
str(guesses) + " guess(es) left"
return first_question(guesses)
def second_question(guesses):
while guesses > 0:
split_string()
second_answer = raw_input("What should be substituted in for 2?")
if second_answer.lower() == "python":
easy_text_splitted[4] = second_answer
new_easy_text = " ".join(easy_text_splitted)
print new_easy_text
else:
guesses -= 1
print "That's not the answer I expected. You have \n " +
str(guesses) + " guess(es) left"
return second_question(guesses)
def level_selection(index):
level = raw_input("Choose the desired level of difficulty: easy, \n
medium, or hard ")
if level.lower() == "easy":
return level1()
if level.lower() == "medium":
return level2
if level.lower() == "hard":
return level3
else:
print "Error"
index -= 1
if index > 0:
return level_selection(index)
return "Bye!"
print level_selection(3)
level2 = "You selected medium"
level3 = "You selected hard"
Whatever the value of guesses was in first_question when second_question was called, it is the same when it returns, so the loop continues, and repeats the first question.
Using a debugger will help you follow how this works.

code does not produce an error but runs and i know its not right

What i am trying to do is write my first program on my own. i don't want the answer but just some guidance its been two days and i haven't made any real progress. I'm a newbie so go easy on me.
Four co-workers carpool to work each day. A driver is selected randomly for the drive to work and again randomly for the drive home. Each of the drivers has a lead foot, and each has a chance of being ticketed for speeding. Driver A has a 10 percent chance of getting a ticket each time he drives, Driver B a 15 percent chance, Driver C a 20 percent chance, and Driver D a 25 percent chance. The state will immediately revoke the license of a driver after his or her third ticket, and a driver will stop driving in the carpool once his license is revoked. Since there is only one police officer on the carpool route, a maximum of one ticket will be issued per morning and a max of one per evening
import random
day_counter = 0
alan_tickets = 0
betty_tickets = 0
charles_tickets = 0
diana_tickets = 0
drivers = ["Alan", "Betty", "Charles", "Diana"]
#def head_to_work(): is the driver selection process when heading to work.
def head_to_work():
if random.choice(drivers) == "Alan":
print "Alan it's your turn."
global alan_tickets
if alan_tickets == 3:
print "i cant"
head_to_work()
else:
return alan_drives_tw()
elif random.choice(drivers) == "Betty":
print "Betty it's your turn."
global betty_tickets
if betty_tickets == 3:
print "nope"
head_to_work()
else:
return betty_drives_tw()
elif random.choice(drivers) == "Charles":
print "Charles it's your turn."
global charles_tickets
if charles_tickets == 3:
print "no way"
head_to_work()
else:
return charles_drives_tw()
elif random.choice(drivers) == "Diana":
print "Diana it's your turn."
global diana_tickets
if diana_tickets == 3:
print "sorry guys"
head_to_work()
else:
return diana_drives_tw()
else:
print "All drivers have their Licenses suspended."
print "Take the Bus."
# driver alan is heading to work he has a 10% chance of getting a ticket
def alan_drives_tw():
global alan_tickets
print "Yo i'm driving"
print "..."
print "Now driving"
print "..."
print "your getting pulled over"
if random.random <= 0.10:
print "your getting a ticket"
alan_tickets += 1
print "i got a ticket, but we have arrived at work"
head_home()
else:
print "just a warning today"
print "we have arrived at work"
head_home()
# driver betty is heading to work she has a 15% chance of getting a ticket
def betty_drives_tw():
global betty_tickets
print "Hi i'll drive"
print "..."
print "we outta here"
print "your getting pulled over"
if random.random() <= 0.15:
print "your getting a ticket"
betty_tickets += 1
print "i got a ticket but, made it to work"
head_home()
else:
print "just a warning today"
print "made it to work"
head_home()
#driver charles is heading to work he has a 20% chance of getting a ticket
def charles_drives_tw():
global charles_tickets
print "I'll take the wheel"
print "..."
print "lets roll out"
print "your getting pulled over"
if random.random() <= 0.20:
print "your getting a ticket"
charles_tickets += 1
print "i got a ticket but, made it to work"
head_home()
else:
print "just a warning today"
print "made it to work"
head_home()
#driver charles is heading to work she has a 25% chance of getting a ticket
def diana_drives_tw():
global diana_tickets
print "I got it today"
print "..."
print "whippin it"
print "your getting pulled over"
if random.random() <= 0.25:
print "its ticket time"
diana_tickets += 1
print "i got a ticket but, were here at work"
else:
print "just a warning today"
print "were here at work"
return head_home()
#def head_home(): is the driver selection process when heading home
def head_home():
if random.choice(drivers) == "Alan":
print "Alan it's your turn"
global alan_tickets
if alan_tickets == 3:
print "i cant"
return head_home()
else:
return alan_drives_h()
elif random.choice(drivers) == "Betty":
print "Betty it's your turn"
global betty_tickets
if betty_tickets == 3:
print "nope"
return head_home()
else:
return betty_drives_h()
elif random.choice(drivers) == "Charles":
print "Charles it's your turn"
global charles_tickets
if charles_tickets == 3:
print "no way"
return head_home()
else:
return charles_drives_h()
elif random.choice(drivers) == "Diana":
print "Diana it's your turn"
global diana_tickets
if diana_tickets == 3:
print "sorry guys"
return head_home()
else:
return diana_drives_h()
else:
print "Drivers are not eligible to drive"
# driver alan is heading to work he has a 10% chance of getting a ticket
def alan_drives_h():
global alan_tickets
global day_counter
print "Yo i'm driving"
print "..."
print "Now driving"
print "your getting pulled over"
if random.random <= 0.10:
print "your getting a ticket"
alan_tickets += 1
else:
print "just a warning today"
print "were home"
day_counter += 1
head_to_work()
# driver betty is heading to work she has a 15% chance of getting a ticket
def betty_drives_h():
global betty_tickets
global day_counter
print "Hi i'll drive"
print "..."
print "we outta here"
print "your getting pulled over"
if random.random() <= 0.15:
print "your getting a ticket"
betty_tickets += 1
else:
print "just a warning today"
print "made it home"
day_counter += 1
head_to_work()
# driver charles is heading to work he has a 20% chance of getting a ticket
def charles_drives_h():
global charles_tickets
global day_counter
print "I'll take the wheel"
print "..."
print "lets roll out"
print "your getting pulled over"
if random.random() <= 0.20:
print "your getting a ticket"
charles_tickets += 1
else:
print "just a warning today"
print "made it home guys"
day_counter += 1
head_to_work()
# driver diana is heading to work she has a 25% chance of getting a ticket
def diana_drives_h():
global diana_tickets
global day_counter
print "I got it today"
print "..."
print "whippin it"
print "your getting pulled over"
if random.random() <= 0.25:
print "its ticket time"
else:
print "just a warning today"
print "were home everyone"
day_counter += 1
head_to_work()
print head_to_work()
print "Alan %d tikets." % (alan_tickets)
print "Betty %d tickets." % (betty_tickets)
print "Charles %d tickets." % (charles_tickets)
print "Diana %d tickets." % (diana_tickets)
print "%d days has passed." % (day_counter)
there are several problems that i come across.
get the code to keep running till everyone has 3 tickets
sometimes it stops after 1,2,3, or 4 days max and i have no idea why
thanks in advance remember no answers just clues and guidance
When you are selecting a random item from a list, and comparing it to multiple values, you should only make a random selection once.
if random.choice(drivers) == "Alan":
...
elif random.choice(drivers) == "Betty":
This selects a random driver and compares it to 'Alan'. If it IS Alan, the if block runs correctly. If it fails, it now calls the random.choice function again, and selects a NEW random driver to compare to 'Betty'. But, that random driver could be Alan (or anyone).
You want something more like this:
driver = random.choice(drivers)
if driver == 'Alan':
...
elif driver == 'Betty':
...
Some other quick thoughts:
Print statements are a good way to debug a program - but that's virtually impossible with as much print spam as you have. Comment most of that out until the program works - and add print statements to show you what variables are at different times.
You have several typos such as random.random instead of random.random() and functions where you forget to update counters. This is due primarily to having so many very similar functions. As you keep writing programs, you're going to want to learn how to make a single function that can handle any of the four drivers for a single trip. It will be easier to program, and reduce some of the typo errors.
You have a fundamental flaw in your code. In your head_to_work function random.choice(drivers) is present in each of if elif clause that is where unpredictability lies. You should improve upon by like this.
drivers = ["Alan", "Betty", "Charles", "Diana"]
available_drivers=drivers[:]
def head_to_work():
if available_drivers:
selected_driver=random.choice(available_drivers)
else:
selected_driver= None
if selected_driver == "Alan":
print "Alan it's your turn."
global alan_tickets
if alan_tickets == 3:
available_drivers.remove("Alan")
print "i cant"
head_to_work()
else:
return alan_drives_tw()
#Similiarly for the other three.
else:
print "All drivers have their Licenses suspended."
print "Take the Bus."
What we did here is removed the unnecessary random choices. Solved the unpredictability. Also maintaining a avaliable_drivers list helps in finding the non-ticketed drivers which is the essential condition for the else clause in head_to_work function to work.Since when all drivers get ticketed random.choice will get an empty list. And this will work until all the drivers will get ticketed.

Transfer variables from one function to the next in Python

I need help, these are the errors: what am I doing wrong?
Traceback (most recent call last):
File "python", line 64, in <module>
File "python", line 6, in walmart
File "python", line 28, in shopping
File "python", line 53, in drink
File "python", line 61, in total_price
NameError: global name 'price' is not defined
My code:
def walmart():
print "Hello welcome to the store!"
answer = raw_input("What's your name?")
if len(answer) > 0:
print "okay great %s, Lets go!...." % (answer)
shopping()
else:
print "Sorry try typing something"
walmart()
def shopping():
print "Ok lets get shopping"
shop_list = {"pizza" : 10.00 , "fries" : 15.00 , "burger" : 15.00}
print "Here are a list of food avaliable..."
print shop_list
ans1 = raw_input("Please select your item...").lower()
price = shop_list[ans1]
if "pizza" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
elif "burger" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
elif "fries" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
else:
print "Please type something on the list..."
shopping()
return price
def drink(price):
print "Okay let's pick you a drink"
drink_list = {"water" : 1 , "soda" : 2 , "tea" : 3}
print "Here is a list of drinks..."
print drink_list
ans2 = raw_input("Please type your choice here...").lower()
price_drink = drink_list[ans2]
if "water" in ans2:
print "Great healthy choice!"
total_price(price_drink)
elif "soda" in ans2:
print "Not that heaalthy but whatever floats your boat!"
total_price(price_drink)
elif "tea" in ans2:
print "OOOOO Tea great choice "
total_price(price_drink)
else:
print " Try again!"
drink(price)
return price_drink
def total_price(price_drink):
totalprice = drink(price) + shopping()
print "Thanks for shopping....\nHere is your total price..."
print totalprice
walmart()
The problem is your variable "price" is local variable and exist only inside the function, therefore in function total_price, variable "price" does not exist. You could fix by making variable "price" a global variable by defining it outside of functions.
# Before functions
price = 0
# your functions go here
def ......
You don't transfer variables from one function to another. If you want to use a variable in multiple function what you can do is define that variable globally and then use it in different functions
global_var = 10
def func1():
global global_var
#rest of the function
def func1():
global global_var
#rest of the function
UPDATE I was thinking about the comment below and I thought I should share this with you. Although in your case global variable seems like a good choice but keep in mind that using globals are not considered as good practice. So I would recommend that you use parameter passing instead. I would recommend you go through this http://www.learncpp.com/cpp-tutorial/4-2a-why-global-variables-are-evil/

How to have a versatile function call that can call different functions in Python?

I'm trying to make a text-based game in Python, however, code could get out of hand pretty quickly if I can't do one thing on one line.
First, the source code:
from sys import exit
prompt = "> "
inventory = []
def menu():
while True:
print "Enter \"start game\" to start playing."
print "Enter \"password\" to skip to the level you want."
print "Enter \"exit\" to exit the game."
choice = raw_input(prompt)
if choice == "start game":
shell()
elif choice == "password":
password()
elif choice == "exit":
exit(0)
else:
print "Input invalid. Try again."
def password():
print "Enter a password."
password = raw_input(prompt)
if password == "go back":
print "Going to menu..."
else:
print "Wrong password. You are trying to cheat by (pointlessly) guess passwords."
dead("cheating")
def shell(location="default", item ="nothing"):
if location == "default" and item == "nothing":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
else:
print "Error: Closing game."
def location():
print "Nothing to see here."
# Placeholder location so the script won't spout errors.
def dead(reason):
print "You died of %s." % reason
exit(0)
print "Welcome."
menu()
First, an explanation on how my game basically works.
The game has a 'shell' (where input is done) which receives information from and sends information to the different 'rooms' in the game, and it stores the inventory. It can receive two arguments, the location and an eventual item to be added to the inventory. However, line 40-42 (the first elif block in 'shell') and line 43-45 (the last elif block in 'shell') are supposed to go back to whatever location the location was (line 42 and 45, to be exact). I've tried "%s() % location" but that doesn't work, it seems to only work when printing things or something.
Is there any way to do this? If not, even writing an engine for this game would be a nightmare. Or I'd have to make an entirely different engine, which I think would be a way better approach in such a case.
Sorry if I made any mistakes, first question/post ever.
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
I guess you want to call a function having its name. For that you need a reference to the module or class inside which it was defined:
module = some_module # where the function is defined
function = getattr(module, location) # get the reference to the function
function() # call the function
If the function is defined in the current module:
function = globals()[location]
function() # call the function
If I correctly understand what you want is something like this : player will enter a location name and you want to call the related method. "%s"()%location will not work, a string (that is what is "%s" is not callable).
Let's try an OOP way :
class Maze:
def __init__(self):
# do what you need to initialize your maze
def bathroom(self):
#go to the bathroom
def kitchen(self):
# go to the kitchen
def shell(self, location="", item=""):
if location == "" and item == "":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location and item:
print "You picked up %s." % item
inventory.append(item)
getattr(self, location)()
elif location and item == "":
print "You enter the room."
getattr(self, location)()
else:
print "Error: Closing game."
maze = Maze()
while True: # or whatever you want as stop condition
location = raw_input("enter your location :")
item = raw_input("enter your location :")
maze.shell(location=location, item=item)
I think you can use the getattr() method.
Example : You want to call method "helloword()" from module "test", you would then do :
methodYouWantToCall = getattr(test, "helloworld")
caller = methodYouWantToCall()
Hope it gives you a clue.

Categories