Name error when name is defined? For class project - python

Thank you for taking time to read this. I have a project due for my Programming class by Friday. The project is basically analyzing the most popular songs around the world. The user will input W is they want to see the most popular genre worldwide and how many streams it has. My program consists of two python files, one that contains the top 10 song list, and the other where the user will input their options.
Here is my file for my top10songs:
def Mostpopularw(Pop):
Pop =='Pop with 10,882,755,219 streams worldwide'
return Pop
and the file for where the user will put input
if choice=='W':
print(top10songs.Mostpopularw(Pop))
the code runs fine but when I try to enter 'W; it prints out
NameError: name 'Pop' is not defined
but I dont understand how pop is not defined? Can anyone help me?
Thanks!

It is not very clear what you want your Mostpopularw function to do, so its hard for us to help you make it do that thing. The current code doesn't make much sense, as you're comparing a Pop argument with a constant string, and then throwing away the result of the comparison before returning the same Pop value.
It may be that you just want the function to return the string, in which case it shouldn't be an argument:
def Mostpopularw():
Pop = 'Pop with 10,882,755,219 streams worldwide' # note, one = sign here!
return Pop
Now the calling code doesn't need to pass in an argument for Pop, which was the error you were having (you were passing in something that didn't exist).

Related

Bracket not showing as closed in Python 3

I'm just starting to learn Python 3.9 as my first language. I have been fighting with this error for a while now, and I can't figure out what the issue is.
Here's what I'm working on:
def eval_express(eqstring[0], eqstring[1], eqstring[2]):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
I'm receiving an error that the "(" after eval_express is not closed, but as far as I can tell it is. At first, I thought it was just a glitch, but despite numerous attempts to rewrite it, increase/decrease the number of arguments, etc. it persisted. The error cropped up after I modified the arguments from variables to list items, but I don't see why that would affect it. Can anyone provide some clarification on what the program's getting hung up on?
Thank you for your help!
You are using square brackets inside the function parameters, which is not valid. Valid code would be:
def eval_express(eqstring0, eqstring1, eqstring2):
eqstring0, eqstring2 = float(eqstring0), float(eqstring2)
return opdict[eqstring1](eqstring0, eqstring2)
although you should probably use more descriptive parameter names.
You can't use parameter[] notation when entering a parameter to a function. Instead just use parameter, or you will have to do something like.
def eval_express(eqstring):
eqstring[0], eqstring[2] = float(eqstring[0]), float(eqstring[2])
return opdict[eqstring[1]](eqstring[0], eqstring[2])
Now you have to pass an array as the function parameter.

Addition with One input

I am using codio and ran into a challenge that doesn't make sense to me.
It says "Your code should expect one input. All you need to do is add 12 to it and output the result".
I am new to Python and was wondering if someone could explain what this means. I can't seem to find any information anywhere else.
This is asking you to make a function which adds 12 to any number you input.
This could be done as follows:
def add_12(num):
return num+12
It's a task definition. You have to write a function which accepts one input parameter, add 12 to it, and return back to caller.
Your solution is as below:
print(N+12)

Python 3.3 - Game - Hint System

I want to make it so it prints different hints dependent on where the player is in the game. I tried it by setting the value of 'Hint' every time the player went somewhere. Obviously I came across a flaw (as I'm here). The value of Hint = 1 was first in one def and I couldn't manage to summon it when writing the Help/Hint def. My pathetic example:
def Room_Choice():
Hint = 1
(60 lines down)
def Hint():
Choice = input("What would you like?\n")
if Choice == ("Hint"):
if Room_Choice(Hint = 1):
print_normal("blah blah blah\n")
else:
print_normal("HINT-ERROR!\n")
Help_Short()
And obviously as the game developed more and more values of hint would be added.
As you can see I'm relatively new to Python and need help.
You are trying to reach a value that exists in a function scope, and you're doing it wrong (as you're here).
Imagine scopes as boxes of one-way mirrors : when you're inside one, you can see what's in the box and what's outside of the box. But you can't see what's in a box you are not in.
Here, Hint exists within the box of Room_Choice, but not in the box of H... oh wait.
You've called your function Hint too ! If you want to reach Hint in a function called Hint with no Hint defined inside the function, you'll probably get the function. Let's call the function DoHint()
So you can't see Hint from within DoHint, because it's in another box. You have to put it somewhere (over the rainboooow... sorry for that) you can see it.
You might want to put it at the module level (not within a def), or make it an object's attribute (but you'll have to know bits of Oriented Object Programming to understand that).
This is really basic programming skills, I can't really explain further without knowing what you're trying to do and showing you how I would do it, but I hope that helped.
Just one more thing on this line : if Room_Choice(Hint = 1):, here you're trying to check if the result of the Room_Choice function with a value of 1 for the Hint parameter is True. I don't know what you wanted to do, but the Room_Choice function doesn't show it can handle any parameters (you should get an error on that), and will not return a boolean value (it will implicitly return None, which is evaluated as a logical False).

