I have some variables A and B and I want to check them for a value and if both are False, the function shall render True:
if ( A == 1 and B == 2 ) == False :
do magic
I breaks down if either A or B is not defined and when I test it with
print(A == 1 and B == 1)
this breaks with an error:
IndexError: list index out of range
A or B are actually some variables from web-API and this whole thing runs in a loop, constantly checking and can be either set or not set with a value.
Is there a way to ignore whether A or B is defined or yield a default FALSE if not defined/existing?
Thanks heaps to #iBug
My solution is to check if there is anything in the list and then check if there is the desired element in the list:
'Yes' if fruit == 'Apple' else 'No'
client.futures_get_open_orders()[0]['side'] == 'BUY' if `client.futures_get_open_orders() == True else False`
Just had to sleep and drink 3 coffee in succession next morning :D
See: Putting a simple if-then-else statement on one line
Related
I asked myself if it makes a performance difference if I use an if statement with x conditions, or x if statements with only 1 condition each.
so for example:
if statement with 3 conditions:
if a == 0 and b == 0 and c == 0:
#do something
3 if statements with just one condition each:
if a == 0:
if b == 0:
if c == 0:
#do something
Why do I want to know this?
I have an if statement with around 30 conditions and my code gets really messi, so I thought about splitting my if-statement in half.
I think that the results of this examples will be the same, but I don't know if there would be a noticeable performance difference if a == 1. Would the program check all 3 conditions in the first example even if the first one (a is 1 not 0) is false?
With the given example, there won't be any difference in performance, even with if a == 0 and b == 0 and c == 0: it won't check b == 0 when the initial condition a == 0 itself is False. But considering the minimal lines of code & readability, if a == 0 and b == 0 and c == 0: would be the better option.
You can test the performance of your script using the timeit library. I will add an example below.
import timeit
stmt1 = 'if a == 0 and b == 0 and c == 0: pass'
stmt2 = """\
if a == 0:
if b == 0:
if c == 0:
pass
"""
setup1 = 'a, b, c = 0, 0, 0'
setup2 = 'a, b, c = 1, 0, 0'
print(f"First statement First setup execution time = {timeit.timeit(stmt=stmt1, setup=setup1, number=10**9)}")
print(f"First statement Second setup execution time = {timeit.timeit(stmt=stmt1, setup=setup2, number=10**9)}")
print(f"Second statement First setup execution time = {timeit.timeit(stmt=stmt2, setup=setup1, number=10**9)}")
print(f"Second statement Second setup execution time = {timeit.timeit(stmt=stmt2, setup=setup2, number=10**9)}")
Output:
First statement First setup execution time = 38.7665075
First statement Second setup execution time = 15.4141367
Second statement First setup execution time = 38.29726529999999
Second statement Second setup execution time = 15.527892699999995
This shows that there is negligible difference to how you format your if statement. But if the first condition is false then the rest of the conditions will not be checked and the execution of the code will run faster.
Edit:
Also after seeing wjandrea comment below I would like to add it to the answer if anyone in the future is wondering why this is. Per the python wiki you can read about short-circuiting operator behavior.
Any time difference between your two pieces of code is complete and total noise. Run your code a billion times, and the amount of time you might save between running one or the other is less than the time it took me to write these two sentences.
Seriously, if you need to be worried about the difference in time between the two pieces of code, Python is the wrong language.
Yes! I think there is an increase of productivity/performance if you can write your code in one line, since often times it can be easier to read and interpret; and even more so if you use descriptive variables.
In your code, I see some things that can be improved: There is what we call the (1) assignment operator, i.e. the equal(=) sign; and (2) The comparison operator, i.e. the "is equal to" (==) sign, "is greater than" (>), "is less than" (<), and etc.
When we define a variable, we use the assignment operator (=) sign. e.g:
a = 0
b = 0
c = 0
On the other hand, we use the comparison operator (such as the (==) symbol) when we make conditional statements. e.g:
if a == 0 and b == 0 and c == 0:
# do something
On to your second question: Would the program check all 3 conditions in the first example even if the first one (a is 1 not 0) is false?
a = 1
b = 0
c = 0
if a == 0:
if b == 0:
if c == 0:
# do something
Python will compare the conditions to your assigned variables, and if the condition turns out to be False, then there will be no ERROR, but it will also not execute the instruction that you've provided in your if-statement (meaning: it will not # do something).
I hope I had help you even a little bit.
Which code segment should replace the statement pass in the function hasEvenNumber which returns True if n contains an even number and False otherwise?
def hasEvenNumber(n):
for i in n:
pass # Replace this section with below options
return result
The question screenshot
This is an actual university exam question. I find it very badly structured and since my classmates are new too, nobody dared to voice out fearing to make a fool of themselves.
Firstly n was not given, but judging that n will be used in a for loop. n therefore, would be an iterable. I think none of the 4 options applies, but please advise me if I'm wrong.
Option 1:
if i % 2 == 0:
result = True
else:
result = False
This will only work if iterable only contains 1 item e.g [1,2,1] will not work since the result of 2 as even number that should return true will be replaced as the loop proceed to next iteration.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] True
[2] True
Option 2:
if i % 2 == 0:
result = True
break
else:
result = False
break
Worse than above, this will only iterate the first item and break regardless.
[1,2,1,1] False # Wrong, should be true
[1,1,1,2] False # Wrong, should be true
[2] True
Option 3:
if i % 2 == 0:
result = True
break
Function will have runtime error if no even number is found, the variable result will not be assigned.
[1,2,1,1] True
[1,1,1,1] Runtime Error
[2] True
[1] Runtime Error
Option 4:
if i % 2 != 0:
result = False
break
Same as above, runtime error. No variable will be assigned if all even numbers.
Personally, as the question asked to check if n contains even number. I would have written something like this.
# Break and exit loop once even number is found. Otherwise continue.
if i % 2 == 0:
result = True
break
else:
result = False
Unfortunately, this is not an option. Apologies if this is the wrong place to post this, but any advice would be gladly appreciated, and could possibly change the fate our my current school cohort.
Yes, you are right and little bit overthinking.
Third option is right and it is kinda assumed here that result is set to False in the beginning.
Also, your solution can be optimised by declaring result = False once in the beginning and then you can eliminate the else block completely.
If you want it to end when an even number is found, option 3.
I wrote this Python code that would check a list and return True if two items in the list next to each other are of the same value:
def samer(nums):
for i in range(0,len(nums)-1):
if (nums[i]) == (nums[i+1]):
return True
else:
return False
Result 1:
>>> samer([1,3,44,5,5,8])
False
This is where I'm puzzled because I feel it should return True.
Result 2:
>>> samer([3,3,49,93,5,8])
True
It only returns True if the first and second number in the list is True.
The solution:
def samer(nums):
for i in range(0,len(nums)-1):
if (nums[i]) == (nums[i+1]):
return True
return False
The above code works well, so my question is since the else statement indented under the if condition's purpose is to return False if no number in the list is next to each other in the process of the for loop, why do I still get False in Result 1?
Is it that it doesn't loop again after checking the first two boxes and why is that since it's the purpose of the for loop to go over each iteration and then check for the conditions?
When a function returns, that's it. The function is done, over, finished..
Since you're returning either true or false when checking each and every element, you really only check the first time through the loop (elements one and two), as you observe.
You should return true if a match is found and only return false at the end, when you've checked everything and, therefore, no matches are found. That code is already in your question, the bit under The solution.
So to chip in here, once that first iteration check occurs, we know that it's going to be returning False as the first two elements are not the same and the program ends there. If you want to really see that this is the case, make use of print() built-in function to see what's going on everytime the element is iterated within the for loop:
Like this:
def samer(nums):
for i in range(0,len(nums)-1):
if (nums[i]) == (nums[i+1]):
print(True)
else:
print(False)
### adding a main method is always a good idea for clarity.
if __name__ == "__main__":
print(samer([1,3,44,5,5,8]))
Output is this:
False
False
False
True
False
See it returned True for the 3th element as they are equal and next to each other.
But with the way you had it structured in the first example it does return False as it hit the roadblock once it checked and saw that the first iteration were not equal to each other and thus returned False.
def samer(nums):
for i in range(0,len(nums)-1):
if (nums[i]) == (nums[i+1]):
return True
else:
return False
if __name__ == "__main__":
print(samer([1,3,44,5,5,8]))
Output is:
False
With your solution approach which is great, the loop only 'terminates' when it really cannot find a match (same two numbers), it will return False without depending on a else statement. So if it finds a match then it will return True which is does and then stops iterating and exits the program.
I got a bit stuck with a for loop - what I can see it is doing appears correct but isn't exactly what I'm trying to accomplish with it. I've come from a C background but any advice here would be beneficial.
def deal(player_num, cards):
a = 0
z = 0
i = 0
b = 0
c = player_num
hand = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for a in range(player_num):
hand[a] = cards[i] + cards[i+b+c]
b == b+1
i == i+1
z == z+1
return hand
So the for a in range(player_num) seems to be working (appends a++) but hand[0], hand[1], etc. gets the same hand. I guess it loops a but not the other variables, so I need to use more than 1 nested loop to get i++, b++ and c++?
b == b+1 is a logical expression (returning False every time), not an assignment. I'm guessing you want something like: b += 1
== is the equality operator in Python. = is the assignment operator.
== checks whether its left operand and its right operand are equal and return True or False accordingly. b and b+1 will never be equal to each other and either way it does not make sense to perform an operation without side-effect (like comparing two values for equality) and then do nothing with its result.
If you want to change the values of your variables, use the assignment operator = instead of ==.
Assignment:
Return the number of occurrences of character c in string s,
ignoring case. Use loops. Do not use the in-built string method count,
which does a similar thing. The idea is to learn to write loops. You
should ignore case when comparing a character of s with c.
My attempt:
def countletter(s, c): #BAD
count = 0
for c in s:
if c == c:
count += 1
return count
Am I on the right track? I seem to get some assertion errors when I test it in the main...
your return is at wrong place. So your function is actually returning only after one iteration.
Also you should not use the variable name c in for loop, use some different variable, as it replaces the value of c recieved from the function call with the current character being fetched by the for-loop.
def countletter(s, c): #BAD
count = 0
for x in s:
if x.lower() == c.lower():
count += 1
return count
print countletter("abcdefFf","F") #prints 3
print countletter("a","A") #prints 1
In addition to the answers above, there is a built-in method count in Python. You can use it in your project, if this function isn't a homework etc.(Oh, i saw now, it is an homework. But additional information is harmless.:) )
"baris".count("b")
returns 1
If you compare the variable c defined by for c in s: you are always going to get true. So, your comparison should look like c == 'c' (you can figure out how to do the case insensitive check) and your return is indented incorrectly
The position of the return statement is wrong. Delete the four spaces (or a tab what you've used)
Just as another example of a way to do this outside of the built-in count() method, one can use a generator expression and the sum() builtin:
>>> def countletter(s, c):
... return sum(x.lower() == c.lower() for x in s)
...
>>> countletter("abcdefFf", "F")
3
>>> countletter("a", "A")
1
What we do is produce a generator of True and Falses (True where the character matches). sum() will then give us the count, as True is 1 in Python, and False is 0:
>>> True == 1
True
>>> False == 0
True