I'm trying to write a looping function that prompts the user to enter a key from the first function and if it is is a key then it prints its value. If the word entered is not in the dictionary it returns "No entry".
What I have so far.
def read_ticker():
c = {}
with open('tickers.csv') as f:
for line in f:
items = [item.strip('"').strip() for item in line.split(",")]
c[items[0]] = items[1:]
print(c)
read_ticker()
d = read_ticker()
def ticker():
x = input('Ticker: ')
if x in d:
return x[c]
else:
return 'No entry'
ticker()
How can I return the value of the key entered in the second function?
You never return your dictionary in read_ticker, and it's unclear why you're calling the function twice.
Where print(c) is put return c.
And I think you want to index the dict instead of indexing the input.
Also, what is c that you're indexing with? This is undefined. I'm assuming this is meant to be the dictionary as defined in read_ticker. In which case you want d[x].
The dictionary c isn't global, although you could define it to be, so you can't access it in your other function by c (ignoring that the indexing is backwards even if possible). Instead, since the dictionary is local to the function read_ticker and modified there we return the dictionary and store it in the variable d.
Your read_ticker() function should return c:
def read_ticker():
c = {}
with open('tickers.csv') as f:
for line in f:
items = [item.strip('"').strip() for item in line.split(",")]
c[items[0]] = items[1:]
print(c)
return c
and then you can modify your ticker function as follows:
def ticker():
x = input('Ticker: ')
if x in d.keys():
return d[x]
else:
return 'No entry'
Your ticker function can use get, which allows you to give a value if the key doesn't exist, like this:
def ticker():
x = input('Ticker: ')
return d.get(x, "No entry")
Related
I'm trying to make a function to check whether a value added to a dictionary already exists.
If a value is already in the dictionary, it should print "Occupied" and not add the value to the existing key.
I have tried to get it to not append when the new input is similar, but it still adds the new input even though it is the same as the previous.
For example, if I add input_v as "Hi" --> XO = {'key': ["Hi"]}
If I were to put in "Hi" again, I then want it to say "Occupied", but as of right now it still adds to the dictionary.
XO = {'key': []}
def check_values(input_v):
value = input_v
print(XO)
if value in XO.values():
print("Occupied")
else:
XO['key'].append(value)
The issue is in the way you referenced the value of the 'key'. Use this:
XO = {'key': []}
def check_values(input_v):
value = input_v
global XO
#print(XO)
if value in XO['key']:
print("Occupied")
else:
XO['key'].append(value)
#print(XO)
d = dict()
for c in a:
if c not in d:
d[c] = 1
else:
print("Occupied")
Would this work? a is a list in this example.
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
when I swap return for print, I do not get all the same values back in my defined function.
Here is my code with print()
def seo():
sou = soup.findAll(class_ = 'rtf l-row')
for x in sou:
l = x.findAll('p')
s = x.findAll('h4')
for i in l:
lolz = i.text
print(lolz)
for j in s:
h = j.text
print(h)
Here is the exact same code with return:
def seo():
sou = soup.findAll(class_ = 'rtf l-row')
for x in sou:
l = x.findAll('p')
s = x.findAll('h4')
for i in l:
lolz = i.text
return lolz
for j in s:
h = j.text
return h
when I use return, I only get back the first line of code. Thanks!
There should be only one return statement in a function, and it should be the last statement in it.
You have two return statements inside your seo function. The function reaches the first return statement, and the rest of the code in the function never runs.
You should either break it into two different functions, or return a list or a dictionary so you can have several values returned in a single variable :)
I want to return the final value of the list which is new_list[3] but it return nothing at the end. I can get the final value of new_list[3] by using print function. I am quite confusing about the return function. Is it possible it return new_list[times] when the 2 for loop is ended?
original_list = [100,300,400,900,1500]
def filter_list(_list,times):
L = len(_list)
new_list = [list(_list) for k in range(times+1)]
for k in range (0,times):
for j in range (0,L):
if j == 0: #exclude the term [j-1] because new_list[-1] is not exist
new_list[k+1][j] = int(new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
elif j == L-1: #exclude the term [j+1] because new_list[L] is not exist
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2)
else:
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
return (new_list[times])
filter_list(original_list,3)
A function is able to "return" a value back to the scope that called it. If this variable is not stored or passed into another function, it is lost.
For instance:
def f(x):
return x + 1
f(5)
will not print anything since nothing is done with the 6 returned from the f(5) call.
To output the value returned from a function, we can pass it to the print() function:
print(f(5))
or in your case:
print(filter_list(original_list, 3))
This is what the return function does:
A return statement ends the execution of the function call and "returns" the result, i.e. the value of the expression following the return keyword, to the caller. If the return statement is without an expression, the special value None is returned.
You are returning the item but not assigning it to anything
x = filter_list(original_list,3)
print(x)
What this will do is assign whatever you return from your function call to a variable in this case x and then your variable will hold whatever you returned so now
Heres a simple model to visualize this
def something():
x = 1
return x
def something_print():
x = 1
return print(x)
a = something()
print(a)
something_print()
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 fucntion_call.py
1
1
Sometimes I get confused as to where to use the return statement. I get what it does, it's just that I don't get its placement properly.
Here's a short example of the same code.
Correct way:
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Wrong way (which I did initially):
def product_list(list_of_numbers):
c = 1
for e in list_of_numbers:
c = c * e
return c
Can someone clarify what's the difference between the two and where should the return be when using a loop in a function?
return in a function means you are leaving the function immediately and returning to the place where you call it.
So you should use return when you are 100% certain that you wanna exit the function immediately.
In your example, I think you don't want to exit the function until you get the final value of c, so you should place the return outside of the loop.
You're putting too much emphasis on the impact of return on controlling the behaviour of the for loop. Instead, return applies to the function and happens to terminate the for loop prematurely by primarily bringing an end to the function.
Instead, you can control the behaviour of the for loop independently from the function itself using break. In addition, you can have multiple return statements in a function depending on what action should be taken in response to particular criteria (as in my_func1). Consider the following:
import random
def my_func1(my_list, entry):
'''
Search a list for a specific entry. When found, terminate search
and return the list index immediately
Return False if not found
'''
print "\n Starting func1"
index = 0
for item in my_list:
if item != entry:
print "Not found yet at index: {}".format(index)
index += 1
else:
print "found item, at index {}".format(index)
print "Terminating function AND loop at same time"
return index
print "########### ENTRY NOT IN LIST. RETURN FAlSE #############"
return False
a = my_func1(['my', 'name', 'is', 'john'], 'is')
b = my_func1(['my', 'name', 'is', 'john'], 'harry')
def my_func2(my_list):
''' Iterate through a list
For first 4 items in list, double them and save result to a list that will
be returned, otherwise terminate the loop
Also, return another list of random numbers
'''
print '\n starting func2'
return_list = []
for i in range(len(my_list)):
if i < 4:
print 'Value of i is {}'.format(i)
return_list.append(my_list[i] * 2)
else:
print 'terminating for loop, but ** keep the function going **'
break
other_list = [random.randint(1, 10) for x in range(10)]
print 'Returning both lists'
return return_list, other_list
c = my_func2([x for x in range(10)])