import string
decimal1 = 55
binary1 = 0
def convert(decimal1, binary1):
binary1 = str(decimal1 % 2) + str(binary1)
decimal1 = decimal1//2
if decimal1 == 0:
binary1 = str(binary1)
return binary1
convert(decimal1, binary1)
x = convert(decimal1, binary1)
print(x[-1])
I wanted a code that converts decimal to binary but the function output is not being taken into x or the program is the returning none. I want to understand why it is happening??
I think if you want to reteurn the result, then you don't need to pass binary1 variable.
import string
decimal1 = 55
def convert(decimal1):
value = str(decimal1 % 2)
decimal1 = decimal1//2
if decimal1 == 0:
return value
else:
return convert(decimal1) + value
x = convert(decimal1)
print(x)
Your function only has one return statement, for the base case. You need a return for the recursive case, too.
When the recursion finishes, in your case the value is just thrown away because there's no return. Python isn't like other languages that return the value of the last expression. If there's no return statement, it returns None instead.
To debug recursion problems like this it can be helpful to visualize whats happening. If you post OPs code in this recursion visualizer here you can see the return value isnt bubbling up, as it does in the selected answer here.
I have a small snippet of code with two functions in it.
I want to call the first function if it receives a response then perform a function on that response. Then assign the result to another variable.
In a verbose way it looks like:
result = get_something()
if result:
answer = transform(result)
alternatively I could do
if get_something():
answer = transform(get_something())
but that requires calling the first function twice
is there a way to do all of this on one line a bit like a ternary (maybe as a lambda)
answer = transform(result) if get_something() else None
Obviously in the above there is nothing to state what result is but I need to say basically where result = get_something()
I can do that in a list comprehension but that seems a bit dumb
answer = [transform(x) for x in [get_something()] if x][0]
In the latest Python version (Python 3.8) there's a new assignment that may be useful for you, :=:
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “walrus operator” due to its resemblance to the eyes and tusks of a walrus.
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
In this example, the assignment expression helps avoid calling len() twice:
We can in Python 3.8 with assignment expressions:
if (result := get_something()) is not None:
# do something with result
Although I don't fully understand the reasons for doing things this way (which is less clear than any of the others), here's an example using lambda:
>>> def get_something(flag): # Added the flag argument, to mimic different return values
... return 5 if flag else None
...
>>> answer = (lambda func, arg: func(arg) if arg else None)(int, get_something(True))
>>> answer
5
>>> answer = (lambda func, arg: func(arg) if arg else None)(int, get_something(False))
>>> answer
>>>
I am fairly new to python but worked with recursion previously. I came across this problem while working with recursive functions.
archive = {1: 0}
def engine(base, chain=0):
if base in archive:
return archive[base]
else:
if base == 1:
return chain
elif base % 2 == 0:
get = engine(base/2)
meaning = 1 + get
archive[base] = meaning
else:
next = 3 * base + 1
get = engine(next)
meaning = 1 + get
archive[base] = meaning
print archive(13)
I worked with scheme recently. So, I expected it to work.
I want the code to evaluate till the case bool(base==1) becomes true and then work it's way up ward making a new entry to the dictionary on each level of recursion.
How can I achieve that? I am just counting the level of recursion until the fore-mentioned condition becomes True with the variable 'chain'.
[Solved]: I missed the return statement in two clauses of if-else statement. The scheme would pass the function itself and the last return statement would do the work but not with python. I understand it now.
Thanks everyone who responded. It was helpful.
Your last two elif and else clauses have no return statements and Python returns None by default.
If I have a function with multiple conditional statements where every branch gets executed returns from the function. Should I use multiple if statements, or if/elif/else? For example, say I have a function:
def example(x):
if x > 0:
return 'positive'
if x < 0:
return 'negative'
return 'zero'
Is it better to write:
def example(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
Both have the same outcome, but is one more efficient or considered more idiomatic than the other?
Edit:
A couple of people have said that in the first example both if statements are always evaluated, which doesn't seem to be the case to me
for example if I run the code:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
l will still equal [1,2,3]
I'll expand out my comment to an answer.
In the case that all cases return, these are indeed equivalent. What becomes important in choosing between them is then what is more readable.
Your latter example uses the elif structure to explicitly state that the cases are mutually exclusive, rather than relying on the fact they are implicitly from the returns. This makes that information more obvious, and therefore the code easier to read, and less prone to errors.
Say, for example, someone decides there is another case:
def example(x):
if x > 0:
return 'positive'
if x == -15:
print("special case!")
if x < 0:
return 'negative'
return 'zero'
Suddenly, there is a potential bug if the user intended that case to be mutually exclusive (obviously, this doesn't make much sense given the example, but potentially could in a more realistic case). This ambiguity is removed if elifs are used and the behaviour is made visible to the person adding code at the level they are likely to be looking at when they add it.
If I were to come across your first code example, I would probably assume that the choice to use ifs rather than elifs implied the cases were not mutually exclusive, and so things like changing the value of x might be used to change which ifs execute (obviously in this case the intention is obvious and mutually exclusive, but again, we are talking about less obvious cases - and consistency is good, so even in a simple example when it is obvious, it's best to stick to one way).
Check this out to understand the difference:
>>> a = 2
>>> if a > 1: a = a+1
...
>>> if a > 2: a = a+1
...
>>> a
4
versus
>>> a = 2
>>> if a > 1: a = a+1
... elif a > 2: a = a+1
...
>>> a
3
The first case is equivalent to two distinct if's with empty else statements (or imagine else: pass); in the second case elif is part of the first if statement.
In some cases, elif is required for correct semantics. This is the case when the conditions are not mutually exclusive:
if x == 0: result = 0
elif y == 0: result = None
else: result = x / y
In some cases it is efficient because the interpreter doesn't need to check all conditions, which is the case in your example. If x is negative then why do you check the positive case? An elif in this case also makes code more readable as it clearly shows only a single branch will be executed.
In general (e.g. your example), you would always use an if..elif ladder to explicitly show the conditions are mutually-exclusive. It prevents ambiguity, bugs etc.
The only reason I can think of that you might ever not use elif and use if instead would be if the actions from the body of the preceding if statement (or previous elif statements) might have changed the condition so as to potentially make it no longer mutually exclusive. So it's no longer really a ladder, just separate concatenated if(..elif..else) blocks. (Leave an empty line between the separate blocks, for good style, and to prevent someone accidentally thinking it should have been elif and 'fixing' it)
Here's a contrived example, just to prove the point:
if total_cost>=10:
if give_shopper_a_random_discount():
print 'You have won a discount'
total_cost -= discount
candidate_prime = True
if total_cost<10:
print 'Spend more than $10 to enter our draw for a random discount'
You can see it's possible to hit both conditions, if the first if-block applies the discount, so then we also execute the second, which prints a message which would be confusing since our original total had been >=10.
An elif here would prevent that scenario.
But there could be other scenarios where we want the second block to run, even for that scenario.
if total_cost<10:
<some other action we should always take regardless of original undiscounted total_cost>
In regards to the edit portion of your question when you said:
"A couple of people have said that in the first example both if statements are always evaluated, which doesn't seem to be the case to me"
And then you provided this example:
l = [1,2,3]
def test(a):
if a > 0:
return a
if a > 2:
l.append(4)
test(5)
Yes indeed the list l will still equal [1,2,3] in this case, ONLY because you're RETURNING the result of running the block, because the return statement leads to exiting the function, which would result in the same thing if you used elif with the return statement.
Now try to use the print statement instead of the return one, you'll see that the 2nd if statement will execute just fine, and that 4 will indeed be appended to the list l using append.
Well.. now what if the first ifstatement changes the value of whatever is being evaluated in the 2nd if statement?
And yes that's another situation. For instance, say you have a variable x and you used if statement to evaluate a block of code that actually changed the x value.
Now, if you use another if statement that evaluates the same variable x will be wrong since you're considering x value to be the same as its initial one, while in fact it was changed after the first if was executed. Therefore your code will be wrong.
It happens pretty often, and sometimes you even want it explicitly to be changed. If that's how you want your code to behave, then yes you should use multiple if's which does the job well. Otherwise stick to elif.
In my example, the 1st if block is executed and changed the value of x, which lead to have the 2nd if evaluates a different x (since its value was changed).
That's where elif comes in handy to prevent such thing from happening, which is the primary benefit of using it.
The other secondary good benefit of using elif instead of multiple if's is to avoid confusion and better code readability.
Consider this For someone looking for a easy way:
>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
... if 'fb' in i:
... pass
... if 'tw' in i:
... pass
... else:
... print(i)
output:
fb.com
cat.com
And
>>> a = ['fb.com', 'tw.com', 'cat.com']
>>> for i in a:
... if 'fb' in i:
... pass
... elif 'tw' in i:
... pass
... else:
... print(i)
Output:
cat.com
'If' checks for the first condition then searches for the elif or else, whereas using elif, after if, it goes on checking for all the elif condition and lastly going to else.
elif is a bit more efficient, and it's quite logical: with ifs the program has to evaluate each logical expression every time. In elifs though, it's not always so. However, in your example, this improvement would be very, very small, probably unnoticeable, as evaluating x > 0 is one of the cheapest operations.
When working with elifs it's also a good idea to think about the best order. Consider this example:
if (x-3)**3+(x+1)**2-6*x+4 > 0:
#do something 1
elif x < 0:
#do something 2
Here the program will have to evaluate the ugly expression every time! However, if we change the order:
if x < 0:
#do something 2
elif (x-3)**3+(x+1)**2-6*x+4 > 0:
#do something 1
Now the program will first check if x < 0 (cheap and simple) and only if it isn't, will it evaluate the more complicated expression (btw, this code doesn't make much sense, it's just a random example)
Also, what perreal said.
I'm making a double variable if statement and it keeps returning an error. I don't know what's wrong:
variable = float(0)
for index in range(10):
variable = variable + float(2)
if x <= float(variable/3) and > float(variable-2.0/3):
# do something
else:
pass
or something like that. This is the basic structure. Why does it keep highlighting the > in red whenever I try to run it?
Python supports regular inequalities as well, so you could just write this:
if variable - 2.0 / 3 < x <= variable / 3:
# ...
You want to do something like
if ((x <= float(variable/3)) and (x > float(variable-2.0/3))):
# do something
else:
pass
In other words, each side of the and must be a boolean expression on its own. I'm not sure whether you need all the parenthesis.
It seems like you're missing a variable or constant before the second condition in the if-block. That might be one reason you're getting an error.
This code works fine:
index=0
x=0
variable = float(0)
for index in range(10):
variable=variable + float(2)
if x <= float(variable/3) and x> float(variable-2.0/3):
print 'Doesn\'t Matter'
else:
print 'pass'