I cannot figure out how do I pass the result of one method to another one. The first method generates new array, filled with numbers in whatsoever size. The second method is supposed to sort all the numbers within the array, which have been previously generated in method no.1. I am getting an error "NameError: name 'value' is not defined". Is this because the list returns None? If so, how do I make it work? I would appreciate any help.
def Display_Details1(self):
value = []
num1 = int(input("Select array size: "))
seed(0)
for i in range(num1):
value.append(random.randint(1, 99))
print(value)
return value
print(self.generate)
def Display_Details2(self):
value.sort()
return value
print(self.sort)
Passing a variable from one function as argument to another function can be done like this:
First off, define functions like this:
def function1():
global a
a=input("Enter any number\t")
def function2(argument):
print ("this is the entered number - ",argument)
call the functions like this
Then call them like this:
function1()
function2(a)
Related
Defining a FUNCTION through which we pass a variable name and in return we get a new variable assigned with a user_inp value.
I Tried this :
def Uinp(variable):
variable = eval(input(f'Enter {variable} value : '))
return variable
#trying the function.
x.Uinp
#trying to call the function.
Uinp(x)
print(x)
But coudn't get the desired results..
I think you need this:
def Uinp(variable):
variable = eval(input(f'Enter {variable} value : '))
return variable
print(Uinp(x))
So it's worth knowing that you really should not do this. It is very unexpected and modification of the globals dict is going to lead to some very hard to debug errors for you or someone else.
HOWEVER, it's definitely possible. Modification of the globals dict is legal Python.
def my_function(var_name):
"""Please don't use this function it's actually Pandora's Box of bugs."""
user_inp = input("Enter some value: ")
globals()[var_name] = user_inp
Use it with:
>>> my_function("this_is_a_new_variable")
Enter some value: this is my value that I've entered
>>> print(this_is_a_new_variable)
this is my value that I've entered
I have created two functions namely inputData(): and validateNumber():
In the inputData() function I enter a value and stores it in a variable called number. And then I want to pass that parameter to validateNumber(): function. But it isn't work :(
It would be fine if anyone explain me the error :)
Regards.
Here's the code:
def inputData():
number = int(input("Enter a Number: "))
print(number)
return number
def validateNumber(number):
n=2
while number > n:
if number%n==0 and n!=number:
print("Not Prime")
break
else:
print("Prime")
break
return number
inputData()
validateNumber()
You need to perform the function call as follows:
validateNumber(inputData())
or
number = inputData()
validateNumber(number)
with def validateNumber(number) you are telling python that the function validateNumber must receive one parameter when it is called. But, you are not passing the parameter to it when you call it.
If you are new to programming, check this tutorial: Python Functions, to understand:
What are functions
How to define them
How to use them.
You need to store the value of inputData() function in some variable then pass it to second function like this
>> number = inputData()
>> validateNumber(number)
You're not passing the inputted number to the validate function.
returned_input_number = inputData()
validateNumber(returned_input_number)
Also, I find it a bit odd that your validateNumber function returns a number. It might be better to return True or False (depending on if the number is valid or not). Either that, or maybe 'validate' is the wrong name for the function.
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.
I am getting an error with the first function that I have
def print():
list = [[" ","1","2","3"],["1","-","-","-"],["2","-","-","-"],["3","-","-","-"]]
for item in list:
print(" ".join(item))
def gorow():
userrow = input("row")
return int(userrow)
def gocolumn():
usercolumn = input("column")
return int(usercolumn)
print()
x = list[gorow()][gocolumn()]
print()
Do not use type names as variables names. Change your variable list so it does not conflict with a typename.
And since you named your function print, Python will attempt to recursively call your print function, instead of the actual Python print function. I'm assuming it is then throwing a TypeError because your print function does not take any arguments.
You used a function is already exist. Dont use def print(). Print is already exist. Change the name
Rename function print to myprint
def print():
to
def myprint():
then call it
myprint()
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