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.
Related
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.
Sometimes inside one function we need to use the return statement several times.
When developer changes a function with multiple returns inside, it's easy to oversee some parts of code where yet another return was "hidden".
If unit tests do not cover all possible paths, disaster is guaranteed - it's only a question of time.
def my_function():
'''Multiple "return" inside'''
if condition 1:
return 1, 2, 3
if condition 2:
return 2, 3, 4
return 5 # this is wrong: only 1 value returned, while 3-tuple expected
Let's assume here: last return is wrong, because other callers expect tuple of 3 items.
I wonder if you know an easy way how to catch such parts of code automatically? I thought I could use AST, but I could not find any useful example of this.
This question is about automatic code analysis and listing such cases found - could be with running a separate script.
Of course I could write a try-to-guess parser (with e.g. regex) and then 'manually' check all unclear cases, but maybe there is a simpler way...
Depending on what version of Python you're using and what you really want to achieve, there are several ways to refactor the code.
One way, as has been already suggested, is to use Type Hints in Python 3.
Another way is refactor your code such that instead of using multiple return statements, you call other more atomic methods that handle those conditions and return the appropriate values. You use exception handling in those atomic methods to make sure the output is as desired, or raise an exception if final return type is unexpected.
def my_function():
'''Multiple "return" inside'''
if condition 1:
output = func_handle_condition_one()
if condition 2:
output = func_handle_condition_two()
output = some_other_value
if type(output) is not tuple:
raise TypeError("Invalid type for output")
return output
Additionally, ensure that you're using the right constructs for your conditions (such as whether you want to use multiple if or the if-elif-else construct). You could even re-factor your calling code to call the right function instead of calling one that has so many conditional statements.
Why not set a variable that gets returned at the end and check for its length
def my_function():
'''Multiple "return" inside'''
return_value=(0,0,0)
if condition 1:
return_value=(1, 2, 3)
elif condition 2:
return_value=(2, 3, 4)
else:
return_value=5 # this is wrong: only 1 value returned, while 3-tuple expected
try:
if len(return_value)==3:
return return_value
else:
print("Error: must return tuple of length 3")
except:
print("Error: must return tuple")
My proposal for the final type check of the result would be:
assert isinstance(return_value, tuple) and len(return_value) == 3
Advantage: as assert is easily switched off after debugging phase; still succinct statement for formulating the expectation.
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.
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.
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.