Using an argument as part of a variable - python

I have a function which takes 1 argument. The function outputs several results and assigns them to a variable for later use. I would like to change the variable names using the argument but I am unsure how to do so. What I envison is something like what I have written below, but this returns a syntax error and I am not sure where to go from here.
Thank you!
def Get_Sums_Counts(Category):
{Category}_Total_Count = len(Analyzed_Month[Analyzed_Month['age_cat'] == Category])
return {Category}_Total_Count
{Category}_Total_Sum = round(Analyzed_Month[Analyzed_Month['age_cat'] == Category].sum())
return {Category}_Total_Sum

Related

Python - Passing Functions with Arguments as Arguments in other Functions

I'm new to programming and I've been stuck on this issue and would really like some help!
One of the parameters in my function is optional, but can take on multiple default values based on another function. Both functions take in the same input (among others). When I try to assign a default using the function as illustrated below:
def func(foo):
# returns different values of some variable k based on foo
def anotherFunc(foo, bar, k=func(foo)):
# this is the same foo input as the previous function
I get the following error:
NameError: name 'foo' is not defined
The thing is, the user can call 'anotherFunc' with any value of 'k' they want, which complicates things. Is there any way to have a function with arguments in it as a parameter in another function? Or is there any way for me to set multiple default values of 'k' based on the previous function while still allowing the user to choose their own 'k' if they wanted?
Thanks!
foo at the moment of defining the function acts as placeholder for the first function argument. It has no value until the function is called, for which its value can be accessed in the function body, like so:
def another_func(foo, bar, k=None):
if k is None:
k = func(foo)
...
You would probably want to do something like:
def func(foo):
return foo
def anotherfunc(foo, bar, k=None):
if k == None:
k = func(foo)
#process whatever

Passing parameters error

I am trying to create a program and get user data then pass it on to another function, but I keep getting a NameError, even though I (appear) to be passing the parameters properly and calling the function with that parameter too.
here is an example of my code:
#Define prompt to get player name
def welcomePrompt():
print("Welcome to my beachy adventure game!")
name=(input("Before we start, you must check-in, what is your name?:"))
return name
#Define dictionary to access all player data
def dataDict(name):
name=name
print(name)
def main():
welcomePrompt()
dataDict(name)
main()
could someone please help? thanks
You don't use the name value returned from welcomePrompt(); a local variable in a function is not going to be visible in another function, so the only way to pass on the result is by returning and then storing that result:
def main():
name = welcomePrompt()
dataDict(name)
Note the name = part I added. This is a new local variable. It may have the same name as the one in welcomePrompt(), but because it is a different function, the two are independent. You can rename that variable in main() to something else and not change the function of the program:
def main():
result = welcomePrompt()
dataDict(result)

It says "TypeError: Oppnadjur() takes exactly 1 argument (0 given)" why?

so this is my function, and it doesn't work.. why?
def Oppnadjur(djurfil):
djurfil = open("djur.txt", "r")
Djur = djurfil.readlines()
Djur.sort()
djurfil.close()
Djurlista=[]
You wrote that your function should receive one parameter, djurfil. However, you clearly did not mean to do that, as you proceed to not use that parameter, overwriting it with a different value. See the Python Tutorial about how to define functions.
The error message you see means that you had called your function as you had intended, with no parameters (Opnnadjur()), but that's not how you had defined it. So Python is looking for the parameter it thinks you should be passing in.
The error would be in your calling code, not the def of the function. You need to call Oppnadjur with one parameter. The error message suggests that you are calling it with zero parameters.
You define your function with one argument (djurfil), but the argument is unused in your function so you can get rid of it.
def Oppnadjur():
djurfil = open("djur.txt", "r")
Djur = djurfil.readlines()
Djur.sort()
djurfil.close()
Djurlista=[]

Python Parameter Confusion

I'm a beginner, writing a Python Blackjack script, and got confused about whether or not a function (dealPlayer) needs a parameter. It works either way, with a parameter or without. I'm not sure if I've had a brain fart, or I've not learned something along the way. Here's the code:
import random
dealer = []
player = []
c = ""
deck = [2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,
9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,11]
def dealPlayer(deck):
cardOne = random.choice(deck)
cardTwo = random.choice(deck)
player.append(cardOne)
player.append(cardTwo)
deck.remove(cardOne)
deck.remove(cardTwo)
The question is, do I need (deck) as a parameter in the function? It works with or without (deck) as a parameter. I've gone back over different tutorials, and other's code, but I'm still confused. Thanks for any help.
The reason your code works with or without deck as a parameter is because there is a global variable named deck, so when you reference deck inside your function, the function will first look for the local variable (the parameter) and then if it doesn't find it, it will look for the global variable.
It's best to refactor your code to not use global variables at all -- define deck initially inside a function and then pass that as a result or argument to other functions as needed. If you don't want to do that, then at least make sure your argument does not shadow (have the same name as) the global variable, to avoid confusion further on. Or remove the argument entirely and use the global variable only, if that's appropriate for your program.
did i get you right that if your function is:
def dealPlayer():
the code still works? this should raise a undefined deck error. EDIT: this was wrong of course its global. And just works without it. but thats a bad practice.
def dealPlayer():
deck = []
this should raise a Index Error.
cardOne = random.choice()
This raises a TypeError.

Assign variable with variable in function

Let's say we have
def Foo(Bar=0,Song=0):
print(Bar)
print(Song)
And I want to assign any one of the two parameters in the function with the variable sing and SongVal:
Sing = Song
SongVal = 2
So that it can be run like:
Foo(Sing=SongVal)
Where Sing would assign the Song parameter to the SongVal which is 2.
The result should be printed like so:
0
2
So should I rewrite my function or is it possible to do it the way I want to? (With the code above you get an error saying Foo has no parameter Sing. Which I understand why, any way to overcome this without rewriting the function too much?
Thanks in advance!
What you're looking for is the **kwargs way of passing arbitrary keyword arguments:
kwargs = {Sing: SongVal}
foo(**kwargs)
See section 4.7 of the tutorial at www.python.org for more examples.

Categories

Resources