You are on page 1of 45

Topic 4 – Variable, Expression and Statement

Python Programming
CT108-3-1-PYP
TOPIC LEARNING OUTCOMES

At the end of this topic, you should be able to:


• Understand the use of relational operators
• Understand the use of variables
• Understand the use of Boolean operators
• Understand the Type conversion in Python

Python Programming Variable, Expression and Statement SLIDE 2


CT108-3-1-PYP
Contents & Structure

• Variables in python
• Rules for naming variables
• Expressions and statements
• Type conversion

Python Programming Variable, Expression and Statement SLIDE 3


CT108-3-1-PYP
Variable

Variable is a name that is used to refer to memory location.

Python variable is also known as an identifier and used to hold value.

No need to specify the type of variable because Python is a infer language


and smart enough to get variable type.

Variable names can be a group of both the letters and digits but must begin
with a letter or an underscore.

Recommended to use lowercase letters for the variable name. For


example, Name and name both are two different variables.

Python Programming Variable, Expression and Statement SLIDE 4


CT108-3-1-PYP
Declaring Variable and Assigning Values

Python – does not have to declare a variable before using it in the application.

Allows to create a variable at the required time.

No need to declare explicitly variable in Python.

When assigning any value to the variable, the variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

Variables are a symbolic name that is a reference or pointer to an object.

The variables are used to denote objects by that name.

Python Programming Variable, Expression and Statement SLIDE 5


CT108-3-1-PYP
Rules of Naming a Variable

