0% found this document useful (0 votes)
20 views47 pages

Variables Expressions Statements vzp1VQp0

This document provides an overview of programming concepts including variables, constants, expressions, statements, and data types. It explains the use of variables for storing data, the rules for naming them, and how to perform operations with different data types. Additionally, it covers data type conversion, comments, and includes knowledge checks and review questions to reinforce learning.

Uploaded by

analindatoh.at
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views47 pages

Variables Expressions Statements vzp1VQp0

This document provides an overview of programming concepts including variables, constants, expressions, statements, and data types. It explains the use of variables for storing data, the rules for naming them, and how to perform operations with different data types. Additionally, it covers data type conversion, comments, and includes knowledge checks and review questions to reinforce learning.

Uploaded by

analindatoh.at
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Lee Kien Phoon

Variables, Expressions & Statements

Learning Outcomes:
Upon successful completion of this lesson, you will be able to:

Explain the use of variables in a program

Explain the use of expressions and statements in a program

Variables

Constants

Expressions & Statements

Data Types

Mixing Data Types

Data Type Conversion

Comments
Summary

TUTOR IAL

Knowledge Check

Review Questions

Online Discussion
Lesson 1 of 11

Variables
Lee Kien Phoon

What are Variables?


Variables are a memory locations used to store data. The data can be retrieved using variable
names during program execution.

This short video gives a detailed explanation on Variables and the Rules for Naming them
(about 13 minutes)

>>> x = 1
>>> print(x)
1

>>> x = 99
>>> print(x)
99

x is a variable and it is being assigned a value of 1. The print statement takes the value in x
and displays it on the screen.

The next statement assigns the value of 99 to x. Again, the print statement takes the value in
x and displays it on the screen.
Study the program given below:

x=1
y=2
x=x+3
y=x

What is the value of x and y after line 1 is being executed?



Value of x is 1, y does not exist.

What is the value of x and y after line 2 is being executed?



Value of x is 1 and y is 2.

What is the value of x and y after line 3 is being executed?



Value of x is 4 and y is 2 (unchanged).
In line 3, there are 3 operations to be done by the program. First, it takes the value from x
which is 1. Next, it adds 1 and 3. Finally, it assigns 4 to the variable x. Note that the original
value of x is overwritten.

What is the value of x and y after line 4 is being executed?



Value of x is 4 (unchanged) and y is also 4. The computer takes the value of x and put it into
variable y. Note that the original value of y is overwritten.

Rules for Variable Name


Variable name must start with a letter or underscore _. The subsequent characters can be a
combination of letters, numbers or underscore _. Variable names are case sensitive. That is,
nric and Nric are not the same.

Note that we do not encourage variable names to start with an underscore _ as this is reserve
for special uses. We do not emphasize naming convention in our beginner's course. If you are
interested to know more, you can refer to PEP 8.

Knowledge Check
Determine if each of the the following variable name is valid or invalid.

nric Valid
Invalid because it starts with a
1nric
number.

nric2 Valid

I lid b it h i l
Invalid because it has a special
nric@1
character.

Invalid because it has two


'nric'
special characters.

n_r_i_c Valid
Reserved words cannot be used as variable names. They have special meanings in Python.
Syntax errors will be encountered if these reserve words are used. The list of reserve words is
given below:

False True if elif else

while for not and or

break continue from nally try

import return in

is def global class with

assert None del pass nonlocal

as except yield raise lamda

We will encounter the highlighted reserved words in later Topics.


Lesson 2 of 11

Constants
Lee Kien Phoon

Constants are xed values that does not change when the program is running. For example,
the number 12 does not change during program execution. Therefore, 12 is an constant.

There are two types of constants, numeric constants and string constants.

Numeric constants are numbers.

String constants are characters enclosed in either single (‘) or double (“) quotes.

>>> print(12)
12

>>> print(1.23)
1.23

>>> print(‘Hello World’)


Hello World

>>> print (“Hello Earth”)


Hello Earth
Lesson 3 of 11

Expressions & Statements


Lee Kien Phoon

An expression is a combination of variables and operators, with or without constants, that


evaluates to a value.

Let's look at an example:

x=x+5

The expression is x + 5. After the expression is evaluated, the result is assigned to variable x.
Hence, x = x + 5 is an assignment statement.

For a simple expression, x + 5, x and 5 are known as operands and + is an operator. The table
below shows the common operators in Python:
This short video gives a detailed explanation on Constants, Expressions & Statements (about
18 mins)

Knowledge Check
Study the codes and give the output of the print statement.

