Fgad 118
Fgad 118
Fgad 118
Logical Operator
For Loops
Reynaldo G. Alvez
Boolean logic expressions, in addition to evaluating to True or False, return the value that was
interpreted as True or False.
It is Pythonic way to represent logic that might otherwise require an if-else test.
And operator
The and operator evaluates all expressions and returns the last expression if all expressions
evaluate to True. Otherwise it returns the first value that evaluates to False:
>>> 1 and 2
2
>>> 1 and 0
0
>>> 1 and "Hello World"
"Hello World"
>>> 1 or 2
1
>>> None or 1
1
>>> 0 or []
[]
Lazy evaluation
When you use this approach, remember that the evaluation is lazy. Expressions
that are not required to be evaluated to determine the result are not evaluated.
For example:
This example is trying to check if two variables are each greater than 2. The
statement is evaluated as - if (a) and (b > 2). This produces an unexpected result
because bool(a) evaluates as True when a is not zero.
a=1
b=6
if a and b > 2:
print('yes')
else:
print('no')
Correct logic should be each variable needs to be compared separately.
a=1
b=6
if a > 2 and b > 2:
print('yes')
else:
print('no')
Python Loops
for loop and the range() function
The range() function returns a list of consecutive integers.
range(a) : generates a sequence of numbers from 0 to a,
excluding a, incrementing by 1.
Ex: for a in range(4): print(a, end=‘ ‘) output: 0 1 2 3
Note: By default python's print() function ends with a newline. ... Python's print() function comes with a parameter called
'end'. By default, the value of this parameter is '\n', i.e. the new line character. You can use end and print statement with any
character/string using this parameter.
The separator between the arguments to print() function in Python is space by default (softspace feature) , which can be
modified and can be made to any character, integer or string as per our choice. The 'sep' parameter is used to achieve the
same, it is found only in python 3. x or later.
range(a,b): generates a sequence of numbers from a to b
excluding b, incrementing by 1.
#for application1
successful = False
for number in range(3):
print("Attempt")
if successful:
print("Successful")
break #terminate the block
else:
print("Attempted 3 times and failed")
Suggested Videos
https://www.youtube.com/watch?v=xtXexPSfcZg
https://www.youtube.com/watch?v=fBIvTEOTzvs