def firstone():
x= 1
print(x)
def firsttwo():
y=1
print(y)
**D={firstone,firsttwo}** ***#Problem is here***
What can be done to run the last line properly? Any ideas?
You should return a value from your functions, if you just print(), their return would be None. If your goal is to create a dict when the output of firstone() is the key and the output of firsttwo() is the value:
Code:
def firstone():
return 1
def firsttwo():
return 1
d = {firstone(): firsttwo()}
Output:
{1: 1}
First you need to make sure your functions actually return a value. Change it from printing to returning. Then call those function in the dictionary (notice the parentheses around the function name?).
def firstone():
x= 1
return x
def firsttwo():
y=1
return y
d = {"firstone":firstone(),"firsttwo":firsttwo()}
Related
I have small a python script looking something like this:
def number1():
x = 1
open_numbers = []
open_numbers.append(x)
return open_numbers
def myfunction(open_numbers):
y = 1
open_numbers.append(y)
I would like to call the myfunction in the the end of the script. Using
myfunction()
But it keeps telling me missing 1 required positional argument: 'open_numbers'
Tried passing the argument and got name 'open_numbers' is not defined
I plan to add more functions later and run them the same way
function(arg)
function2(arg)
function3(arg)
Solution
First of all, your code was not properly indented. I have corrected that.
The function myfunction takes in a list (open_numbers) as input and should return it as well.
I have passed in the output of number1() as the input to myfunction(). This should create a list: [1, 1]. And that's what it did.
def number1():
x = 1
open_numbers = []
open_numbers.append(x)
return open_numbers
def myfunction(open_numbers):
y = 1
open_numbers.append(y)
return open_numbers
myfunction(number1())
Output:
[1, 1]
you need to pass in an object to your function. you can call your function with an empty list if you want:
a = []
myfunction(a)
You might want to define default parameter, and return the updated value
def myfunction(open_numbers = []):
y = 1
open_numbers.append(y)
return open_numbers
Then you can call it with passing parameter
myfunction([1]) or without myfunction()
I have a function that most of the time should return a single value, but sometimes I need a second value returned from the function. Here I found how to return multiple values, but as most of the time I need only one of them I would like to write something like this:
def test_fun():
return 1,2
def test_call():
x = test_fun()
print x
but calling this results in
>>> test_call()
(1,2)
and when trying to return more than two, as in
def test_fun2():
return 1,2,3
def test_call2():
x,y = test_fun2()
print x,y
I get an error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my_module.py", line 47, in test_call2
x,y = test_fun2()
ValueError: too many values to unpack
I am thinking about something like in matlab, where x = test_fun() would result in x == 1 (while [x y] = test_fun() would also work as expected). Is something like that possible in python?
You can use star unpacking to gather all additional return values into a list:
x, *y = fun()
x will contain the first return value. y will be a list of the remaining values. y will be empty if there is only one return value. This particular example will only work if the function returns a tuple, even if there is only one value.
When fun always returns 1 or 2 values, you can just do
if y:
print(y[0])
else:
print('only one value')
If, on the other hand, you want to completely ignore the number of return values, do
*x = fun()
Now all the arguments will be gathered into the list. You can then print it with either
print(x)
or
print(*x)
The latter will pass each element as a separate argument, exactly as if you did
x, y, z = fun()
print(x, y, z)
The reason to use *x = fun() instead of just x = fun() is to get an error immediately when a function returns something that isn't a tuple. Think of it as an assertion to remind you to write fun properly.
Since this form of star unpacking only works in Python 3, your only option in Python 2 is to do
x = fun()
and to inspect the result manually.
There are several ways to get multiple return values.
Example 1:
def test_fun():
return 1,2
def test_call():
x, y = test_fun()
print x
print y
you will get correct output:
1
2
When you would like to ignore several return values, you can use * before a variable in python3.
Example 2:
def test_fun2():
return 1,2,3
def test_call2():
x, *y = test_fun2()
print x
print y
you will get the result:
1
(2, 3)
Here is my code I've tried:
import csv
f = open("nfl.csv", "r")
nfl = list(csv.reader(f))
patriots_wins = 0
for each in nfl:
if each[2] == "New England Patriots":
patriots_wins = patriots_wins + 1
return patriots_wins
print(patriots_wins)
It gives the below error:
SyntaxError: 'return' outside function
return is used to return a value from a function and you have not defined a function.
For instance, you might have created the following function:
def f(x):
"""Adds 5 to any integer x"""
y = x + 5
return y
and put this function in some larger context, such as:
def main():
for i in range(10):
print(f(i))
Here, when main is called, we will call the function f() 10 times and everytime we do so f() will return the answer to "What is i + 5?".
You get a return from a function.
check out this link
The return statement
return may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else None is substituted.
return leaves the current function call with the expression list (or None) as return value.
When return passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the function.
So I am new to coding and this is my first question so I apologise if the formatting is incorrect.
I am trying to figure out how to combine the (get_x_start) and the (get_x_end) functions {where x is the unique name given to the pair of functions} such that there is one function for each x that returns (field) and (end). I tried just using a list ie:
return (field,end)
But then when I tried I didn't know how to use those as indivual perameters within (main()) such that the function (fetch_data) could use both of the returned parameters from a single x function.
My code follows. If anything in it is unclear please let me know and I will try and clarify. Thanks.
def get_data (url):
response = url
return str(response.read())
def fetch_data (field,data,end):
sen = data[data.find(field)+len(field)+3:data.find(end)-3]
return sen
def get_name_start (data):
field = "Name"
return field
def get_name_end (data):
end = "ClosingTime"
return end
def get_open_start (data):
field = "OpeningTime"
return field
def get_open_end (data):
end = "Name"
return end
def get_close_start (data):
field = "ClosingTime"
return field
def get_close_end (data):
end = "CoLocated"
return end
def main ():
import urllib.request
data = get_data (urllib.request.urlopen('http://www.findfreewifi.co.za/publicjson/locationsnear?lat=-33.9568396&lng=18.45887&topX=1'))
print (fetch_data(get_name_start(data),data,get_name_end(data)))
print (fetch_data(get_open_start(data),data,get_open_end(data)))
print (fetch_data(get_close_start(data),data,get_close_end(data)))
main ()
Here it is a function that returns a tuple
def return_ab():
return 5, 6
Here it is a function that accepts three arguments
def test(a, b, c):
print(a, b, c)
And here it is how you can call the test() function passing it the two parameters returned by return_ab() but unpacked
test(*return_ab(), 7) # => 5 6 7
The key point is the asterisk in front of return_ab(). It's a relatively new syntax that is very useful indeed...
From this post here multiple variables can be returned like this
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
From here you can then pass your variables into the new function like:
new_f(succeeded, b)
Hope this helps
I would like to return two values from a function in two separate variables.
For example:
def select_choice():
loop = 1
row = 0
while loop == 1:
print('''Choose from the following options?:
1. Row 1
2. Row 2
3. Row 3''')
row = int(input("Which row would you like to move the card from?: "))
if row == 1:
i = 2
card = list_a[-1]
elif row == 2:
i = 1
card = list_b[-1]
elif row == 3:
i = 0
card = list_c[-1]
return i
return card
And I want to be able to use these values separately. When I tried to use return i, card, it returns a tuple and this is not what I want.
You cannot return two values, but you can return a tuple or a list and unpack it after the call:
def select_choice():
...
return i, card # or [i, card]
my_i, my_card = select_choice()
On line return i, card i, card means creating a tuple. You can also use parenthesis like return (i, card), but tuples are created by comma, so parens are not mandatory. But you can use parens to make your code more readable or to split the tuple over multiple lines. The same applies to line my_i, my_card = select_choice().
If you want to return more than two values, consider using a named tuple. It will allow the caller of the function to access fields of the returned value by name, which is more readable. You can still access items of the tuple by index. For example in Schema.loads method Marshmallow framework returns a UnmarshalResult which is a namedtuple. So you can do:
data, errors = MySchema.loads(request.json())
if errors:
...
or
result = MySchema.loads(request.json())
if result.errors:
...
else:
# use `result.data`
In other cases you may return a dict from your function:
def select_choice():
...
return {'i': i, 'card': card, 'other_field': other_field, ...}
But you might want consider to return an instance of a utility class (or a Pydantic/dataclass model instance), which wraps your data:
class ChoiceData():
def __init__(self, i, card, other_field, ...):
# you can put here some validation logic
self.i = i
self.card = card
self.other_field = other_field
...
def select_choice():
...
return ChoiceData(i, card, other_field, ...)
choice_data = select_choice()
print(choice_data.i, choice_data.card)
I would like to return two values from a function in two separate variables.
What would you expect it to look like on the calling end? You can't write a = select_choice(); b = select_choice() because that would call the function twice.
Values aren't returned "in variables"; that's not how Python works. A function returns values (objects). A variable is just a name for a value in a given context. When you call a function and assign the return value somewhere, what you're doing is giving the received value a name in the calling context. The function doesn't put the value "into a variable" for you, the assignment does (never mind that the variable isn't "storage" for the value, but again, just a name).
When i tried to to use return i, card, it returns a tuple and this is not what i want.
Actually, it's exactly what you want. All you have to do is take the tuple apart again.
And i want to be able to use these values separately.
So just grab the values out of the tuple.
The easiest way to do this is by unpacking:
a, b = select_choice()
I think you what you want is a tuple. If you use return (i, card), you can get these two results by:
i, card = select_choice()
def test():
....
return r1, r2, r3, ....
>> ret_val = test()
>> print ret_val
(r1, r2, r3, ....)
now you can do everything you like with your tuple.
def test():
r1 = 1
r2 = 2
r3 = 3
return r1, r2, r3
x,y,z = test()
print x
print y
print z
> test.py
1
2
3
And this is an alternative.If you are returning as list then it is simple to get the values.
def select_choice():
...
return [i, card]
values = select_choice()
print values[0]
print values[1]
you can try this
class select_choice():
return x, y
a, b = test()
You can return more than one value using list also. Check the code below
def newFn(): #your function
result = [] #defining blank list which is to be return
r1 = 'return1' #first value
r2 = 'return2' #second value
result.append(r1) #adding first value in list
result.append(r2) #adding second value in list
return result #returning your list
ret_val1 = newFn()[1] #you can get any desired result from it
print ret_val1 #print/manipulate your your result