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.
Related
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.
I have a two-line code like this:
if validated_data.get('is_shipped') == False: # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)
I am using Pycharm and the PEP8 check is on. So there is an underline below validated_data.get('is_shipped') == False which shows me Expression can be simplified. Replace boolean expression with ``not validated_data.get('is_shipped')`` . But, the truth is, I only want to run code in if statement when is_shipped is explicitly passed as False, and not when is_shipped is None. So, how can I handle this PEP8 check warning?
You hit the solution in your question: use the explicit is operator:
if validated_data.get('is_shipped') is False:
This makes your condition an explicit identity, rather than the "truthy" boolean evaluation.
Here x == False is equivalent to not x, and I don't know why do you want to only use x == False and PEP8 suggests that:
if not validated_data.get('is_shipped'): # 管理员取消了发货,则把物流信息删掉
validated_data.update(logistics_company=None, logistics_tracking_no=None)
I can't use if statements and loops in my assignment so I was wondering how I would rewrite this line:
if (not float(gravity).is_integer()):
It's just checking to see whether or not gravity is a float or integer so it can pass more code.
My guess is that the assignment is trying to teach you a paradigm of "Ask forgiveness not permission".
In that case:
try:
gravity = float(gravity)
# Do floaty gravity stuff
except (TypeError, ValueError):
gravity = some_default_value_you_can_handle_some_other_way
You can use shortcut operators to achieve logical flow without an if statement.
E.g.
float(gravity).is_integer() and do_stuff()
The second part will only execute if the first part is true.
Alternatively you can use
float(gravity).is_integer() or do_stuff()
where the second part will only execute if the first part is false.
UPDATE
I just read the comment about how the function is simply meant to evaluate if two sides yield an integer hypotenuse. So unless I misunderstood what you're after here, in that case, the whole point is that you don't need an if statement to decide whether you should then explicitly return True or False by yourself; you can simply return the output of the evaluation of is_integer() directly, since this will evaluate to either True or False anyway.
You could use assert in combination with a try block:
try:
assert(not float(gravity).is_integer())
print("evaluated to true")
except:
print("evaluated to false")
Replace the print statements with the code you want to execute in case it evaluates to true or false.
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.
I'm using argparse.
def help():
parser.print_help()
sys.exit(0)
help() if (args.lock and args.unlock)
This gives me a syntax error. What is wrong with my if statement?
You are using a conditional expression: true_result if condition else false_result. A conditional expression requires an else part, because it has to produce a value; i.e. when the condition is false, there has to be an expression to produce the result in that case.
Don't use a conditional expression when all you want is a proper if statement:
if args.lock and args.unlock: help()