Computer Programming Lecture 2
Computer Programming Lecture 2
Programming Lecture 2
Outline
• Variables
• Expressions
• Statements
• Data types
Variable
• Variable refers to a named place in the memory where a programmer can store data and later
retrieve it.
• Programmers get to choose the names of the variables
>>> x = 3
>>> message = “Hello”
>>> print(x) -> 3
>>> print(x + 2) -> 5
>>> print(message) -> Hello
Exercise
• Computing area of a rectangle
• Computing area of a triangle
Variables
• You can change the content of a variable:
>>> x = 3
>>> x = 4
>>> print(x) -> 4
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters and numbers and underscores
• Case Sensitive
>>> PI = 3.14
Literals
• Literals in Python are raw values or data that are assigned to variables or constants.
• There are different types of literals:
• String literal -> “Hello”, ‘Hi’, ‘’’this is multi-line literal’’’
• Numeric literal -> 1, 1.5
• Boolean literal -> True, False
• Literal collections -> [1,2,3,4], (1,2)
Expressions
• An expression is a combination of operands and operators.
• Operators are special symbols that designate some sort of computation, such as addition,
subtraction, multiplication, etc. Operands are the values that an operator acts on, such as
numbers, strings, variables, etc.
>>> radius = 2
>>> PI = 3.14
>>> area = PI * (r ** 2)
>>> print(area)
Statements
• A statement is a unit of code that performs some action but does not return any value.
Example:
• Assignment Statement -> x = 2
• Assignment statement with an expression -> x = 2 + 3
• Print statement -> print(x)
•x=7
• x = x + 7 -> 14
Numeric Expressions
Operation Symbol
+ Addition
- Subtraction
* Multiplication
/ Division
** Power
% Remainder
// Floor division
Operation Precedence
• Dictates order of execution in evaluating arithmetic expressions.
• Parenthesis
• Power
• Multiplication and division
• Addition and Subtraction
• Left to right
Example
x = 1 + 2 ** 3 / 4 * 5
Evaluation:
1 + 8 / 4 * 5 -> Power gets evaluated
1 + 2 * 5 -> The division gets evaluated due to left to right rule
1 + 10 -> The multiplication gets evaluated
11 -> the addition gets evaluated
Exercise
>>> 2 + 3 – 1 * 5 + 1 / 4
>>> 2 + 3 – 1 * (5 + 1/4)
Data Types
• Data types are classifications of data that tell the compiler or interpreter how the programmer
intends to use the data.
• Data types define the set of values and operations that can be applied on those values.
Numeric Types
• This types are for data that is numeric or should be worked with as a number for addition or
other math operations.
• Numbers can be integers or floating point (numbers with fractional parts).
• Integers are represented using int data type in python.
• Floating point numbers are represented using float data type.