Python Boolean error? - python

Ok so I'm creating a loop:
def equ(par1,par2):
con1=4/par1
ready=False
add=False
if ready==True:
if add==True:
par2+=con1
add=False
print("true")
elif add==False:
par2-=con1
add=True
print("False")
elif ready==False:
par2=con1
ready=True
input()
return par2
Every time I run the program it doesn't do what it's supposed to. I notice that it will NOT change ready to true. Could any one give me some help? THANKS! :)

First, you have no looping construct. You only have a linear flow of logic.
Second, ready==True will never be true, since it is explicitly set to False before that code block is ever hit.
If you're intending to reuse the boolean value ready, then you'd either want to preserve its state somewhere outside of the scope of the method - once you leave the method, it goes right back through and sets it to False again.

Related

Why statements after the while loop are not always executed?

I am very new to python and I have encountered the following code:
def function(array):
i = 0
j = 10
while i < j:
if array[i]!=array[j]
return False
i += 1
j -= 1
return True
I can't understand why the True value is not always assigned to the function no matter what happens in a while loop. The while loop just seems to check the if statement, and after finishing the loop, the True value should be assigned to the function anyway. But this code works as follows: the if statement checks for the condition and if it is true, we assign False to the function, if it is not true, we assign True to the function. But the assignment of True is not inside the while loop, so we should have assigned the True to function anyway, no matter what happens in while loop. I can't understand the logic here, can anyone enlighten me in this. Thanks a lot.
A return statement ends the execution of the function call and "returns" the result...
A return statement ends the function.
From https://www.python-course.eu/python3_functions.php
A return is used to hand the control of the program back to the calling function. So when you're in the while loop, and your condition in the if clause is evaluated to be true, your function terminates execution and the control of the program is handed back to the calling function. The only scenario in which your function will return true would be if the conditions in your if clause was never satisfied during the execution of your while loop.
Return exits the current function or method.
when you return False in if statement it will not continue the rest of the code and will always return false.
The condition is likely to have gotten executed before the rest of the loop has a chance to finish. When
if array[i]!=array[j]
is met, return False is called, exiting the loop and returning False.
This happens because
array[i]!=array[j]
is the condition that is met first, before the loop can finish and return with True.
Instead, you may want to 'skip' the part of the loop where this condition is met. If so, use the keyword
continue
This 'skips' the current iteration to the next one, and will continue on with your loop.
Code as follows:
while i < j:
if array[i]!=array[j]:
continue

The for-loop only loops once, so it's like there was no loop used

so first thing I'm new to python and I came across a simple problem but still complicated. Basically I try to loop all of the things from a list, and make them go through a conditional check if there the ones.
This is to check if a sentence is a greeting.
greets = ["Hi","Hello", "Hey"]
#Thinking
def isGreet(mes): #Checks if it's a greeting
words = mes.split()
for greet in greets:
print(greet)
if (words[0]==greet):
return 1;
else:
return 0;
When a user types in something, the code should check if it's a greeting, and if it is, return true, and if it's not return false. Simple, isn't it? But when I type in something, the code only returns true if it's hi which is used, but when i type let's say hello there, it would return false. I added a print function to see if loops works, but it only prints Hi, so I concluded that there must be something wrong with the for loop. Reaally appreciate any help.
The for-loop only loops once, so it's like there was no loop used
yes, because you're returning from the function no matter what at the first iteration. So your test works if the first word tested is the first in the list only. Else it returns 0.
no need for a loop, use in
greets = {"Hi","Hello", "Hey"} # set should be faster, only if a lot of words, though
def isGreet(mes):
return mes.split()[0] in greets
as stated in comments, mes.split()[0] is somehow wasteful because it keeps splitting other words we don't need, so replace by mes.split(maxsplit=1)[0] or mes.split(None,1)[0] for python 2.
I am assuming that you expect the greeting to be the very first word. In that case you can do it in 1 line:
isGreet = True if mes.split(maxsplit=1)[0] in greets else False

Updating only the first occurrence of an object in a queue with python without break

