Code Academy, Conditionals and Control Flow Grand Finale - python

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.

Related

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

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.

Boolean in python

a=True and 1/0
print(a)
The output for the above code fragment shows an error.
While the output for the below code fragment :
a=False and 1/0
print(a)
Is False
Why is that so? From the layman point of view, since 1/0 is undefined, error should be displayed in each case.
Similarly if I take a = True or 1/0, output is true while an error for False or 1/0
I tried different versions of this:
a=1/0 or False
print(a)
or
a=1/0 or True
print(a)
Both of which display an error (division by zero)
I realized that it has something to do with the order I take them in and the boolean operators I use.
In any case, why am I getting an output and in some cases?
Both and and or are short circuited i.e. if the first input is respectively false or true, the rest of the inputs are not evaluated at all. That is why both False and 1/0 as well as True or 1/0 can return results, while other variations do not.
Python exhibits short-circuit evaluation semantics for and and or expressions. What that means is that, if the result of the entire expression can be determined from the left-hand-side, then the right-hand-side needn't be evaluated.
False and a
Here, we first evaluate the expression False (which is a literal and equal to the Python value False). Now, and is only true if both sides are true, and we've already found one side which is false. So no matter what a evaluates to, the result is False. Hence, we don't evaluate the right-hand-side because it's unnecessary.
Likewise,
True or a
Since True is truthy and or only requires one of its arguments to be truthy, whatever a evaluates to, the result is True.
This is commonly used to do several veins of error checking in one line. Python doesn't have a null-safe access operator, so we can do the next best thing.
if person is not None and person.salary is not None:
...
Without short-circuit evaluation, the person.salary is not None would evaluate, even in the case where person is actually None, which is an error. We'd have to write the more verbose
if person is not None:
if person.salary is not None:
...
which does nothing for readability.
Likewise, we can use or to short circuit error conditions.
if person is None or person.salary is None:
raise(MyCustomException("This person doesn't have a job"))
Again, if person happens to be None, we don't want person.salary to evaluate at all, or we'll get an AttributeError rather than our nice, informative custom exception. Without short-circuiting, we'd have to resort to the much uglier
if person is None:
raise(MyCustomException("This person doesn't have a job"))
if person.salary is None:
raise(MyCustomException("This person doesn't have a job"))
In case of False, It is not necessary to check more after and - it is due to the optimization, so 1/0 is never executed.
On the other hand: a=1/0 and False will not work as 1/0 is evaluated first.
and operator stops when a False is encountered to save resources.
Here:
a=False and 1/0
Division is never computed.
The same you can check with or operator: it stops when True is validated:
a=True or 1/0
Will give True.

Replacing an if-statement

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.

Return True/False - when to use it over just return

