0% found this document useful (0 votes)
6 views

Module3 - Variables, Expression and Statement(1)

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module3 - Variables, Expression and Statement(1)

Uploaded by

Blossomlove12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

COMPUTER PROGRAMMING I

VARIABLES, EXPRESSIONS AND STATEMENTS

COURSE CODE:
(COS201)

COURSE LECTURERS

1 Dr. Olaniyan Deborah


2 Dr. Julius Olaniyan

First Semester
2024/2025 Session
OUTLINE
 This Module familiarises the students with Python
 variables,
 Operators
 arithmetic operators,

 boolean operators,

 assignment operators,

 statements, and
 expressions,
 a user can get input from the keyboard.
2
OBJECTIVES
 By the end of this module, students should be able to:
a) explain Python programming basics (variables, operators,
assignment statements, and expressions);
b) write programmes using Python programming basics
(variables, operators, assignment statements, and
expressions);
c) apply various basics (variables, operators, assignment
statements, and expressions) in Python;
d) design and implement programming problems using
arithmetic operators;
e) design and implement programming problems using boolean
operators;
3
f) describe how to get inputs from the keyboard
VARIABLES
 A variable is a named place in the memory where a
programmer can store data and later retrieve the data
using the variable “name”.
 Variables are nothing but reserved memory locations to store
values. This means that when you create a variable, you reserve
some space in memory.
 Variables need not be declared first in Python. They
can be used directly.
 Variables in Python are case-sensitive, as are most of
the other programming languages. 4
5

VARIABLES
a=10 a,b,c=2,40.3,”NUC CCMAS”
A=20 print(b)
print(a)
print(c)
k=10
k=20 print(a)
print(k)
5
6

NAMING CONVENTION
There are certain rules we have to follow when
picking the name for a variable:
 The name can start with an upper- or lower-case alphabet.
 A number can appear in the name but not at the beginning.
 The _ character can appear anywhere in the name.
 Spaces are not allowed. Instead, we must use snake_case to
make variable names readable.
 Special characters are not allowed.

6
NAMING CONVENTION 7

The name of the variable should be something


meaningful that describes the value it holds instead
of being random characters.
Examples:
v Good: Spam eggs spam23 _speed

v Bad: 23spam #sign var.12

v Different: Spam Spam SPAM


7
RESERVED WORDS AND KEYWORDS
 In a computer language, a reserved word is a word
that cannot be used as an identifier, such as the
name of a variable, function, or label – it is
"reserved from use".
 Keywords are predefined words in a programming
language with a specific use. Additionally, we use
them to define the structure and flow of a program.
 In other words, a keyword word is a special word only in
certain contexts, but a reserved word means a special word
that cannot be used as a user-defined name.
8
RESERVED WORDS AND KEYWORDS
 Python has the following keywords:

False class return is finally None if for lambda


continue True def from while nonlocal and del
global not with as elif try or yield
Assert else import pass break except in raise

9
ASSIGNMENT
 A value can be assigned to a variable through the
= operator.
 A big advantage of variables is that they allow us to store
data so that we can use it later to perform operations in the
code.
 The value of a variable can always be updated or replaced

because they are mutable. Hence, you can change the


contents of a variable in a later statement.
 x=20.6

 y=11

 x=99

 print(x) 10
OBJECT IN PYTHON
Objects are variables that contain data and functions that can be
used to manipulate the data.

The object's data can vary in type (string, integer, etc.) depending on
how it's been defined.

An object is like a mini-program inside Python, with its own set of


rules and behaviours.
11
EXPRESSIONS AND STATEMENT
 An expression is a combination of values, variables, and operators.
If you type an expression on the command line, the interpreter
evaluates it and displays the result:
 Although expressions contain values, variables, and operators,
not every expression contains all of these elements. A value all by
itself is considered an expression, and so is a variable.
 The evaluation of an expression produces a value, which is why
expressions can appear on the right-hand side of assignment
statements. A value all by itself is a simple expression, and so is a
variable.
 A statement is an instruction that the Python interpreter can
execute. We have seen two kinds of statements: print and 12
assignment.
EXPRESSIONS AND STATEMENT
 When you type a statement on the command line,
Python executes it and displays the result, if there is
one. The result of a print statement is a value.
Assignment statements don't produce a result.
 A script usually contains a sequence of statements. If there
is more than one statement, the results appear one at a
time as the statements execute.
 print(1)
 y=6

 print(y) 13
EXPRESSIONS AND STATEMENT
 Again, the assignment statement produces no output.
 Some other kinds of statements that we’ll see shortly are
 while statements,
 for statements,

 if statements, and

 import statements.

14
 There are other kinds too!
ARITHMETIC OPERATORS AND EXPRESSION

 Arithmetic operations in Python can be


performed by using arithmetic operators and
some of the in-built functions.

 Operators are special tokens that represent


computations like addition, multiplication and
division. The values the operator uses are
called operands. 15
ARITHMETIC OPERATORS AND EXPRESSION

16
ARITHMETIC OPERATORS AND EXPRESSION