I created a function in python that will change the priority for the first occurrence of an object, but im having trouble fixing it so that it would only work for the first occurrence without the use of break. In my code below I have used break and it works as intended but I would like to not use it.
def update_priority(self, object, priority):
for i in range(len(self._queue)):
if object == self._queue[i].get_item():
# checking object already has that priority
if priority == self._queue[i].get_priority():
# dont change if it has the priority
pass
# if the object does not have that priority set to new
else:
self._queue[i].set_priority(pri)
break
else:
pass
It sounds like you also want to learn how to reduce the length of the code. A rule of thumb is to concentrate on making your code clear and concise first, so you can try to identify ways to simplify the structure. For example, you can restructure and remove redundant branches. Many of your cases are just passes. Also, yes, college classes say that break statements aren't great. For clarity, you might want to use a conditional variable to end the loop. In this case, you don't really need to do that, but an alternative is to wrap the code in a function and bypass the rest of a loop simply by returning, You already use a function, so you can just return from the function if all you do is update the one item's priority (and exit). Perhaps you want to return a status code indicating that an item was found or not. (True or False).
def update_priority(self, object, priority):
# check all items in the queue (you do not require the index.)
# the entry is stored in "entry"
for entry in self._queue:
# if you find the object and its priority needs an update
if object == entry.get_item() and priority != entry.get_priority():
# set the priority
entry.set_priority(priority)
# return true for success, you found the object and updated it
return True
""" If you arrive at this line, the object didn't exist or
it didn't need an update (if you need to distinguish between "object not found" and
"object found but didn't update," use an extra flag or nest the != entry.get_priority as you did before"""
return False
Your solution is correct you do not need to change it so it doesnt use break. There is no other way to end a loop unless its a while loop and the condition is false or you reach the end of range in a for loop.

Why do we not need "else" in an if-statement if it contains "return"?

I'm a beginner in Python, and I can't understand why we don't have to use else in cases like the one below:
def find_element(p,t):
i=0
while i<len(p):
if p[i]==t:
return i
i=i+1
return -1
In this code I thought I should use else return -1 if I wanted to return -1, but it seems that python understands this without else like in the code above.
Return terminates a function. Basically, if the "if" condition is satisfied within the "while" loop, the function will end. Alternatively, if the "while" loop is permitted to complete ("if" condition fails), then you force a return value. In this instance, you do not want an "else" statement if you expect to iterate through your entire "while" loop.
Well, in the exact case you provided, it's because you're "returning" after a match. Once a function returns, no code after the return is executed meaning if you ever pass the if conditional, the method breaks out of the loop and everything, making the else unnecessary.
Essentially: you don't need an else because if your conditional ever passes the code execution breaks out of method anyways.
You do not need else because you if the element t is found return i yields the index, otherwise you exit loop without encountering t, return -1 will be executed. But feel free to add else pass if it make you more comfortable.
As explained above, else: return -1, is an error, with such else clause the function will only the check the first element of the list being t
In Python the indentation decides the scope, so the return -1 is actually outside of the while loop. Your code will return -1 only if t is different from all p.

Does this Python expression make sense?

I found this kind of expression several times in a python program:
if variable is not None:
dothings(variable)
It seems strange to me, and I think that it has no more sense than:
if variable:
dothings(variable)
Maybe I don't know Python enough, and the expression is explained somewhere?
variable could be 0, or False, or [], or (); be 'falsy' in other words, and then the if statement would be skipped.
See Truth testing for more detail on what is considered false in a boolean context.
In short, testing if variable is not None allows variable to be anything else, including values that would otherwise be considered False in a boolean context.
Some values are falsy, but are not None. You may still want to dothings() to those values.
Here are the things that are falsy in Python 2. (You may want to change the '2' in the URL to a '3' to get the values for Python 3, but it didn't change much.)
E.g.
i = 0
if i is not None:
print i # prints i
if i:
print i # prints nothing
In the google voice python implementation I came across this as well, their use was during a function call. The parameters are defaulted to "None" and then when the function is called they can check if the values are changed or the default.
I.E.
def login (user=None, password=None)
if user is None:
user = input('Please enter your username');
...
return <something>;
called by
login()
OR
login(user='cool_dude')
OR
any combination of user/password you wish.
Additionally your "update" of the logic implies that variable == true or false. That is not correct for all cases (it may work in some cases but I'm throwing them out, since it's not a general case). What you are testing by using the "NONE" logic is whether the variable contains anything besides NONE. Similar to what I was saying above, all the "login function" was doing was determining if the user passed anything, not whether the value was valid, true, etc.

Categories