"if" statements not working - outputting certain code always user-input - python

No matter what it always outputs Spammer().
option = int(input("Enter the what you want to do: "))
<insert code not relevant>
if option == 1 or 'spam'.upper():
Spammer()
elif option == 1:
pcInfo()
Python 3.9.7
I've looked through several posts and nothing has worked.
edit: The typo was made while typing the code into StackOverflow. To fix the if statement I wrote it again but without ctrl-c and ctrl-v and it somehow worked.

'spam'.upper()
will always return
SPAM
which is a non-empty string and therefore is regarded as a truthy statement by Python.
Since an if statement checks for truthy expressions, the if block will always be triggered.
If you need more help, please specify what you actually intend to with that statement.
Also: The else if block contains the same condition as the if block which I suppose is a typo? Otherwise if would always catch that case first and then skip over else if in all cases. So you should definitely use another value of the else if statement.

As 'spam'.upper() will return 'SPAM',
which will always give True.
also, the pcInfo() will never execute,
as it has the same condition (option == 1) as the one above.

Related

How to run a function in a single line if statement

I have this if statement i am trying to convert into a single line to be used in a terminal shell, but cannot seem to get it to work.
Essentially the code sort of looks like this:
import module
if condition:
module.runCustomMethod()
else:
pass
so i tried to write this like so:
import module;module.runCustomeMethod() if condition == True else pass
but no matter how i arrange it, it always gives me a syntax error. how would i go about running a method in this way?
What you're trying to do is pretty ugly, and there are better ways to do it, but…
import module;module.runCustomeMethod() if condition == True else pass
The problem here is that pass is a statement, and Python expressions can never contain statements.
Since you're not using the value of the expression, you can replace that pass with any expression that's harmless to evaluate:
import module;module.runCustomeMethod() if condition == True else None
Now there's no SyntaxError in your code. Although it's still not going to work, because that condition isn't defined anywhere, so it's just going to raise a NameError instead. But if that isn't a problem in your real code, this will work.
As a side note, you almost always just want if condition, not if condition == True. Only use that if you specifically only want to accept True and reject other truthy values like 1.
If you're doing this in a sh script, the cleanest solution is probably this:
python <<EOF
import module
if condition:
module.runCustomeMethod()
EOF

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.

Ternary using pass keyword python

I have a working conditional statement:
if True:
pass
else:
continue
that I would like to turn it into a ternary expression:
pass if True else continue
However, Python does not allow this. Can anyone help?
Thanks!
pass and continue are a statements, and cannot be used within ternary operator, since the operator expects expressions, not statements. Statements don't evaluate to values in Python.
Nevertheless, you can still shorten the condition you brought like this:
if False: continue
Point 1: Are your sure your condition is right? Because if True will always be True and code will never go to else block.
Point 2: pass and continue are not expressions or values, but a action instead You can not use these is one line. Instead if you use, 3 if x else 4 <-- it will work
Ternary expression are used to compute values; neither pass nor continue are values.

Code Academy, Conditionals and Control Flow Grand Finale

I'm using Code Academy and I began with Python. For the "Grand Finale" of Conditionals and Control Flow and this is the problem:
"Write an if statement in the_flying_circus(). It must include:
if, elif, and else statements;
At least one of and, or, or not;
A comparator (==, !=, <, <=, >, or >=);
Finally, the_flying_circus() must return True when evaluated.
Don't forget to include a : after your if statements!"
and I know this is the format:
def the_flying_circus():
if condition:
# Do Something!
elif condition:
# Do Something Else!
else condition:
# Do yet another thing!
Firstly, I don't know what exactly it means by conditions. I thought it meant condition using comparators in relation to the_flying_circus, but that showed an error message. Am I supposed to define the_flying_circus? If not is it already defined, and how would I know the definition? It says it's an invalid syntax error. Secondly, with the "#Do Something" I think I'm supposed to use strings, so a certain script shows up if the_flying_circus fulfills one of the 3 certain conditions, but since I can't figure out what to write for the conditions I don't know. Also, Code Academy did give an overview of if, elif and else statements, but I'm still shaky on the concept. An overview with a simplified example of what this would be used for in real life would be greatly appreciated.
In all languages a condition is some expression that can evaluate to a boolean expression i.e 1<2 or anything else so lets take a look at the following code
def the_flying_circus():
x = True
if True and x:
print "x is true"
if 2 < 1:
print "The universe is ending"
elif 2>1:
print "Ok sanity"
else:
print "the sky is falling"
return True
So each conditional statement checks whether or not a condition is true, and evaluates the following statement at the end. Lastly return True so the method condition is satisfied.
Something like
def the_flying_circus():
if 1>2 or 2==3:
return False
elif 4<3:
return False
else:
return True
You are defining the_flying_circus as a function. It uses > == and < as comparators. It has if, elif, and else. It returns True.
The conditions are the things that could be true or false but have to be checked by the if/elif statement. "4<3" is a condition. It evaluates to false.
The "#Do something" comments could be anything. Print something, return something, call some other function, etcetera.
Maybe some kind of beginner's tutorial on if statements? Plenty through google.

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