You are on page 1of 35

CENG1004 – Introduction to Programming

Lecture 2

Variables, Expressions, Statements

Spring 2023
Values and Data Types

• A value is one of the fundamental things — like a word or a


number — that a program manipulates.

• Some values are 5 and "Hello, World!".

• These objects are classified into different classes, or data


types:
• 5 is an integer
• "Hello, World!" is a string
Values and Data Types

• int – represent integers, ex. 5

• float – represent real numbers, ex. 3.27

• bool – represent Boolean values True and False

• NoneType – special and has one value, None

• can use type() to see the type of an object


Values and Data Types

• Strings (str)

• letters, special characters, spaces, digits

• can be enclosed in either single quotes (') or double quotes


("), or three of each (''' or """)

• A string represents text


• "python"
• "Introduction to Programming"
• 'ceng1004'
Type conversion functions

• to convert values from one type to another

• The int function can take a floating-point number


or a string, and turn it into an int.
• For example;
int(123.45) → 123
int("3") → 3

• The type converter float can turn an integer, a float,


or a syntactically legal string into a float.
• For example;
float("123.45") → 123.45
float(3) → 3.0
Type conversion functions

• to convert values from one type to another


• The type converter str turns its argument into a string.

• For example;
str(17) → '17'
str(29.75) → '29.75'

• Note that: Remember that when we print a string, the quotes are
removed in the output window.
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”

• A variable is a name that refers to a value.

• Assignment statements create new variables and also give them


values to refer to.

• To assign a variable, use “variable_name = expression”


Variables

• 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
Variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2
y = 14
y 14
Variables

• You can change the contents of a variable in a later statement

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
Python Variable Name Rules

• Variable names can contain both letters and digits, but they have to
begin with a letter or an underscore.

• Variable names are case sensitive


• number and Number are different variables.

• Variable names can never contain spaces.

• The underscore character (_) can also appear in a name.


• for example: my_name, student_id

• Variable names cannot begin with numbers.

• Variable names cannot contain illegal character such as the dollar sign.
Reserved Words

• You cannot use reserved words as variable names.

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
Quick Check

Which of the followings are valid variable names in Python?

A. isGood
B. 4cats
C. _number
D. student id
E. name&surname
F. break
G. score2
Statements

• A statement is an instruction that the Python interpreter can


execute.

• We have only seen the assignment statement so far.

• Some other kinds of statements that we will see in future chapters


are:
• while statements,
• for statements,
• if statements,
• import statements.
Expressions

• An expression is a combination of literals, variable names,


operators, and calls to functions.

• Expressions need to be evaluated.

• The result of evaluating an expression is a value or object.


Operators

• Operators are used to perform various operations on variables and


values.
• The standard arithmetic and assignment operators are the most
familiar.

Syntax

• The following code snippet uses the assignment operator, =, to set


my_variable to the value of num1 and num2 with an arithmetic
operator acting on them.
• For example, if operator represented *, my_variable would be
assigned a value of num1*num2.

my_variable = num1 operator num2


Operators

• Python operators can be organized into the following groups:


• Arithmetic operators for performing traditional math
evaluations.
• Assignment operators for assigning values to variables.
• Comparison operators for comparing two values.
• Logical operators for combining boolean values.
Arithmetic Operators

• Python has the following arithmetic operators:

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
** Exponentiation
% Remainder
Arithmetic Operators

• The division operator / produces a floating-point result (even if


the result is an integer)
• for example;
• 4/2 is 2.0
• 9/5 is 1.8
• 9.0/4.0 is 2.25

• If you want truncated division, which ignores the remainder, you


can use the // operator (floor division)
• for example;
• 5 // 2 is 2
• 9 // 5 is 1
• 7.0 // 3.0 is 2.0
Arithmetic Operators

• The modulus operator, sometimes also called the remainder


operator or integer remainder operator works on integers (and
integer expressions) and yields the remainder when the first
operand is divided by the second.

• In Python, the modulus operator is a percent sign (%).

• The syntax is the same as for other operators.

• For example;
• 7 % 3 is 1
• 19 % 5 is 4
Quick Check

What is the value of below expression?

28 // 3.0

A. 9
B. 9.0
C. 1
D. 1.0
E. I don’t know.
Operator Precedence Rules

• Python evaluates an expression in order of precedence as follows:


• Items in parentheses, ((…)), have the highest level of precedence,
expressions within them are evaluated first.
• Exponentiation (**)
Parenthesis
• Multiplication and division operators (*,/,//,%) Power
• Addition and subtraction (+,-) Multiplication
• Comparison (<,<=,>,>=) Addition
• Equality (==,!=) Left to Right
• not
• and
• or
Note: Items at the same precedence are evaluated left to
right. The exception to this is exponentiation, which
evaluates right to left.
Quick Check

What is the result of the following each expression?

• 26 % 4

• 17 / 5

• 3 + 9 / 6 * 5 - 7

• 11 // 3

• 8 / 2 + 5 * 7 / 5 + 3
Assignment Operators

• Python includes the following assignment operators:


• The = operator assigns the value on the right to the variable on the
left.
• The += operator updates a variable by incrementing its value and
reassigning it.
• The -= operator updates a variable by decrementing its value and
reassigning it.
• The *= operator updates a variable by multiplying its value and
reassigning it.
• The /= operator updates a variable by dividing its value and
reassigning it.
• The %= operator updates a variable by calculating its modulus
against another value and reassigning it.
Assignment Operators

x = 11

x += 1 x = x + 1
x -= 5 x = x - 5
x *= 2 x = x * 2
x /= 7 x = x / 7
x %= 4 x = x % 4

x = 9
y = 11
x += y - 3 x = x + (y-3)
Print function

• To show output from code to a user, use print command

print("Hello World!")
>> Hello World!

print('Hello World!')
>> Hello World!

print(15 + 19)
>> 34

x = 7
print("The value of x is", x)
>> The value of x is 7

a = 8
b = 19
print('a =', a, "and b =", b)
>> a = 8 and b = 19
User Input

• We can instruct Python to pause and read data from the user
using the input() function

• The input() function returns a string

• For example;
name = input("Enter your name: ")
print("Hello", name)

• The input function allows the programmer to provide a prompt


string.
Converting User Input

• If we want to read a number from the user, we must convert it


from a string to a number using a type conversion function

• For example;
number = input("Enter a number: ")
print("The square of the number:", number**2)

Output: TypeError: unsupported operand type(s) for


** or pow(): 'str' and 'int'

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


print("The square of the number:", number**2)
Output: Enter a number: 7
The square of the number: 49
Quick Check

What is the output of the following code?

a = 7
b = a + 4
a = 9
print(b)

A. 7
B. 9
C. 11
D. 13
E. I don’t know.
Comments

• A comment in a computer program is text that is intended only for the


human reader - it is completely ignored by the interpreter.

• Comments are used to explain the code we write.

• In Python, comments start with the # symbol:

• It is used to make it easier for the user to understand the written code.

• For example;
# This code calculates area of the circle
# the formula is area = pi*radius*radius
pi = 3.14
r = 5
area = pi*r*r
print("area is", area)
Exercise 1

Write a program that will ask your name and your age and then
print "your_name is your_age years old."

Sample output:
Exercise 1 - Solution

Write a program that will ask your name and your age and then
print "your_name is your_age years old."
Exercise 2

Write a program that calculates the area and perimeter of a rectangle.


Prompt the user to enter the width and height of the rectangle and
store the values in variables called width and height. The width
and height will be entered as floating point numbers. Display the
area and perimeter values.

Sample output:
Exercise 2 - Solution

Write a program that calculates the area and perimeter of a rectangle.


Prompt the user to enter the width and height of the rectangle and store
the values in variables called width and height. The width and
height will be entered as floating point numbers. Display the area and
perimeter values.

width = float(input("Enter width: "))


height = float(input("Enter height: "))

area = width * height


perimeter = 2*(width + height)

print("Area =", area)


print("Perimeter =", perimeter)
References

• Slides are adapted from


• https://web.cs.hacettepe.edu.tr/~muh101/
• https://ocw.mit.edu/courses/6-0001-introduction-to-
computer-science-and-programming-in-python-fall-2016/
• https://www.py4e.com
• https://runestone.academy/ns/books/published/fopp/index.h
tml
• https://www.codecademy.com/resources/docs/python/opera
tors

You might also like