This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 5 years ago.
I am having issues with values being returned exactly as they are passed to a method despite being modified inside the method.
def test(value):
value+=1
return value
value = 0
while True:
test(value)
print(value)
This stripped-down example simply returns zero every time instead of increasing integers as one might expect. Why is this, and how can I fix it?
I am not asking how the return statement works/what is does, just why my value isn't updating.
You need to assign the return'd value back
value = test(value)
Use this :-
def test(value):
value+=1
return value
value = 0
while True:
print(test(value))
You weren't using the returned value and using the test(value) inside the print statement saves you from creating another variable.
Related
This question already has answers here:
Why doesn't list have safe "get" method like dictionary?
(13 answers)
Closed 1 year ago.
In python we have get() method in dictionary to get values safely. Any way to achieve this in list?
my_dict = {'fruit':'apple','colour':'black'}
my_dict.get('colour','None') #returns black
my_dict.get('veg','None') #returns None
my_list = ['apple','fish','blue','bottle','gold']
colour = my_list[2]
print(colour) #returns blue
value = my_list[7] #gives error. Expected: need to return default value as None.
In my case length of my_list is not constant.Values are getting populated in runtime.If i try to get the index which is not present in the my_list it should return default value as None.
How to get the default values when list is not having requested index.?
Use try-except block -
try:
value = my_list[7]
except:
print("Value doesn't exist")
In case, the try statement has an error, it switches to the except block
This question already has answers here:
Check if key exists and get the value at the same time in Python?
(3 answers)
Closed 3 years ago.
I would like to optimize this statement:
if 'key' in dictionary and dictionary['key']!=value:
Is there a way to check if a key exists in a dictionary and check the value at the same time?
Use the .get() dict method, which returns None if the key is not in the dictionary instead of throwing a KeyError exception:
d = {'a':0,'b':1}
if d.get('a')==0:
# you will enter this if-statement
if d.get('c')==0:
# you will not enter this if-statement and will not throw a KeyError
Python dict has a get() method. For example, if d is a dict, d.get(x, y) returns d[x] if it exists, otherwise it returns y. This means that your if statement can be replaced with if dictionary.get(key, value) != value.
This question already has answers here:
Return multiple values over time
(2 answers)
Closed 5 years ago.
I've written a function in python to see If i know what I'm doing but unfortunately I'm not. I thought my defined arg variable will hold a number and multiply each of the numbers which *args variable holds and print it all at a time. But, it is giving me the first result only.
This is what I've written:
def res_info(arg,*args):
for var in args:
return var*arg
print(res_info(2,70,60,50))
Having:
140
Expected:
140
120
100
I don't understand why I'm not getting all the results. Thanks for taking a look into it.
You are on the right path. The problem you had was due to your use of the return statement. Use yield instead.
>>> def res_info(arg,*args):
for var in args:
yield var*arg
>>> list(res_info(2,70,60,50))
=> [140, 120, 100]
So, what was happening was, even though your logic was correct, since there was a return statement in the loop, your loop hence was never fully executed and your program scope would come out on the first iteration of the loop itself (ie, when var = 70).
Using yield, solved the problem as it returns a Generator object after all calculations, and hence does not exit the loop like return does.
def res_info(arg,*args):
result = []
for var in args:
result.append(var*arg)
return result
print(res_info(2,70,60,50))
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 5 years ago.
I'm trying to create a function that uses a while loop to count up from one to a number given by a user. The code executes as I intend it to but returns None at the end. How do I get rid of the None? Here's the code.
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
print (printFunction(int(input())))
You can use this code to prevent none, tough its just the last line changed
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
printFunction(int(input()))
In the last line you were using
print(printFunction(int(input()))) which was getting you None after printing the results.
Instead just use printFunction(int(input())). This will not print None. You can also use a message to ask user like printFunction(int(input("Enter a number"))). Since there is noting getting returned you no need to use print.
This question already has answers here:
Assignment Condition in Python While Loop
(5 answers)
Closed 5 years ago.
I am learning python. I tried to the following code but it did not work.
How can I print inputs from a user repeatedly in python?
while ( value = input() ):
print(value)
Thank you very much.
Assignments within loops don't fly in python. Unlike other languages like C/Java, the assignment (=) is not an operator with a return value.
You will need something along the lines of:
while True:
value = input()
print(value)
while true is an infinite loop, therefore it will always take an input and print the output. value stores the value of a user input, and print prints that value after. This will always repeat.
while True:
value = input()
print(value)
Use this code
while 1:
print(input())
If you want to stop taking inputs, use a break with or without condition.