Python 3.3 - Game - Hint System - python

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

Related

How to create a repeating loop in python with sympy, without changing one variable in the loop

so basically I have encountered a problem where I have made my loop, but since one of the variables is defined before the actual assignment, the code stops working. the code.
Another thing is that I'm working in Spyder, and I don't know why, but if I try to code so that the program collect variables initially (which is essential for this purpose), the program encounters an internal issue. Any ideas on how to ask for user input in Spyder?
Thanks to everyone in advance
Basically, what I want this to do is to differentiate functions, and the with these derivatives create a maclaurin series. When the actual error ((r-j)/r) is smaller than the stopping variable s, I want the program to stop and display the result, but I don't know what is wrong.
The second thing I want to achieve is to get to know how to gain input from the user in the program.
So, here is, in text form, your code (sorry, plagiarism argument is not valid around here)
q = sympy.Function('q')
q = sympy.diff(f)
def main():
a = sympy.Function('a')
a = sympy.diff(q)
j = sympy.function
j = 1+(1/sympy.factorial(count))*q
r = sympy.Function('r')
r = j+(1/sympy.factorial(count+1))*a
if ((r-j)/r)>s:
count = count + 1
q = sympy.diff(a)
j = r+(1/sympy.factorial(count))*q
r = j+(1/sympy.factorial(count+1))*a
main()
else:
print(f"Answer{r}")
In the middle of an obviously very confused code, and even more confused situation with that "plagiarism" stuff (don't worry, if you have a working code at the end of your effort, there is no way it will look similar enough to your original to be detected as plagiarism because I've posted it here:D) there is actually a good question, and I remember that I while ago I had to scratch my head to understand what was happening in a similar situation.
The problem you have here, is that you can't compute sympy.diff(q) in main function, before assigning something to q in that same function later.
Because of the line q = sympy.diff(a) that you have later, q has to be a local variable (unless you say otherwise, see later). That's default behavior in python: a variable that you assign in a function is a local variable.
But because you are reading this variable before, in the previous line (the one that triggers the error) a = sympy.diff(q), then python has a problem: the local variable a doesn't exist yet.
Without the future q = sympy.diff(a), q would have been "read-only" inside main, and python would have done what you probably expect: read the global variable q.
So, your real problem is not really that line. Your real problem is the line q = sympy.diff(a).
Because even without the current error, that line would not do what you expect it to do. You probably expect it to alter q so that in the subsequent recursive call of main, q has this new value for now on. Not to create a local value q, and have the next call of main start over with the global value of q.
You have several options here.
One would be to declare q has global. Just add line global q at the beginning of your main, and q is now the global variable.
A cleaner way would be to pass q as an argument to main.
Note that you'll have probably the same problem with count. You should also either declare it as global, or, neater way, pass it to main.
Note also that this would solve only syntax errors (well, not even all. j=sympy.function is meaningless for example). But there are many other errors here. The least serious being your strange habit to create a Function and immediately delete it by overwriting it by another function or expression.

Name error when name is defined? For class project

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

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.

TypeError: 'function' object is not subscriptable. Working on text-based adventure game

I'm creating a text based adventure game as a hobby project and encountered this problem when implementing one of the possible interactions in the game world
Other functions using the move[0] thing work as shown bellow but here it just doesn't seem to want to work.
def gamehelp():
if move[0] == 'help':
showInstructions()
This is what the error refers to
def move():
move = ''
while move == '':
move = input('>')
move = move.lower().split()
if move[0] == 'go':
global currentRoom
if move[1] in rooms[currentRoom]:
if currentRoom == 'Corridor' and move[1] == 'west' and not 'key' in str(inventory):
print('This Door is Locked!')
else:
currentRoom = rooms[currentRoom][move[1]]
else:
print('You can\'t go that way!')
Here is where i have the move variable defined
while True:
showStatus()
move()
gamehelp()
itemPickup()
look()
And here i call upon the different functions, where gamehelp() and look() have just been implemented.
The output which i was expecting was for it to display the showInstructions() function when i type 'help' into the game but it comes back with this error
Traceback (most recent call last):
File "main.py", line 139, in <module>
gamehelp()
File "main.py", line 72, in gamehelp
if move[0] == 'help':
TypeError: 'function' object is not subscriptable
In your gamehelp function you have no parameters, but it's expecting move to be checked. You would need to accept, and pass move as a parameter like
gamehelp(move)
With the function changed to
def gamehelp(param):
if param[0] == 'help':
showInstructions()
This should fix that error. I will now do a few unrequested code recommendations. Feel free to ignore these if you wish, but I think you'll have problems down the line if you don't at least heed them.
Firstly, the method gamehelp() is somewhat pointless if that is the entire method. If you're calling gamehelp, you may as well call showInstructions() instead. You should be checking if you're calling gamehelp before just running the method and extend that to everything. I'm happy to help you try and sort that out if you like, but your current method will not scale and will almost certainly bring around bugs, because you will have to check every single method whenever there's a problem in your while loop.
Your move function can also be refactored quite a bit. I would also not recommend using a variable with the same name of the method, because it can get confusing when you use first class functions.
I have refactored just the move variable as an example. Explanation below:
You're not actually adding to the move variable, it's only taking the LAST thing the user input. If you do want to add to the move variable, use the += operator or the string join() method. I'm guessing this is a bug you don't know about yet or else this would look different. At any rate this does the exact same thing, except that it only takes the first thing the user input. The way you did it before also meant that the user had to enter a blank line by itself. I think In order to have it actually do anything You should also have a space after the more than sign, it'll look cleaner when the user is typing. Now you should be able to do >go west instead of >go >west >
def move():
move = input('> ').lower().split()
...
There are lots of other problems that I can foresee eventually coming to fruition in your code as well. For example, what if you want a named corridor? Then this would fail because it's just checking currentRoom, which is a string. You would be better off using a class that has a room TYPE, or even different types of classes for each room (which is probably unnecessary). You could then do currentRoom.type and have zero contention on what type of room it is. This could carry over to which ways the player can move, like having a method check whether or not west is an option and/or if they have a key, and/or if west is a door... etc.
Let's take the players inventory for example. If you're just checking whether or not they have a key, how will you handle multiple, different keys? What if there's an occurrence of key in the inventory (since it's a string), or has absolutely nothing to do with keys? The answer is to use objects and arrays. Make a player class with their inventory/statuses/etc. Then you can make their inventory an array/dict/whatever floats your boat, and finally check for them having a specific item instead of just 'key'. This would also allow you to actually use up the key (which you didn't do, but may have been on purpose) by removing it from the array/dict/whatever.
You are going to have lots of repeated code, or errors unless you use something akin to classes. Even in this short snippet I can already see problems or future problems.
TL;DR: Use OOP. Classes are your friends.
P.S. I am more than happy to help you if you like. I hope that this was helpful :>
P.P.S. Unless your goal is to make a text adventure engine, you may want to use one that's already been made.

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.

Categories