17
ARITHMETIC OPERATORS AND EXPRESSION
CLASS WORK

18
ORDER OF OPERATIONS

 When more than one operator appears in an expression, the


order of evaluation depends on the rules of precedence.

 Python follows the same precedence rules for its mathematical


operators that mathematics does. The acronym PEMDAS is a
useful way to remember the order of operations:
1. Parentheses have the highest precedence and can be used to force an
expression to evaluate in the order you want
2. Exponentiation (raise to a power) has the next highest precedence
3. Multiplication and both Division operators have the same precedence,
which is higher than Addition and Subtraction, which also have the same
precedence.
4. Operators with the same precedence are evaluated from left to right.
19
ORDER OF OPERATIONS 20

This example prints the results of the various operations (sum, subtraction, multiplication, division,
floor division, modulo and power) performed on variables x and y.

# Define the variables # Print the results


x = 10 # You can change this value print(f"The sum of {x} and {y} is: {addition}")
y = 3 # You can change this value print(f"The difference when {y} is subtracted from {x} is: {subtraction}")
print(f"The product of {x} and {y} is: {multiplication}")
# Perform arithmetic operations
print(f"The result of dividing {x} by {y} is: {division}")
addition = x + y
print(f"The floor division of {x} by {y} is: {floor_division}")
subtraction = x - y
print(f"The remainder when {x} is divided by {y} (modulo) is: {modulo}")
multiplication = x * y
division = x / y # Regular division print(f"{x} raised to the power of {y} is: {power}")
floor_division = x // y # Floor division (integer division)
modulo = x % y # Remainder of the division
power = x ** y # x raised to the power of y 20
ORDER OF OPERATIONS
 Anarithmetic expression containing different
operators will be computed on the basis of
operator precedence.

 Whenever operators have equal precedence,


the expression is computed from the left side:
21
ORDER OF OPERATIONS
1 # Different precedence
 print (10 - 3 * 2) # multiplication computed
first, followed by subtraction

2 # Same precedence
 print (3 * 20 / 5) # multiplication computed first,
followed by division
 print (3 / 20 * 5) # division computed first, followed by

multiplication 22
ORDER OF OPERATIONS
 An expression which is enclosed inside parentheses will be
computed first, regardless of operator precedence:
# Different precedence

print ((10 - 3) * 2) #subtraction computed first, followed by


multiplication

print ((18 + 2) / (10 % 8)) #addition and Modulus are computed first,
followed by division
23
ASSIGNMENT STATEMENT
We assign a value to a variable using the assignment statement (=)
Syntax

A = 20
print(A)

This will assign value ‘20’ to the variable ‘A’ and will print it. Try it
yourself
An assignment statement may consist of an expression on the right-
hand side and a variable to store the result
x = 3.3 * x * ( 3 - x )
24
ASSIGNMENT STATEMENT
 The right side is an expression.

 Once the expression is evaluated, the result is


placed in (assigned to) the variable on the left
side (i.e., x).
 x=4 Assignment statement
 x=x+4 Assignment with expression
 print(x) Print statement
 The assignment token, =, should not be confused with equals, which uses the token = =. The
assignment statement binds a name on the left-hand side of the operator to a value on the
right-hand side.
25
ASSIGNMENT STATEMENT
 Increment and Decrement Operators
 Python uses + = and - = operators for incrementing and
decrementing, respectively.
 In Python, the augmented assignment operator += adds the
right-hand operand to the left-hand operand and assigns the
result to the left-hand operand.
 To increment a value, use
a + = 1

 to decrement a value, use


 a-=1
26
BOOLEAN EXPRESSIONS
 The Python Boolean Expression is a very vital part of
Programming with Python.
 They are used to represent truth values.
 When programming with Python, the Boolean expressions are
used to evaluate expressions and return a result which is either
True or False.
 The following example is a Boolean that Python uses to store
whether it is December:
 is_december = False
 Our parameter evaluated to False, indicating that it is not
December.
27
BOOLEAN EXPRESSIONS

28
OPERATORS AND MEANING

29
EVALUATING BOOLEAN EXPRESSION
 The Python Programming language has a built-in function that is
called bool(), which you can use to evaluate a variable or value.
This function, bool(), takes in one argument, which is the value or
variable you want to evaluate.

 The syntax for evaluating the bool() is given below:


 bool(value)

 When you want to perform a comparison, you can enclose it


within the bool() method, which in turn returns a Boolean value.
30
EVALUATING BOOLEAN EXPRESSION
 For example, if you want to know if a student has scored 40 or
more in the COS 201 examination. If so, you want to give a grade
of pass or fail. You could figure this out using the following code:

 students_score = 41
 print(bool(students_score >= 40))
 The output of our code is True.

 The above evaluation shows that the student has scored more
than 40 points in the COS 201 examination, so our statement 31

evaluates to True.
EVALUATING BOOLEAN EXPRESSION
 If we want to check if a value is empty, None, or False, we can use
the bool() method.
 This particular method converts a value into a Boolean according to
"standard truth" testing.
 You can use the method to convert integers or floating point