Is it pointless to receive a parameter/argument and do nothing with it?

I'm learning python from a textbook. This code is for the game Tic-Tac-Toe.
The full source code for the problem:
http://pastebin.com/Tf4KQpnk
The following function confuses me:
def human_move(board, human):
""" Get human move."""
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Where will you move? (0 - 8): ", 0, NUM_SQUARES)
if move not in legal: print "\nThat square is already taken. Choose another.\n"
print "Fine..."
return move
I do not know why the function receives 'human' parameter. It appears to do nothing with it.
def human_move(board, human):
How would I know to send 'human' to this function if I were to write this game from scratch? Because I can't see why it is sent to this function if it isn't used or returned.
The answer: it depends. In your example it seems useless to me, but I haven't checked it in depth.
If you create a function to be used only from your code, it is in fact useless.
def calculate_money(bank_name, my_dog_name):
return Bank(bank_name).money
money = calculate_money('Deutsche bank', 'Ralph')
But if you are working with some kind of API/Contract, the callbacks you specify might accept arguments that are not needed for a certain implementation, but for some others, are necessary.
For instance, imagine that the following function is used in some kind of framework, and you want the framework to show a pop up when the operation is finished. It could look something like this:
def my_cool_callback(names, accounts, context):
# do something blablab
context.show_message('operation finished')
But what if you don't really need the context object in your callback? you have to speficy it anyway for the signature to match... You can't call it pointless because that parameter is used sometimes.
EDIT
Another situation in which it could be useful, would be to loop through a list of functions that have almost the same signature. In that case could be ok also to have extra arguments as "garbage placeholders". Let's say all your functions need 3 arguments in general, but one needs only 2.

Python TypeError: argument of type 'NoneType' is not iterable

So for my first big python project I'm building a text based game. It's supposed to be modular so the story and items etc. can be edited and replaced with little editing of the actual source code. Basically, the user command is stored as a string which is immediately broken into a list. The first element is an action like 'inspect' and the second element is a pseudo-argument for that action like 'location' or 'item'. After the command is interpreted, it goes to the execution module called 'item_or_loc' It's here that I get the error. Can anyone help? I'll provide more info or the entire source code if it'll help.
Command module:
def item_or_loc(iolo):
if iolo in items.items_f():
print (items.iolo(1))
elif iolo in locations.locations_f():
print (locations.iolo(1))
else:
print ('Command not recognized, try again.')
def location(loco):
plo_l = PlayerClass #(player location object_location)
if loco == 'location':
plo_l.player_loc(0)
def abort(abo):
sys.exit()
def inventory(invo):
pio_i = PlayerClass #(player inventory object_inventory)
if invo == 'inventory':
pio_i.player_inv(0)
Items module:
patient_gown=('Patient gown', 'A light blue patient\'s gown.')
wrench=('Wrench','')
stick=('Stick','')
prybar=('Prybar','')
screwdriver=('Screwdriver','')
scalpel=('Scalpel','')
broken_tile=('Broken tile','')
hatchet=('Hatchet','')
janitor_suit=('Janitor suit','')
Locations module: Basically the same as the Items module
Player module:
import items
import locations
class PlayerClass:
def player_inv(inv_index):
pinventory = [items.patient_gown[inv_index]]
print (pinventory)
def player_loc(loc_index):
ploc = [locations.cell[loc_index]]
print (ploc)
You don't return anything from items.items_f. You need to return a container or sequence. I would advise a different approach from the below, but it's a start, at least.
def items_f():
patient_gown=('Patient gown','A light blue patient\'s gown.')
wrench=('','')
stick=('','')
crowbar=('','')
screwdriver=('','')
scalpel=('','')
broken_tile=('','')
hatchet=('','')
janitor_suit=('','')
return (patient_gown, wrench, stick, crowbar,
screwdriver, scalpel, broken_tile, hatchet, janitor_suit)
To explain, items_f is not a container itself, but is rather a function (or more precisely, a method, which you can think of simply as a function "attached" to an object). Functions don't have to return anything, but then when you call them, the value that results from the call is simply None.
Now, when you do a test like if x in y:, y has to be a sequence or container type; and since you're testing the result of the function items_f, and since that function returns None as you've defined it above, the test throws an error.
The best way to handle this situation really depends on the larger structure of the program. A first step in the right direction might be something like this:
def items_f():
return (('Patient gown', 'A light blue patient\'s gown.'),
('Wrench', 'A crescent wrench.'),
('Stick', '...'))
But that's probably not the best solution either. My suggestion based on what you've added above (which, by the way, is now missing the items_f function) would be to use a data structure of some kind that holds items. A simple approach would be a dictionary:
items = {'patient_gown':('Patient gown', 'A light blue patient\'s gown.'),
'wrench':('Wrench', '...'),
...
}
This creates a dictionary that contains all possible items. Now when you want a particular item, you can get it like so:
item = items['patient_gown']
This way you don't need a function at all; you can just access the whole dictionary directly.

Categories