Python function default argument random value - python

In the following code, a random value is generated as expected:
import random
for i in range(10):
print(random.randint(0,10))
However, this does not work if I use a function:
import random
def f(val: int = random.randint(0,10)):
print(val)
for i in range(10):
f()
Why is the result of the second code snippet always the same number? The most similar question I could find is this one, but it refers to a different language (I don't master) .

The default argument expression isn't evaluated when you call the function, it's evaluated when you create the function. So you'll always get the same value no matter what you do.
The typical way around this is to use a flag value and replace it inside the body of the function:
def f(val=None):
if val is None:
val = random.randint(0,10)
print(val)

You'll want to have the default value be a specific value. To make it be dynamic like that, you'll want to default it to something else, check for that, and then change the value.
For example:
import random
def f(val=None):
if val is None:
val = random.randint(0,10)
print(val)
for i in range(10):
f()

The default param can't be changed on calling.
I can't understand why it needed.
you can do simply like this.
import random
def f():
print(random.randint(0,10))
for i in range(10):
f()

Related

How to complete this function then print it out, using Python?

I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function?
string = "Hello"
reverse = string[::-1]
print(reverse)
I tried putting it in a function but I cannot make it print Hello.
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
also tried this
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
Nothing seems to work. I'm having same problem with this as well.
total = 0
def length(words):
for i in words:
total += 1
return total
Functions without a return value
Functions that just take action or do something without returning a value (for example, print).
Functions that don't return a value can be defined like that:
def sayHello():
print "Hello!"
And can be used (called) like that:
sayHello()
And the output will be:
Hello!
Function parameters
A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example.
A function that receives a name and greets this name:
def sayHelloTo(name):
print "Hello", name
It can be called like that:
sayHelloTo("Yotam")
And the output will be:
Hello Yotam
The parameters are the function's input.
Functions with a return value
Other functions, unlike sayHello() or sayHelloTo(name) (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6).
from random import randint
def rollDice():
result = randint(1, 6)
return result
The return keyword just sets the output value of the function and exits the function. An example use of the rollDice function will be:
dice = rollDice()
print "The dice says", dice
When the function hits a return keyword, it finishes and the return value (in our case, the variable result) will be placed instead of the function call. Let's assume randint(1, 6) has produced the number 3.
Result becomes 3.
Result is returned.
Now, instead of the line:
dice = rollDice()
We can treat the line as:
dice = 3
(rollDice() was replaced with 3)
Functions with parameters and a return value
Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one.
def max(a,b):
if a > b:
return a
else:
return b
What it does is pretty clear, isn't it? If a is greater, it returns the value of it. Otherwise, returns the value of b.
It can be used like that:
print max(4, 6)
And the output will be:
6
Now, your case
What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that:
def reverse_a_string(my_text):
return my_text[::-1]
now you can do something like that:
s = raw_input("Please enter a string to be reversed\n") #input in Python3
r = reverse_a_string(s)
print r
r will contain the reversed value of s, and will be printed.
About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one.
Local variables
About your 3rd example:
def reverse_a_string(string):
string = "Hello"
reverse = string[::-1]
print(reverse)
This is something that is really worth delaying and understanding.
the variable reverse is first used inside the function. This makes it a local variable.
This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done.
This means that even if you called reverse_a_string(string), you wouln't be able to use the reverse variable outside of the function, because it would be local.
If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the global keyword, like that:
reverse = "" #This makes reverse a global variable
def reverse_a_string(string):
global reverse #Stating that we are going to use the global variable reverse
reverse = string[::-1]
# Then you can call it like that:
reverse_a_string("Hello")
print reverse
The output will be
olleH
Although it's strongly not recommended to do it in Python, or in any other language.
Once you create a function you must call it. You have created the function reverse_a_string but then you never actually call it. Think about a function as a button that does something everytime it is pushed (or in our case called). If you never push the button then although it has the potential to do something, it never will. In order for the set of instructions to happen we need to push the button (or in our case call the function). So in order for your code to work you first need to define the function then actually call it:
def reverse_a_string():
string="Hello"
reverse = string[::-1]
print reverse
reverse_a_string()
Result: 'olleH'
If you want to pass your own string in to the function so it doesn't just return 'olleH' all the time your code needs to look like such:
def reverse_a_string(stringThatWillBeReversed):
reverse = stringThatWillBeReversed[::-1]
print reverse
reverse_a_string('whateverStringYouWant')
Result: The reverse of the string you entered.
Hope that helps!
I don't know whether you are asking how to define functions in python or something else
If you want to learn python functions, go to http://www.tutorialspoint.com/python/python_functions.htm or just write python tutorial in google, you will get billions of good sites
def reverse_a_string(string):
#function definition
reverse = string[::-1]
print(reverse)
#function call
reverse_a_string("your string")
But you to define function for this, you could simply do
print( string[::-1] )
# defines the 'Reverse a String' function and its arguments
def reverse_a_string():
print(string)
reverse = string[::-1]
print(reverse)
print("Type a string") # asks the user for a string input
string = input() # assigns whatever the user input to the string variable
reverse_a_string() # simply calls the function
for functions, you have to define the function, then simply call it with the function name i.e. funtion()
In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.

what is the difference of built-in function and myfunction

If I use this
def myfunction():
print('asd')
print(myfunction)
The IDE tells me None
but if I use this
import math
print (math.cos(90))
The IDE tells me the COS90°
Why?
It's all about return value.
def myfun(x):
return x
print(myfun("hello")) will return hello.
Your function (myfunction) does not return a value, that's to say it returns None value. So, print (a built in python function) returns that value.
When functions are called they always return something they processes.
def myfunction():
print('asd')
This will print the output. Since there is nothing explicitly returned, the function by default return None
Now lets add a bit of complexity to your function:
def myfunction(text):
print(text * 2)
This will print the text it gets twice. And it works just fine. But lets say you need to store the "printed twice" text to a variable.
Try this:
def myfunction(text):
print(text * 2)
twoText = myFunction("some text foo")
print(twoText)
Output should look like this:
some text foosome text foo
None
This is happening because you are in your function first printing twice some text foo and then printing what your function returned. In this case it returned None since nothing was explicitly returned.
To fix this you just replace print with return.
def myfunction(text):
return text * 2
twoText = myFunction("some text foo")
print(twoText)
The output is correct because you print only the return of the function.
some text foosome text foo
The math function returnes data like this:
def cos(number):
# Insert super complex math calculation here
return result
If it didn't do this you would not be able to store the result in a variable, instead it would just be printed.
If a Question is general than there is no difference except built-in function is one that is properly tested and approved by author's command; You can contribute too if You write something good and useful - don't shy offer it to community; ppl will thank You.
But if You mean exactly Your example then You have to change code to be:
def myfunction():
print('asd')
myfunction()
this is the way to call function without arguments, You could have
def myfunction(n):
print(n)
myfunction('hi')
this would print hi and so on

Using the same variables in different functions in Python

I'm trying to use the return function, I'm new to python but it is one of the things I don't seem to understand.
In my assignment I have to put each task in a function to make it easier to read and understand but for example I create a randomly generated number in a function, I then need the same generated number in a different function and I believe the only way this can be done is by returning data.
For example here I have a function generating a random number:
def generate():
import random
key = random.randint(22, 35)
print(key)
But if I need to use the variable 'key' again which holds the same random number in a different function, it won't work as it is not defined in the new function.
def generate():
import random
key = random.randint(22, 35)
print(key)
def number():
sum = key + 33
So how would I return data (if that is what you need to use) for it to work?
The usage of return indicates to your method to 'return' something back to whatever called it. So, what you want to do for example in your method is simply add a return(key):
# Keep your imports at the top of your script. Don't put them inside methods.
import random
def generate():
key = random.randint(22, 35)
print(key)
# return here
return key
When you call generate, do this:
result_of_generate = generate()
If you are looking to use it in your number method, you can actually simply do this:
def number():
key = generate()
sum = key + 33
And if you have to return the sum then, again, make use of that return in the method in similar nature to the generate method.

return variable name from outside of function, as string inside python function

So I have created a function that applies an action (in this case point wise multiplication of an array with a sinusoid, but that does not matter for my question) to an array.
Now I have created another function with which I want to create a string of python code to apply the first function multiple times later-on. The input of the second function can be either a string or an array, so that I can use the second function on its own output as well, if need be. My method of getting the variable name in a string works outside of the function.
Input :
var = np.array([[1,3],[2,4]]) # or sometimes var = 'a string'
if type(var)==str:
var_name = var
else:
var_name = [ k for k,v in locals().items() if v is var][0]
var_name
Output :
'var'
So here var is the variable (either array or string) supplied to the function, in this case an array. The if statement nicely returns me its name.
However when I use this inside my function, no matter what input I give it, it actually seems to look for var in locals(). Somehow it does not take var from the function input.
Definition :
def functionTWO(var, listoflistsofargs=None):
if type(var)==str:
var_name = var
else:
var_name = [ k for k,v in locals().items() if v is var][0]
if listoflistsofargs==None:
return var_name
command = []
for i in range(len(listoflistsofargs)):
if i==0:
command.append('functionONE(')
command.append(var_name)
command.append(',%.17f, %.17f)' % tuple(listoflistsofargs[i]))
else:
command.insert(0,'functionONE(')
command.append(',%.17f, %.17f)' % tuple(listoflistsofargs[i]))
''.join(command)
command[0] = var_name + ' + ' + command[0]
return ''.join(command)
Input :
somearray = np.array([[1,2,3],[1,2,3],[1,2,3]])
args = [[1,3],[6,5]]
command = functionTWO(somearray, args)
command
Output :
NameError: name 'var' is not defined
Wanted output :
'functionONE(functionONE(somearray, 1, 3), 6, 5)'
Why is listoflistsofargs taken from the function input and var not? I specify var in the listcomprehension in the definition of functionTWO. Normally when I use list comprehensions with function inputs it works fine. Does anybody know why this isnt the case here? Thank you in advance!
EDIT : So I guess the answer is dont. The implementation of classes by Marcin looks much cleaner and about the same order of amount of code. Too bad I couldnt get this to work inside a function. For other donts (actually other ideas) about using variable names as strings there is this question, where I got the above list comprehension for variable names.
You cannot pass a variable as a string*, and you should not do so.
If you want to pass a value between functions, the normal way is to pass it in as a parameter, and out as a return value.
If that is inconvenient, the usual solution is an object: define a class which carries both the shared variable, and methods which act on the variable.
If you need to create command objects, it is much better to do so in a structured way. For example, if you want to pass a function, and parameters, you can literally just pass the function object and the parameters in a tuple:
def foo():
return (functionONE,somearray,1,3)
command = foo()
command[0](*command[1:])
If you want to embed such commands within commands, you'll likely want to wrap that up with a class, so you can recursively evaluate the parameters. In fact, here's a little evaluator:
def evaluator(object):
def __init__(self,func=None,params=None):
self.func = func
self.params = params
def eval(self,alternativeparams=None):
if alternativeparams is not None:
params = alternativeparams
else:
params = self.params
if params is not None:
evaluatedparams = (item() if callable(item) else item for item in params)
else: evaluatedparams = None
if func is not None:
return self.func(*(evaluatedparams or ()))
else: return evaluatedparams
def __call__(self, *params):
return self.eval(params if params else None)
Although there are hacks by which you can pass references to local variables out of a function, these are not a great idea, because you end up creating your own half-baked object system which is more difficult to understand.
* This is because a variable has a name (which is a string) and a context, which maps names to strings. So, you need, at least to pass a tuple to truly pass a variable.
presenter's answer works in python 3
def get_variable_name(*variable):
return [ k for k,v in globals().items() if v is variable[0]][0]
example:
>> test = 'sample string'
>> get_variable_name(test)
'test'
>>
The only issue is it is a little messy.
The reason you get the error NameError: name 'var' is not defined when you wrap it all into a function is the following: locals().items() refers to the locally defined variables. as a matter of fact, the locally defined variables in your functions are only the variables defined inside the function and those passed as arguments to the function.
As the name says, locals().items() is local, and will consist of different variables depending on where it is called in your script.
On the contrary globals().items() consists of all the global variables, so try using it instead in your functions, it should do the trick.
For more info, look up global and local variables as well as the scope of variables in Python.

Python: Cannot Assign Function Call

I am having a problem such as:
def function (number):
for number in list:
number = number + 1
For example function(1):
for number in range(1,5):
number = number + 1
Error come back as "can't assign function call"
I would like to use that variable as a value for further calculations.
Help!
I think you have two problems. First, you are not naming your function or declaring it properly; you should do this:
def f(number):
...
Second, you are naming the function parameter number but on the next line you seem to be treating list as though it were the parameter. I think you mean to do this instead:
def f(list):
for number in my_list:
...
Functions in python are defined using the def keyword:
def function_name(number):
for number in my_list:
number = number + something
you have to use def to define a function

Categories