01 02 03 04 05
The first All the character except
the first character may
Identifier name Identifier name Identifier name are case
sensitive for example :-
character of be an alphabet of lower
must not use any must not be similar
• NAME and name are
variable must be case like(a-z),upper case white space and any keyword the different name not
an alphabet or like(A-Z) and they use special character a same variable
the digits(0-9) (!,@,#,%)
underscore(_)

Python Programming Variable, Expression and Statement SLIDE 6


CT108-3-1-PYP
Variable – Python Example

Create a variable number = 10

Replaced or reassign the number = 10


value of the variable. number = 2.5

Assigning multiple values a, b, c = 3, 3.5, “Python”


to multiple variables:

Assigning same values to a = b = c = “I love Python”


multiple variables:

Python Programming Variable, Expression and Statement SLIDE 7 ‹#›


CT108-3-1-PYP
Variable - Example

Good: spam, eggs, spam23, _speed

Bad: 23spam, #sign, var.12

Different: spam, Spam, SPAM

Python Programming Variable, Expression and Statement SLIDE 8


CT108-3-1-PYP
‹#›
Python Variable Types

• Global
– Global variables can be used throughout the program, and its scope is in the entire program.
– Global variables can be used inside or outside the function.
– A variable declared outside the function is the global variable by default.
– Python provides the global keyword to use global variable inside the function. If the
global keyword were not used, the function treats it as a local variable
• Local
• Variables that declared inside the function and have scope within the function

Python Programming Variable, Expression and Statement SLIDE 9


CT108-3-1-PYP
Local Variable - Example

def add():
a=20
b=10
c=a+b
print("The sum is ", c)
add()

Python Programming Variable, Expression and Statement SLIDE 10


CT108-3-1-PYP
Global Variable - Example

a = 50
def add():
global a
b=10
c=a+b
print("The sum is ", c)
add()
print(a)

Python Programming Variable, Expression and Statement SLIDE 11


CT108-3-1-PYP
Constants

Is a type of variable whose value cannot be changed.

It is helpful to think of constants as containers that hold information which cannot be changed
later.
Refer to names associated with values that never change during a program’s execution.

Fixed values such as numbers, letters, and strings are called “constants” - because their value
does not change.
Constants are usually declared and assigned in a module

Python Programming Variable, Expression and Statement SLIDE 12


CT108-3-1-PYP
‹#›
Declaring and Assigning a value to a Constant

Create python file name constant.py


Create PI = 3.14

Create python file name week4.py


Create import constant
print(constant.PI)

Python Programming Variable, Expression and Statement SLIDE 13 ‹#›


CT108-3-1-PYP
Data Types

• Variable can hold value and every value has a data type
• No need to define the type of the variable while declaring
– Example:- a=5
– The variable hold the integer value five
• User can not define any Data Type
• Python interpreter will automatically give an integer Data Type to the variable
• Python provide the type () function to check the data type any variable
• The basic types are:

Python Programming Variable, Expression and Statement SLIDE 14


CT108-3-1-PYP
‹#›
Why should we care?

Python Programming Variable, Expression and Statement SLIDE 15


CT108-3-1-PYP
‹#›
Why Type Matters?

Important lesson to remember!


We can't do arithmetic operations on
variables of different types.
Therefore, make sure that you are
always aware of your variable's
types!

You can find the type of a variable


using type(). For example, type
type(x).

Python Programming Variable, Expression and Statement SLIDE 16


CT108-3-1-PYP
Casting types

Luckily, Python offers us a way of converting variables to different types!


Casting – the operation of converting a variable to a different type

Similar methods exist for other data types:


int(), float(), str()

Python Programming Variable, Expression and Statement SLIDE 17


CT108-3-1-PYP
Quick quiz

What will be the result?

Python Programming Variable, Expression and Statement SLIDE 18


CT108-3-1-PYP
Python Keywords

Python keywords are special reserved words that convey a special meaning to
the compiler/interpreter.

Each Keywords has a special meaning and a specific operation.

These keywords cannot be used as a variable.

Python Programming Variable, Expression and Statement SLIDE 19


CT108-3-1-PYP
Python Reserved Words

False class finally is return None continue for

lambda try True def from nonlocal while and

del global notwith as elif if or yield

assert else import pass break except in raise

Python Programming Variable, Expression and Statement SLIDE 20


CT108-3-1-PYP
‹#›
Assignment Statements

• We assign a value to a variable using the assignment statement (=)


• An assignment statement consists of an expression on the right-hand side and a
variable to store the result

x = 3.9 * x * ( 1 - x )

Python Programming Variable, Expression and Statement SLIDE 21


CT108-3-1-PYP
‹#›
Assignment Statements - Example

A variable is a memory location used to store a value (0.6).

x = 0.6

x = 3.9 * x * ( 1 - x )

Right side is an expression. Once expression is


evaluated, the result is placed in (assigned to) x.
0.936

Python Programming Variable, Expression and Statement SLIDE 22


CT108-3-1-PYP
‹#›
Arithmetic / Numeric operations

• Like actual Mathematics.


• Order of precedence is the same as in Mathematics.
• We can also use parenthesis ()
• Because of the lack of mathematical symbols on computer keyboards - we use “computer-speak” to express
the classic math operations
• Asterisk is multiplication
• Exponentiation (raise to a power) looks different from in math.

Python Programming Variable, Expression and Statement SLIDE 23


CT108-3-1-PYP
‹#›
More Sample

Exponentiation:
2**3 is 8
2.5**2 is 6.25

Integer division (rounds down):


5//2 is 2

Modulus (gives the remainder):


28 % 5 is 3

Python Programming Variable, Expression and Statement SLIDE 24


CT108-3-1-PYP
Real numbers

Python can also manipulate real Examples: 6.022 -15.9997 42.0 2.143e17
numbers.

The operators + - * / % ** ( ) all work The / produces an exact answer: 15.0 / 2.0 is 7.5
The same rules of precedence also apply to real numbers:
for real numbers. Evaluate ( ) before * / % before + -

Example: 1 / 2.0 is 0.5


The conversion occurs on a per-operator basis.
When integers and reals are mixed, the 7 / 3 * 1.2 + 3 / 2
2 * 1.2 + 3 / 2
result is a real number. 2.4 + 3 / 2
2.4 + 1
3.4

Python Programming Variable, Expression and Statement SLIDE 25


CT108-3-1-PYP
‹#›
Expressions

• Expression: A data value or set of operations to compute a value.


– Examples: 1 + 4 * 3
» 13
• Precedence: Order in which operations are computed.
– * / % ** have a higher precedence than + - 1 + 3 * 4 is 13
– Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16

Python Programming Variable, Expression and Statement SLIDE 26


CT108-3-1-PYP
‹#›
Order of Evaluation

When we write
Which operator “takes
operators together - This is called
precedence” over the
Python must know “operator precedence”
others
which one to do first

x = 1 + 2 * 3 - 4 / 5 ** 6

Python Programming Variable, Expression and Statement SLIDE 27 ‹#›


CT108-3-1-PYP
Order Precedence Rules

• Highest precedence rule to lowest precedence rule


– Parenthesis are always respected
– Exponentiation (raise to a power)
– Multiplication, Division, and Remainder
Parenthesis
– Addition and Subtraction Power
– Left to right Multiplication / division/
Modulus
Addition
Left to Right

Python Programming Variable, Expression and Statement SLIDE 28


CT108-3-1-PYP
‹#›
Order precedence example

Python Programming Variable, Expression and Statement SLIDE 29


CT108-3-1-PYP
Quick quiz

vs

Python Programming Variable, Expression and Statement SLIDE 30


CT108-3-1-PYP
Operator Precedence

Remember the rules top to bottom

When writing code - use parenthesis

When writing code - keep mathematical expressions simple enough that they are easy to
understand

Break long series of mathematical operations up to make them more clear

Python Programming Variable, Expression and Statement SLIDE 31


CT108-3-1-PYP
‹#›
Comparison operators

• Return Boolean values i.e., True or False


• Used extensively for conditional statements

Python Programming Variable, Expression and Statement SLIDE 32


CT108-3-1-PYP
‹#›
Comparison examples

False

Python Programming Variable, Expression and Statement SLIDE 33


CT108-3-1-PYP
Logical operators

• Allows us to extend the conditional logic


• Will become essential later

Python Programming Variable, Expression and Statement SLIDE 34


CT108-3-1-PYP
Combining both

True True

Python Programming Variable, Expression and Statement SLIDE 35


CT108-3-1-PYP
Another example

True True True

That wasn't very easy to read was it?


Is there a way we can make it more readable?

Python Programming Variable, Expression and Statement SLIDE 36


CT108-3-1-PYP
More readable

Python Programming Variable, Expression and Statement SLIDE 37


CT108-3-1-PYP
Exercise 1

• What will the following code snippet print?

– a = 10
– b=a*5
– c = "Your result is: "
– print(c, b)

Python Programming Variable, Expression and Statement SLIDE 38


CT108-3-1-PYP
Exercise 2

• What will the following code snippet print?

a = 10
b=a
c = "Your result is: "
print(b)

Python Programming Variable, Expression and Statement SLIDE 39


CT108-3-1-PYP
Exercise 3

• What will the following code snippet print?

a = 10
b=a
c = "Your result is: "
print(b)

It will print out 10. When you set one variable equal to another, they don’t become linked; b
is set to 10 and no longer has anything else to do with a.

Python Programming Variable, Expression and Statement SLIDE 40


CT108-3-1-PYP
Exercise 4

• Without using any Python IDLE, write on a piece of paper or any text editor tools a
python program that asks the user for two numbers and prints out the average.

Python Programming Variable, Expression and Statement SLIDE 41


CT108-3-1-PYP
Exercise 5

• Pretend that you’re writing a program to compute someone’s weighted grade. You have so
far:
– hwWeight = 0.4
– examWeight = 0.5
– discussionWeight = 0.1
• Write a program starting with these three lines that asks the user for their homework grade,
exam grades, and discussion grades and prints out their total grade in the class.

Python Programming Variable, Expression and Statement SLIDE 42


CT108-3-1-PYP
Summary / Recap of Main Points

• Variables in python
• Rules for naming variables
• Expressions and statements
• Type conversion

Python Programming Variable, Expression and Statement SLIDE 43


CT108-3-1-PYP
What To Expect Next Week

In Class Preparation for Class


• Conditional Statement • Students are required to
– Have a basic in conditional statement

Python Programming Variable, Expression and Statement SLIDE 44


CT108-3-1-PYP
Python Programming Variable, Expression and Statement SLIDE 45
CT108-3-1-PYP

You might also like