x=3*2
y = x ** 2
36
print(y)
36
y%5
print(y)
x=3*2
y = x ** 2
36
print(y)
1
y=y%5
print(y)

x = 10 / 4
y = 10 // 4 2.5
print(x) 2
print(y)

When an expression has a long series of operations, we use parenthesis to make it more
readable. Let's look at 2 examples:
result_1 = (1 + 2) / 3 * 4 - 5 + 6
result_2 = 1 * 2 ** 3 / 4 + 5 * 6

The operator precedence is shown in the table below:


Lesson 4 of 11

Data Types
Lee Kien Phoon

A variable can hold di erent types of data. For example, the name of an employee must be
stored as a string whereas the salary must be stored as an integer.

In Python, there are 4 basic data types and we can use type() to check on the type of the data:

Integer (int)

Integers are whole numbers.
>>> type(1)
<class 'int'>

Floating point number ( oat)



Floating point numbers are decimal numbers.
>>> type(1.0)
<class ' oat'>

String (string)

A string is a sequence of characters represented in the quotation marks. In python, we can use
single, double, or triple quotes to de ne a string.
>>> type('string')
<class 'str'>

Boolean (bool)

A boolean expression (or logical expression) evaluates to one of two states true or false. Python
provides the boolean type that can be either set to False or True.
>>> type(False)
<class 'bool'>

Knowledge Check
Study the codes and give the output of the print statement.

x=3*2
y = x ** 2
36
print(y)
36
y%5
print(y)
x=3*2
y = x ** 2
36
print(y)
1
y=y%5
print(y)

x = 10 / 4
y = 10 // 4 2.5
print(x) 2
print(y)

When an expression has a long series of operations, we use parenthesis to make it more
readable. Let's look at 2 examples:

result_1 = (1 + 2) / 3 * 4 - 5 + 6
result_2 = 1 * 2 ** 3 / 4 + 5 * 6
The operator precedence is shown in the table below:
Lesson 5 of 11

Mixing Data Types


Lee Kien Phoon

We can mix the data types in the expressions and statements. However, there are rules to be
applied:

1 + 1.0 = 2.0
Operations between Integer and oating point number yields oating point number.

1 + True = 2
When booleans are used in arithmetic operation, True is 1 and False is 0.

5 * ‘s’ = ‘sssss’
A string multiply with an integer ended up with the repeated string value.

1 / 1 = 1.0
Division of two numbers resulted in a oating point number.

5 + ‘1’
We cannot add a number and a string.

True + ‘1’
Cannot add a boolean and a string.

Knowledge Check
What is the value of the following statements?
'1' + 2 * '3'+ '1' '1331'

TypeError: unsupported
1 + '2' * 3 + '1' operand type(s) for +: 'int' and
'str'

1+2*3 /3+1 4.0


TypeError: can't multiply
'1' + '2' * '3' + '1' sequence by non-int of type
'str'

1 + False / True 1.0


ZeroDivisionError: division by
1 + True / False
zero
Lesson 6 of 11

Data Type Conversion


Lee Kien Phoon

We can use the type conversion function to change the data type of a variable. For example, to
add a string '2' to an integer 5, we need to convert the string to an integer before the
operation:

>>> sum = '2' + 5


TypeError: can only concatenate str (not "int") to str

>>> sum = int('2') + 5


>>> print (sum)
7

The three data type conversion functions are list below:

int(item) where item can be a oating point number or a string



The int() function converts the item to an integer value.
>>> num = int(3.7)
>>> print(num)
3

>>> hour = int('2')


>>> print(hour + 2)
4

oat(item) where item can be an integer or a string



The oat() function converts the item to a oating point number.

>>> num = oat(3)


>>> print(num)
3.0

>>> hour = oat('2')


>>> print(hour + 2)
4.0

str(item) where item can be any number



The str() function converts the item to a string value.

>>> any = str(3)


>>> print(any + "%")
3%

>>> any = str(3.7)


>>> print(any + "%")
3.7%
Knowledge Check
What is the value of result?

TypeError: unsupported
result = 1 + '2' * 3 + '1' operand type(s) for +: 'int'
and 'str'

result = str(1) + '2' * 3 + '1' 12221


result = 1 + int('2') * 3 +
8
int('1')

Reading Input from Keyboard


It is very common for computer programs to read input entered by the user on the keyboard.

>>> name = input("What is your name? ")


What is your name? Python <ENTER>
>>> type(name)
<class 'str'>
>>> print(name)
Python

