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
Related
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)
I am trying to create a function in which I will store formulas for my converter. When X formula will be needed, it will be called from it. When trying it with simple 0:a+b it works when returning, but when trying to store it as string meters_to_foots, it doesn't work. I need to have that formula stored as something since I need to output it later.Here is a part of the code which I have problems with. NameError: name 'meters_input' is not defined
def my_formulas(i):
switcher={
0:(meters_input/0.3048)
}
return switcher.get(i,"Invalid formula")
distance_pick=input("Please pick one of the current convertions : \n \n1.Meters to X \n2.Inches to X \n3.Feets to X ")
if(distance_pick=="1"):
cls()
distance_choice = input ("Please select which converter would you like to use ! : \n \n1.Meter to Foot \n2.Meter to Yard \n3.Meters to Inches ")
if(distance_choice=="1"):
meters_input=float(input("Make sure to enter distance in Meters ! : "))
my_formulas(0)
print ("\nYou entered", meters_input , "meters, which is equal to",my_formulas(0),"foots.")
time.sleep (3)
cls ()
read_carefully_message()
To create a function in Python use either lambda functions or the regular function definition. Examples are respectively:
def divide(meters_input):
return meters_input / 0.3048
or
divide = lambda meters_input: meters_input / 0.3048
Generally the regular function definition is preferred since it improves readability. You can define your function mapping as follows:
def my_formulas(i):
switcher={
0:divide # do not write divide()
}
If these will always be simple functions you can use a lambda expression for this:
def my_formulas(i):
switcher= {
0:lambda meters_input: meters_input/0.3048
}
return switcher.get(i,"Invalid formula")
my_formulas(0)(27) #88.58267716535433
If your function lookup will always be a number starting with zero you might be better off storing the functions as an array. You could do something like this as well:
def my_formulas(index):
def meters2Feet(meters):
return meters/0.3048
def hours2Minutes(hours):
return hours * 60
def invalid(*args):
return "Invalid formula"
lookup = [
meters2Feet,
meters2Feet
]
if index >= len(lookup):
return invalid
return lookup[index]
my_formulas(0)(27) # 88.58267716535433
It's a little more complicated, but probably easier to read and understand.
Try changing your function to this:
def my_formulas(i):
switcher = (i/0.3048)
return switcher
The "i" in the function is a local variable for the function. In your code you are passing 0 into the my_formulas() function. i then becomes 0, but meters_input is out of scope 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 brushing up a bit of good old algorithms, and doing it with python, since I use it more often nowadays.
I am facing an issue when running a recursive function; where the variable get reset every time that the recursive function call itself:
def recursive_me(mystring):
chars = len(mystring)
if chars is 0:
print("Done")
else:
first = int(str[0])
total = + first
print(total)
recursive_me(mystring[1:])
recursive_me("4567")
What I am doing here is to get a string made of digits; take the first, convert it to an int; and run recursively the function again, so I can take one digit at time from the string and sum all the values.
Ideally the output should show the total, while it add all the digits (4+5+6+7), although when the recursive function is called the first time, the function reset the total value.
Is common habit to use global variables when running operations with recursive functions or am I doing something wrong?
You can code as simply as this:
def recursive_me(mystring):
if mystring: # recursive case
return int(mystring[0]) + recursive_me(mystring[1:])
else: # base case
return 0
or
def recursive_me(mystring, total = 0):
if mystring: # recursive case
return recursive_me(mystring[1:], total + int(mystring[0]))
else: # base case
return total
although this won't help much in Python since it doesn't implement tail-call optimisation.
If you want to see the intermediate values, change the second version like so:
def recursive_me(mystring, total = 0):
if mystring: # recursive case
newtotal = total + int(mystring[0])
print(newtotal)
return recursive_me(mystring[1:], newtotal)
else: # base case
return total
then
4
9
15
22
22 # this is the return value; previous output is from `print()`
as a foreword: a lot of answers received meaningful edits in the meantime I was writing this answer. Don't hold it against me.
I'm throwing my two cents in here just because there's a lot of over-complicated answers.
This is a corrected copy-paste of the OP's effort.
def recursive_me(mystring, total=0):
chars = len(mystring)
if chars is 0:
print("Done")
return total
else:
first = int(mystring[0])
total += first
print(total)
recursive_me(mystring[1:], total)
first what happens is that we check the base case, if there's no left chars in the string. If the string length is 0 we return the total calculated ammount.
Otherwise, we turn the first of the chars into an int, and add it to total. The first error you have is that you wrote str[0]. str is a python built in type and the produced error would be something like "str is not subscriptable".
This error means that the str can't be operated on by "[]" operator. The same would happen if you tried doing 1[0] because 1 is a integer. The "[]" operator can only operate on lists, tuples and strings (I might've forgot some built-in type).
The second error you had was with the addition part. You had written total = + first but the operator you are looking for is the += which in fact is just a shortened way to write a = a+b.
Additionally, your original question was concerning about "python" forgetting the value of "total". This is because you have to either pass that value forward, or write your recursive function in a way that "forces" it to, what's called, evaluate your next call to your function on the spot.
In my example I'm sending the next call of the function recursive_me, the current total value. In the example given by #uselpa; above he's making python evaluate the next call to the function by putting it after operator +:
return int(mystring[0]) + recursive_me(mystring[1:])
this then gets to be (for recursive_me("4567"))
return int(4)+recursive_me("567")
return int(4)+int(5)+recursive_me("67")
....
return int(4)+int(5)+int(6)+int(7)+0
because python needs to return a value here, but the expression keeps calling new functions and python can't return until it evaluates all of them to a final number (in this case at least).
The common practice is to save these variables as parameters, and pass them along the chain. It seems in your case, you would want to pass total as an additional parameter, and update it as needed.
There's also a neat functional way to do it in python
t=raw_input()
print reduce(lambda a, b: a+b, map(int,t))
This is recursive in nature.
Some pointers:
Your default case should return an actual number (0 in your case) and not just print done.
total = + first is setting total to first, not adding first to total. You would need total += first to do the latter.
The trick with "retaining" the value of your current total is to "save" it in the recursive call-chain itself by passing it along with each call. You won't need a global variable or a default parameter to do this.
Here's a solution:
def recursive_me(mystring):
if not mystring: # True if mystring is empty
return 0
return int(mystring[0]) + recursive_me(mystring[1:])
print(recursive_me("4567")) # 22
Here is a solution that uses the LEGB scope rule to avoid creating a new string instance on every recursive call
def sum_str(mystring):
def recursive_me(pos):
cur_char = int(mystring[pos])
if pos:
return cur_char + recursive_me(pos-1)
else:
return cur_char
return recursive_me(len(mystring)-1)
s = '4567'
print('summing', s)
print(sum_str(s))
However, indexing can be avoided as well by iterating on the string
def sum_str(mystring):
def recursive_me(itx):
try:
cur_char = int(next(itx))
return cur_char + recursive_me(itx)
except StopIteration:
return 0
return recursive_me(iter(mystring))
Obviously, both solutions produce
summing 4567
22
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.