Different output than expected - python

I just started programming and right now I'm stuck with a problem. I'm wondering how if functions really work.
a = [ 20.0, 8.0, 2.5 ]
b = 4
if b > len(a):
r = 2*b
r = b
I expected the output of 8, but the actual output is 4. How come? Because 4 > 3 and that should execute the if statement right?

The problem is that you do not have an else statement which should be executed if your condition if b > len(a) is not True. So in your code, the if statement is first executed, the value of r becomes twice of b (r becomes 8) but then you come out of the if statement and again reassign b to r which is why your r becomes 4 again. I hope the concept is clear now.
The correct way would be
a = [ 20.0, 8.0, 2.5 ]
b = 4
if b > len(a):
r = 2*b
else:
r = b

Related

Python - Multiple Assignment [duplicate]

This question already has answers here:
Multiple assignment and evaluation order in Python
(11 answers)
Closed 2 years ago.
Recently I was reading through the official Python documentation when I came across the example on how to code the Fibonacci series as follows:
a, b = 0, 1
while a < 10:
print (a)
a, b = b, a + b
which outputs to 0,1,1,2,3,5,8
Since I've never used multiple assignment myself, I decided to hop into Visual Studio to figure out how it worked. I noticed that if I changed the notation to...
a = 0
b = 1
while a < 10:
print (a)
a, b = b, a + b
... the output remains the same.
However, if I change the notation to...
a = 0
b = 1
while a < 10:
print(a)
a = b
b = a + b
... the output changes to 0, 1, 2, 4, 8
The way I understand multiple assignments is that it shrinks what can be done into two lines into one. But obviously, this reasoning must be flawed if I can't apply this logic to the variables under the print(a) command.
It would be much appreciated if someone could explain why this is/what is wrong with my reasoning.
a = 0
b = 1
while a < 10:
print(a)
a = b
b = a + b
In this case, a becomes b and then b becomes the changed a + b
a, b = 0, 1
while a < 10:
print (a)
a, b = b, a+b
In this case, a becomes b and at the same time b becomes the original a + b.
That's why, in your case b becomes the new a + b, which, since a = b, basically means b = b + b. That's why the value of b doubles everytime.
When you do a, b = d, e the order in which assignment happens in from right to left. That is, b is first given the value of e and then the other assignment happens. So when you do a, b = b, a + b what you are effectively writing is,
b = a + b
a = b
Hence the difference.
You can verify this by doing
a = 0
b = 1
while a < 10:
a, b = b, a + b
print(a, b)
the first output is 1 1. So first b becomes 0+1 and then a is given the value of b=a making it also 1.
If you want more details on how this works, you can check out this question.
In a multiple assignment, the right side is always computed first.
In effect,
a, b = b, a + b
is the same as:
b = a + b
a = b

How to replace values in a array?

I'm beggining to study python and saw this:
I have and array(km_media) that have nan values,
km_media = km / (2019 - year)
it happend because the variable year has some 2019.
So for the sake of learning, I would like to know how do to 2 things:
how can I use the replace() to substitute the nan values for 0 in the variable;
how can i print the variable that has the nan values with the replace.
What I have until now:
1.
km_media = km_media.replace('nan', 0)
print(f'{km_media.replace('nan',0)}')
Thanks
Not sure is this will do what you are looking for?
a = 2 / np.arange(5)
print(a)
array([ inf, 2. , 1. , 0.66666667, 0.5 ])
b = [i if i != np.inf or i != np.nan else 0 for i in a]
print(b)
Output:
[0, 2.0, 1.0, 0.6666666666666666, 0.5]
Or:
np.where(((a == np.inf) | (a == np.nan)), 0, a)
Or:
a[np.isinf(a)] = 0
Also, for part 2 of your question, I'm not sure what you mean. If you have just replaced the inf's with 0, then you will just be printing zeros. If you want the index position of the inf's you have replaced, you can grab them before replacement:
np.where(a == np.inf)[0][0]
Output:
0 # this is the index position of np.inf in array a

Explain how multiple variable assignment in single line works? (Example: a, b = b, a+b)

Say I have this Python code
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
For n=1000 this prints:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
But I don't understand why it's 1 1 2 3.
The issue is with this line:
a, b = b, a+b
What is the order of execution?
The two options I see are:
1:
a = b
b = a+b
2:
b = a+b
a = b
But neither gives me the correct result when I try it manually.
What am I missing?
None of the two options you shared actually describe the working of:
a, b = b, a+b
Above code assigns a with the value of b. And b with the older value of a+b (i.e. in a+b the older value of a). You may consider it as an equivalent of:
>>> temp_a, temp_b = a, b
>>> a = temp_b
>>> b = temp_a + temp_b
Example: Dual variable assignment in one line:
>>> a, b = 3, 5
>>> a, b = b, a+b
>>> a
5
>>> b
8
Equivalent Explicit Logic:
>>> a, b = 3, 5
>>> temp_a, temp_b = a, b
>>> a = temp_b
>>> b = temp_a + temp_b
>>> a
5
>>> b
8
The order of operations in a, b = b, a+b is that the tuple (b, a+b) is constructed, and then that tuple is assigned to the variables (a, b). In other words, the right side of the assignment is entirely evaluated before the left side.
(Actually, starting with Python 2.6, no tuple is actually constructed in cases like this with up to 3 variables - a more efficient series of bytecode operations gets substituted. But this is, by design, not a change that has any observable differences.)
It's python standard way to swap two variables, Here is a working example to clear your doubt,
Python evaluates expressions from left to right. Notice that while
evaluating an assignment, the right-hand side is evaluated before the
left-hand side.
http://docs.python.org/3/reference/expressions.html#evaluation-order
a=[1,2,3,4,5]
for i,j in enumerate(a):
if i==1:
a[i-1],a[i]=a[i],a[i-1]
print(a)
output:
[1, 2, 3, 4, 5]
For more info , read this tutorial

Factorial number printing

I'm a newbie at python. I started it not long a ago as a hobby after uni lecture hours.
I found this exercise ( forgot where I got it from now) to do which is to print out the factorial numbers.
Which I did. But, problem is that I'm tasked to manipulate line 3 so it only prints out the number 1 once at the start of the sequence and I'm having trouble with that.
Please can any help? :)
In advance sorry if the question wasn't worded as good as it could have been.
a, b = 0, 1
while a < 19:
print b,
a, b = a + 1, b * (a+1)
Result:
1 1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800 87178291200 1307674368000 20922789888000 355687428096000 6402373705728000
a, b = 0, 1
while a < 19:
if a: print b,
a, b = a + 1, b * (a+1)
Use a in-line if statement to check if a is 1. If it's 1 then you know that you already went through the loop at least once.

How to add to an already existing variable in python?

I know this is a very simple question, but I couldn't find it. Basically what I'm trying to is have a=2, b=3, and I need a+b=b so when I add a and b what it equals needs to be b.
Either:
b = a + b
# make b equal to a + b
Or
b += a
# increase the value of b by a
declare variables
a = 2
b = 3
operates
b = a+b
You can use the += shorthand for summation on variable.
For instance, in order to add in the value of a in the b variable, and retaining the last value of b:
b += a
This is the same thing as saying: b = a + b. Both works fine. Choose as you feel is readable.
Here is a quick example:
First, initialize your variables:
a = 2
b = 3
print a, b
Output: 2 3
You can add a to b, this way:
b += a
print b
Output: 5
You can also add to the actual value of b 10
b = 10+b
print b
Output: 15

Categories

Resources