Week 7 First Year
Week 7 First Year
Statements with logical operators evaluate to a Boolean value (true or false). Such
statements are known as conditions or predicates. Statements that test for:
Equality A == B
Not Equal A != B
Greater Than A>B
Greater or Equal A >= B
Less Than A<B
Less or Equal A <= B
Example:
A=5
B=2
The operation Syntax in python The result
Equal A == B False
Not Equal A != B True
Greater A>B True
Less A<B False
Greater or Equal A >= B True
Less or Equal A <= B False
Boolean Operators
The logical operators AND, OR and NOT are also referred to as Boolean operators.
(AND) and (OR) operators need two operands, which may evaluate to true or false,
(NOT) operator needs one operand evaluating to true or false.
AND operator returns true if both operands return true
A=50 b=25
1
OR operator returns true if any one operand is true
NOT operator inverts the value (not (true) = false) and (not (false)= true)
If statements
In computer programming, if statement is used to run a block of code only when a
certain condition is met.
For example, assigning grades (excellent, very good, good) based on marks obtained
by a student.
if the percentage is above 85, assign grade excellent
if the percentage is above 75, assign grade very good
if the percentage is above 65, assign grade good
2
Syntax of Python If
Observe the empty space provided for statement(s) inside if block and the
colon : after Boolean expression.
If the Boolean expression returns true, the statement(s) of the if block are executed.
Else, the statement(s) are not executed, and the program execution continues with the
statements after if statement, if there are any.
Example 1: when the condition is true
No result
1. If … else statement
Python If Else is used to implement conditional execution where in if the condition
evaluates to true, if-block statement(s) are executed and if the condition evaluates to
false, else block statement(s) are executed.
3
Syntax of Python If … else
4
For loop
In any programming language loops are very important to repeat any operation(s) as
must as the programmer wants. For example, if we want to find the summation of all
numbers between (1: 1000). Using loops, this code can be written in few lines.
In Python programming, the for loop also has the ability to iterate over elements of
sequential data types, such as strings or lists.
The range is from 1 until 6. So, the range has items: 1, 2, 3,4 and 5. The statements
inside the for loop are executed for each of these elements.
5
Example 2: For Loop with List
End Next
Example 4: For Loop to print the sum of the numbers from 1:11
Sum=55
6
Exercises:
Write a python code to print even numbers from 1 : 20?
Write a python code to print the sum of the numbers from 20:50?
Write a python code to print the odd numbers from 1 : 100?
Write a python code to print each letter in your name by itself?
Write a python code to find the average of all numbers between 1: 15?
7
Practical Part
8
9
10
11
12
13
14
15