numbers to Booleans.
 For instance, we have some students preparing for the COS 201 examination, and we
want to check if the student has registered for the course in preparation for the
upcoming exam. This evaluation can be performed using the following lines of code:
 Registered_course = []

 print(bool(Registered_course))

 Our code returns False.

 In this case, our student has not registered for the course in preparation
for the upcoming examination, so our bool() method returns False. 32
SHORT-CIRCUIT AND COMPLETE EVALUATION
 Short-circuiting is a very vital aspect of Python
programming.
 It is the act of avoiding executing parts of a
Boolean expression that have no influence on the
final result.
 For instance, if you know already that A is False,
you can conclude that B and C is False no matter
what the outcome of the subexpression C is.

33
SHORT CIRCUIT LOGICAL AND
 The short circuit logical AND comes into play if
you want to evaluate the result of the logical
AND expression A and B, but you already know
that A=False.

 Because you know this, you also know that the


overall expression will be evaluated to False.
Therefore, the Python programming language
will skip the computation of the remaining
expression B and just return the result False.
34
SHORT CIRCUIT LOGICAL OR
 The logical OR comes into play if you wa n t to
evaluate the result of the logical OR expression A or B,
but you already know that A=True.

 Because you know this, you also know that the overall
expression will evaluate to True.

 Therefore, the Python programming language will


skip the computation of the remaining expression B
and just returns the result True.
35
PRECEDENCE AND ASSOCIATIVITY RULES
 The Python operator precedence and associativity rule is one very
important aspect of the Python Programming language. It determines
the priorities of the operator.

 The operator precedence is used in an expression with more than one


operator and with different precedence to ascertain which operation is
to be performed first. The Python interpreter first executes the
operations with higher precedence operators in any given expression.
Apart from the exponent operator (**), every other operator is
Precedence and Associativity Rules executed from left to right.

 In Python programming, there is a principle of precedence for


evaluating expressions. For example, Division is given priority over
addition. As seen in example 3 below:

36
PRECEDENCE AND ASSOCIATIVITY RULES
 # Division is given priority over addition.
 18 + 20 / 2

 # Parentheses () takes precedence over division


 (18 + 20) / 2

37
PRECEDENCE OF PYTHON OPERATORS

38
PRECEDENCE OF PYTHON OPERATORS

39
OTHER FORMS OF EXPRESSIONS
In Python programming, there are other types of expression.
Note that an expression deals with operators and operands.
An example of expression can be seen in the example below:

x=24
x=x+10
print(x-1)
print(x-x)
print(x)

40
GETTING INPUTS FROM THE KEYBOARD
 In getting user inputs from the keyboard, the input() function is
used.
 Syntax:
 input("Your name: ")
 it takes a string, which is displayed in the terminal.
 The input() function - input from keyboard
 The program indefinitely waits for user input without timing out.
 The input function returns a string that you can store in a
variable
 It can Terminate with Ctrl-Z+Return (for WINDOWS) and CTRL-
D for Unix
41
CONCLUSION
 This module covered Python programming basics, including
variables, operators, assignment statements, and expressions. It
also demonstrated how to receive user input from the keyboard,
with examples illustrating Python’s key features. Additionally, it
explained how to design and implement programming solutions
using arithmetic and Boolean operators, concluding with a clear
explanation of handling keyboard input.

42
THANK YOU

43
EXERCISES
1) What are variables, expressions and statements in Python?
2) What is a Boolean Expression?
3) Consider two number and check if the sum of the numbers is
greater than 5, less than 5 or equal to 5.
4) Assuming that the pass mark for COS 201 is 40. Take input of
scores from a student and check if it is greater than the pass
marks or not.
5) Given that x=5 and y=10. What will be the output of the following
expressions? x + y (x*y) + (x *y +2)

44
EXERCISES
6) What is the output of the following expression (43+13−9/3∗ 7)
(43+13−9/3∗ 7)
7) What is Short-Circuit and Complete Evaluation?
8) List any other Four (4) forms of Expressions apart from the
Boolean Expression
9) Draw a table showing any 10 Python Operators in their order of
precedence
10) In a tabular form, list the Python Arithmetic Operators,
showing their syntax

45
EXERCISES
11) Which of the following would give a syntax error?
A. x, y, z = 10, 20, 30
B. x, y, z = 10, 'Hello', True
C. x = 10, y = 'Hello', z = True
D. None of the above

12) Which of the following statements is correct?


A. The variable names cannot start with a digit.
B. Variable names in Python are case-sensitive.
C. Variable names cannot start with the underscore _. 46
D. Variable names can be reserved keywords.
EXERCISES
13) What will be the output of the following code?
x=10
y=20
x, y = y,x
print(x,y)

A. 10 20
B. 20 10
C. 0 0
D. Syntax Error 47
EXERCISES
14) Which one of the following Boolean expressions is not equivalent
logically to the others?
A. not(-6<10 or-6==10)
B. -6>=0 and -6<=10
C. not(-6<0 or-6>10)
D. not(-6>10 or-6==10)

48

You might also like