The input from the keyboard is stored as string type. What can be done if we want to read
numbers with the input() function? Well, we can use the int() or oat() function to convert
the input.

>>> num = int(input("Enter a number: "))


Enter a number: 3 <ENTER>
>>> type(num)
<class 'int'>
>>> print(num)
3
This short video gives a detailed explanation on Data Types (about 31 minutes)
Lesson 7 of 11

Comments
Lee Kien Phoon

Comments are text notes added to the program to provide explanation about the source code,
especially when the logic is complex. It helps other programmers to understand and ease the
maintenance of complex programs.

# This is a comment
# The interpreter will skip these lines automatically
# We use comment to help us (or other programmers)
# to understand the code that we have written

>>> name = input("What is your name? ")


What is your name? Python <ENTER>
>>> print(name)
Python
Lesson 8 of 11

Summary
Lee Kien Phoon

We have covered the following:

The use of variables, expressions and statements in a program

Data Type Conversions


Lesson 9 of 11

Knowledge Check
Lee Kien Phoon

Question 1
Which of the following are legal identi ers? If illegal, give reason.

3com

Cannot start with a digit.

an_apple

Legal

Aug1965

Legal
a*star

Cannot have special characters +, - * /.

let’s go

Cannot have special character ‘ and space.

__hello

Legal but not recommended. A variable starts with an underscore is normally used for a
speci c purpose.

rst-name

Cannot have special characters +, - * /.

lastName

Legal
class

Cannot use reserved word.

Mix#8

Cannot have special characters.

Question 2
For each of the following assignment statements, give the result if it is correct. Otherwise,
explain why it is incorrect.

Correct. A string '7689' is


var1 = '7689'
assigned to var1.
Incorrect as == is a comparison
var2 == 'Hi'
operator.

Incorrect as Hello is not


var3 = Hello
de ned.

Incorrect as we cannot assign


3 = var4
value to a number.
Correct. Expression evaluated
'7'+3*'8'+'2'
to 78882.

Correct. Expression evaluated


9.0/5.0*True
to 1.8.
Incorrect as we cannot add a
False*'9'+2.0
number and a string.

Correct. Expression evaluated


5//2*3/True
to 6.0.

Question 3
Write the statement to

create two variables named width and length. Assign the value of 4 to the variable
width and value of 3 to the variable length.

calculate area of rectangle using the variable width and length. Reassigned the value to
variable width.

display the values referenced by the variables.


width = 4
Answer #1
length = 3

Answer #2 width = width * length

print(width)
A #3
p t( dt )
Answer #3
print(length)

Question 4
Given the following program, what value and type will be stored in result after each of the
following statements is being executed.


1.25 and it is a ' oat'

When 5 is divided by 4, it gives a oating point number of 1.25. The value remains unchanged when
multiply by 1 (True).

aaaa and it is a 'str'

y is 'a' and x is 4. So, 'a' * 4 is 'aaaa'.


10 and it is an 'int'

5 + 4 + 1 = 10
Lesson 10 of 11

Review Questions
Lee Kien Phoon

There are 5 questions in this review. You need to score 80% to pass the review.
Question

01/05

Which of the following variable names are valid?

False

rst_name

rstName

rst name

halt!

2MoreToGo

_width

length
Question

02/05

Select all the correct statements.

The number of months in a year should be stored in a variable of type int.

The area of a circle is of type int.

The postal code of a place is better to be stored as a string than an int.

The name of a customer is of type string.

The expression "hello" * 3 is valid in Python.

The salary of the workers should be stored as oat.


Question

03/05

If x = "dog" and y = "cat", what is the value of x + y * 2?

Type your answer here


Question

04/05

Which of the following list of operators is ordered by decreasing precedence?

parenthesis (), multiplication *, addition +, exponential **

exponential **, parenthesis (), multiplication *, addition +

exponential **, multiplication *, addition +, parenthesis ()

parenthesis (), exponential **, multiplication *, addition +


Question

05/05

What is the output of the following program?

x=9
y=2
result = x ** y + x // 4
print(result)

20

22.25

83

83.25
Lesson 11 of 11

Online Discussion
Lee Kien Phoon

A cookie recipe calls for the following ingredients

1.5 cups of sugar

1 cup of butter

2 cups of our

The recipe produces 48 cookies with this amount of ingredients. Write a program that asks
the user for the number of cookies he wants to make, and display the number of cups of each
ingredient needed for the speci ed number of cookies.

What are the potential pitfalls of the suggested solution, and what enhancements can you
suggest to improve your program?

You might also like