def message(number):
`number+=2`
print(number)
ans = message(number)
return number`
if ans == 3:
`print("theory was right")`
number=1234
message(1)
print(number)
In the above code, I am not able to use variable returned from def() out of the function body. Is there a way I can do it? Pls. don't mind indents coz this is my first post here. thnx
I've tried
ans = number
also
ans = message()
but still not able to do get the output
Firstly, you build an infinite recursion - if you want to use a function inside itself, you have to insert a condition which will stop the recursion and let you get a result.
So, above ans = message(number), you should place if statement.
Secondly, you cannot use a variable out of a function, if it is not returned - it has never been counted.
You probably got confused it with possibilty of using global variables out of loops.
To sum up, if you want to check ans, you have to return it in a function and call the function like this (it is not the solution):
def function(x):
ans = message(number)
return ans
if funcion(x):
print("theory was right")
Related
Sorry for my ugly English.
This is one of my homework.
I'm making function that finds the max integer in any list, tuple, integer..
like "max_val((5, (1,2), [[1],[2]])) returns 5"
When I ran my code, there was no syntax error. I ran as many various cases I can.
But the homework system told me this code was incorrect.
Anyone give me hint?
numList = []
def max_val(t):
if type(t) is int:
numList.append(t)
else:
for i in range(len(t)):
if t[i] is int:
numList.append(t[i])
else:
max_val(t[i])
return max(numList)
Your code gives wrong results when called several times:
>>> max_val((5,4,3))
5
>>> max_val((2, 1))
5
That's because numList is a global variable that you don't "reset" between calls of your function.
You can simplify your code quite a bit, without needing that global variable:
def max_val(t):
if isinstance(t, int):
return t # t is the only element, so it's by definition the biggest
else:
# Assuming max_val works correctly for an element of t,
# return the largest result
return max(max_val(element) for element in t)
As explained in L3viathan's answer, the main issue with your code is that numList is a global variable. Here is a simple way to fix it without changing the logic of your code:
def max_val(t):
numList = [] # local variable
max_val_helper(t, numList) # fill numList with elements from t
return max(numList)
def max_val_helper(t, numList): # this function modifies its second argument and doesn't return a value
if type(t) is int:
numList.append(t)
else:
for i in range(len(t)):
max_val_helper(t[i], numList)
The function max_val_helper is recursive and appends all numbers in the nested iterables to its argument numList. This function doesn't have a return value; the effect of calling it is that it modifies its argument. This kind of function is sometimes called a "procedure".
The function max_val, on the other hand, is a "pure" function: it returns a value without any side-effect, like modifying its argument or a global variable. It creates a local variable numList, and passes this local variable to max_val_helper which fills it with the numberss from the nested iterables.
The code suggested in L3viathan's answer is arguably more elegant than this one, but I think it's important to understand why your code didn't work properly and how to fix it.
It's also good practice to differentiate between functions with side-effects (like modifying an argument, modifying a global variable, or calls to print) and functions without side-effects.
Whenever I am trying to run the given code it always gives the error 'str' object is not callable.
Somebody please tell me what is wrong with the code.
Here is the code:
def intel():
c=0
for i in num(1,9):
if((num[i]%2)==0):
c=c+1
return c
num = input()
out= intel()
print(out)```
Bachchu, welcome! There are a few different things going on here:
As usr2564301 explained, the TypeError: 'str' object is not callable is Traceback for statement for i in num(1,9): because the num() function does not exist unless you define one yourself. That is to say that functions like print() are built-in to Python such that you need not import additional modules to have automatic access to them. The num() function does not exist in the default 'namespace' which you have access to. Perhaps you did define one in another module and forgot to import it, or perhaps you did not mean to call that as a function, but it caused the error because unless you have visibility to it (for example through a def or import) then it does not exist as far as Python is concerned.
This segues into Carl Brubaker's assumption that you meant to use the range() function instead of num() altogether. The range() function would generate a list of [1,2,3,4,5,6,7,8] for your code to iterate through. It starts at the first argument (1) and goes up to but not including the second argument (9-1 = 8). I will add that perhaps, if you did indeed intend for the generation of a list, you probably meant to include 9 in the list, in which case you would need to use range(1,10).
As far as num() and input() are concerned, I don't think you are trying to define a num() function by entering it at the keyboard and assigning it to variable num via a call to the input() function.
The num = input() statement accepts user input from the keyboard and assigns it in string format to the variable num. As Carl Brubaker explained, you will need to convert (or cast if you are familiar with other languages) that data to int() before comparing it numerically. You can easily do this by wrapping the input() call:
num = int(input())
or like this:
num = input()
num = int(num)
One last piece of two-cents: The input() function can be passed a prompt string to present to the user so that when the control is passed to the terminal, the prompt will indicate to the user that it is expecting something. Here's an example:
num = int(input('Please enter a number: '))
As expected, this will present the user, at the terminal (command prompt), with the following:
Please enter a number:
Note that the blank space is a spacer so that the user's data will begin one space after the colon (for the sake of clarity).
At this juncture, we could guess what your objective is, but it would be best if you first cleaned up what we have pointed out here, then followup with outstanding issues, if any remain.
I am having trouble with the second function in converting it back to the original string. I see what the issue is as when I call previous function, the tuple has a string and an int. So I assume I must convert that int to a string. But based on the code I wrote, I am not sure where to convert it. Hopefully, I am on the right track with this. My professor is very strict when it comes to certain things I cannot use any built-ins. Thank you. Any help is appreciated.
EDIT
Will put code back soon
My suggestion is in this case to use print statements for debugging.
def rldecode(rlencode):
decodedString = ""
L = []
for i in rlencode:
counter = 0
occurrence = i[1] # tuple (item, occurrence) == positions (0, 1)
for j in range(occurrence):
L.append(i[0])
return ''.join(L)
I'm kind of newbie as programmer, but I wish to master Python and I'm developing open source application. This application has function to gather some information. This function takes 1 parameter. This parameter can be 0, 1 or 2. 0 = False, 1 = True, 2 = Multi. Also I have an if statement that does 2 actions. 1st - (when False) gathers single type value, 2nd - (when True) gathers multiple type values and when parameter is 2 (multi) then it will gather single type (1st) and multiple types (2nd). My if statement looks like this:
if False:
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
elif True:
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
else:
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
Is there maybe better way of avoiding this kind of coding, like in last else statement when I call both single and multiple.
Thank you in advance.
One thing I learned from Python is that although it lacks the Switch operator, you can use dictionary in a similar fashion to get things done since everything is an object:
def get_single():
# define your single function
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
def get_multi():
# define your multi function
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
actions = {
0: [get_single],
1: [get_multi],
2: [get_single, get_multi]
}
parameter = 0 # replace this line with however you are capturing the parameter
for action in actions[parameter]:
action()
This way you avoid c+p your code everywhere and have it referenced from the function, and your "actions" dictionary define the function to be used based on the parameter given.
In this case since you have multiple functions you want to call, I kept all dictionary items as a list so the structure is consistent and it can be iterated through to perform any number of actions.
Ensure you use leave out the () in the dictionary so that the functions aren't instantiated when the dictionary is defined. And remember to add () when you are actually calling the function from the dictionary to instantiate it.
This is something you will often encounter and it is pretty much always bad practice to be repeating code. Anyway, the way to do this is use two if-statements. This way, even if the first case passes, the second case can still pass. Oh, and assuming your variable that can be 0, 1 or 2 is called x, then we could either use or and two checks:
if x == 0 or x == 2:
but, personally, I prefer using in on a tuple:
if x in (0, 2):
get_single_type = code.of.action
generators.generate_data(False, get_single_type)
if x in (1, 2):
get_multiple_type = code.of.action
generators.generate_data(True, get_multiple_type)
I am getting an value from the user in getInteger.
I need to get the output from sqInteger in getInteger.
No matter how I set up the parameters or indent the sqInteger function, variable x is undefined.
I added a return line to try and pass the x variable, but that's definitely not helping.
Please help me understand what I'm missing!
def getInteger():
while True:
try:
x = int(input('Enter an integer: '))
except ValueError:
print()
print('That\'s not an integer. Try again.')
continue
else:
return x
print(x)
break
def sqInteger(getInteger, x):
y = x**2
print(y)
Is this the entire code? You need to call the getInteger() function at some point in the code before that loop will begin. You're also not calling function sqInteger() at any point.
Your exception handler will immediately stop evaluating the try block and move down to the except block upon a non-integer being typed into the input. Therefore, you can place a call to the sqInteger() function after the input() function. If the user types a non-integer into the terminal, it will move down to your Exception handler and prompt the user to retry. If they enter an integer, the code will continue to evaluate and run the function sqInteger.
For this, you also do not need to pass getInteger into the sqInteger() function. You are technically allowed to pass functions as parameters in Python but it's not necessary for this and probably out of the scope of this program.
So the following code would be suitable:
def getInteger():
while True:
try:
x = int(input('Enter an integer: '))
# variable 'squared' now receives the return value from the function
squared = sqInteger(x) # call to function sqInteger necessary for this function to be executed
except ValueError:
print('That\'s not an integer. Try again.')
continue
else:
print(x) # if user entered 2, prints 2, not 4
return x # this value is still only what the user input, not the result of sqInteger()
break
def sqInteger(x):
y = x**2
print(y)
return y #you need to return values from functions in order to access it from outside the function
The reason you pass a variable into a function (as a parameter) is to give that function access to that variable. Creating a function creates a local scope for that function so that variables named within that function are in a separate namespace from variables outside that function. This is useful in large programs where many variables might exist and you need to keep them separate.
Because you've separately defined a sqrt function, it does not have access to variables outside of its scope. You need to pass in variables that you'd like it to have access to.
You also need to call functions before they will run. Defining a function only serves to set up the function so that it can be called as one functional unit. It's useful for separating concerns within a program. The ability to call a function is useful because it allows you to separate your code out and only mention a single call to a function rather than having the entire functionality jumbled in with the rest of the code. It also allows for reusability of code.
You can also have access to the result of the squared integer by returning a value and assigning this value to a function call, like such:
# lets say x = 4
squared = sqInteger(x)
def sqInteger(x):
y = x**2
return y
This would NOT work:
x = input("Enter integer") #lets say you enter 3
squared = sqInteger()
print(squared)
def sqInteger():
print(x) # error: x is not defined
return x**2 # error: x is not defined
The function does not have access to outside variables like x. It must be passed these variables as parameters so that you can call this function and set the parameters at will. This is for the sake of modularity in a program. You can pass it all sorts of different integers as parameters and it allows you to have a resuable function for anytime you need to square an integer.
Edit: Sorry this was a mess, I finally fixed all the errors in my explanation though...