Download Python Loops & Conditionals: Relational, Assignment & Boolean Operators, Syntax Rules and more Study notes Logic in PDF only on Docsity!
Loops and
Conditionals
HORT 59000 Lecture 11 Instructor: Kranthi Varala
Relational Operators
- These operators compare the value of two ‘expressions’ and returns a Boolean value.
- Beware of comparing across data types, especially when reading values in from command line or files.
Assignment Operators
- A += B increase A by value of B
- A - = B decrease A by value of B
- A *= B multiply A by B and assign value to A
- A /= B divide A by B and assign value to A
- A **=B raise value of A to the power of B
- A %= B modulus of A by B, assigned to A
- A //= B floor of A divided by B, assigned to A
- String context:
- S 1 += S2 add string on right to the one on left
- S1 *= A Make A copies of S1 and concatenate them to S
Boolean Operators
Combines two or more statements that return a Boolean value. A and B True if both A and B are true A or B True if either A or B is true not A reverse the Boolean given by A xor(A,B) True if only one of A or B is True A B A and B A or B Not A xor(A,B) TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE TRUE FALSE FALSE FALSE FALSE TRUE FALSE
Branching logic
- Used to implement alternate paths for the logic flow. https://upload.wikimedia.org/wikipedia/commons/4/44/LampFlowchart.png
If/elif/else statements
if test1: statement 1 elif test2: statement 2 else: statement 3
- Both the elif and else blocks are optional.
Lamp flowchart with if/else
Accepts input from user, as a string
Truth and Boolean tests in Python
- All objects in python have an inherent true or false value.
- Any nonempty object is true.
- For Integers : Any non-zero number is true
- Zero, empty objects and special object ‘None’ are false.
- Comparisons return the values True or False
while loops
- while condition: statement 1 statement 2 . .
- Most generic form of loop, that checks whether the condition is true at the start of each iteration.
- Expects the condition to become false at some point during the iterations of the loop.
- If condition is never changed, this creates an ‘infinite’ loop. i.e., the program will get stuck in this loop for ever.
Example while loops
Altering while loops
for loops
- for item in sequence: statement 1 statement 2 . .
- Generic iterator for items in a ordered sequence such as lists, tuples etc.
- On each iteration retrieves one item from the list and assigns it to the variable specified.
- Automatically moves to the next item in the order.
- Value of variable may be altered within the for loop, but change is not made in the list.
Looping over Strings and Lists
- List is a general sequence object while String is a character sequence object.
- Both can be iterated over by a for loop:
Looping over lists with and without index
- Looping with an index allows accessing the item within the list and changing it.