I have searched over internet why i should use return False/True over just return but can not find the answer.
Why would i want to have statement return True/False inseatd of just return ?
Can you please show me an example ?
def test(var):
if var > 5:
return True
else:
return False
test(8)
>>> True
#------------------------
def test(var):
if var > 5:
return
else:
return
test(8)
>>> None
Analogy: A function is a cloneable assistant ready to perform a task, and give you an answer. The task is defined by the parameters of the function (the stuff inside the parentheses). Let's rewrite the names to give them semantic meaning (i.e. names which illustrate what we expect).
def isXGreaterThanY(.....
Here, the name of the task is "is X greater than Y?". If you go up to your cloneable assistant and ask "is X greater than Y?", your assistant will not be able to accomplish what you want unless you tell them what X and Y are.
def isXGreaterThanY(x, y):
.........
Now I can start to explain where you may be going wrong. One error at this level of programming is that just because you see something that does almost what one wants on a webpage, one may be tempted to copy it syntactically and try to fiddle around with the syntax and hope it will just work. This will never work. It is not the point of programming.
Some everyday people think that programming is about magic words (not that I am implying you think that) that solve your problem. This is not the case. Rather, programming is (classically) about being able to make automatons (these little assistants) which manipulate information for you. The rote, mechanical manipulation of information is what computers are good at. We want our tasks to be replicable though, so we give them names like "is X greater than Y?", and specify them in what is known, aptly, as procedures (a.k.a. functions).
Let's consider what you wrote:
def isXGreaterThanY(x, y):
if x > y:
return True
else:
return False
A procedure is all about control flow. Each part of the procedure is either a statement or expression (which you can, at this level, consider to be the same thing). A procedure usually has an answer: whenever control flow hits a "return ANSWER" statement, the entire procedure stops (the task is finished) and your magical assistant returns to you with the answer on a piece of paper with ANSWER written on it. A procedure which returns an answer is known as a 'function', and this is almost always what we want (procedures which do ugly 'side-effects' behind the scenes are usually not what we want).
Below, I illustrate the idea that takes us from syntax (what we write down) to mechanical actions. A procedure is made up of syntactic expressions, and each expression may have subexpressions, etc.
We have the if __ then __ else __ statement, which consists of three subexpressions:
the query clause of x > y, which consists of:
the _ > _ operator acting on:
the variable x
the variable y
the "then" clause of return True, which consists of:
the return statement, returning:
the literal boolean value True
the "else" clause of return False, which consists of:
the return statement, returning:
the literal boolean value False
This 'syntax tree' is what the computer sees. Now, the programming language associates meaning to these expressions: it knows how to navigate this tree in what is known as "control flow". In particular, in the programming language Python, we know that when we see an if-then-else statement, that first we check the test condition. In this case we look at the test condition and notice it is a naked comparison (we ask the CPU, and it gives either True or False back). If the comparison is true, we will do the "then" clause, which returns; i.e. hands you a slip of paper with the answer True. If the comparison was false, we'd do the "else" clause, and hand you a slip of paper with the answer False.
In this way, whenever you ask your assistant "is X greater than Y? where X=... and Y=...", your assistant will (in effect) look at the instructions you've specified in the procedure, and interpret them with the assistant's eye being always fixed on one expression at a time (the "control flow" can be thought of as a highlighted or underlined 'active' subexpression, i.e. control flow is the path your assistant's eye takes while looking through the code). In this particular case, your procedure begins with an if-then-else clause, which it interprets as a branching point in the control flow (a fork in the road); it takes the appropriate branch, and in this case, will discover one of the two 'return' statements, and then dutifully give you a slip of paper.
Control flow is determined by the semantics (meaning) behind special control-flow statements, such as if-then-else. Other control flow structures are interpreted differently. for x in range(7): ... will pretend x is 1 and execute ..., pretend x is 2 and execute ..., etc.
A while True: ... will loop forever, performing the ... over and over again.
A break (break out of) means "stop the while loop" or "stop the for loop prematurely".
A continue means "skip the rest of the ... in this while/for loop, but keep on looping".
You can implement your own control flow using the above and your own custom functions, with what is known as recursion (another topic outside this answer's scope).
That is control flow and imperative programming in a nutshell.
By the way, it is better form to do this:
def isXGreaterThanY(x, y):
# this is a comment
# you can insert a print x>y here, or print(x>y) depending on your version of python
return (x > y)
The expression x > y evaluates to True/False before it's fed into the if-then-else statement. So, you could just return the expression as the answer. However, by that point, your function is simple enough that you wouldn't write a function answer:
#print isXGreaterThanY(1,3)
print (1 > 3)
One major problem is that your second function will return None either way. Returning a boolean value is a way to have the return value of your function be meaningful/useful elsewhere.
If it returns a value like True or False, you can in turn use the return value of your function in cases like:
if test(8):
# do something it returns True
else:
# do something otherwise
Otherwise, you function is meaningless because test() will return the same thing regardless of input.
I was once told that a function should either "do something" or "return something". Your second example function, doesn't "do anything", because the > comparison has no effect if you are not making some choice based on the results of that comparison. It also doesn't really return anything (at least not anything meaningful) because it will return None no matter what - in fact, even if you remove the return keyword, it will still just return None.

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.

Categories