02 Python Intro
02 Python Intro
02 Python Intro
Learning Outcomes
● Terminology used in computer programming
○ Variables (identifiers / variable names)
○ Data types and Type conversion
○ Operators, Boolean operators
○ Precedence of operators
○ Expressions
○ Comments
○ Assignments, Simultaneous assignments
○ User input (number, string of characters)
○ Output statements
○ Math module (library)
Python Basics Part 1
What is Python?
4
What is Python?
∙ A general-purpose programming language that can be used
effectively to build almost any kind of program that does not
need direct access to the computer’s hardware.
∙ An easy to learn, powerful programming language
∙ It has efficient data structures
∙ It is “interpreted”!
− A compiled program is converted from source code into
machine-language instructions by a compiler, and then run
from its binary form
− An interpreted program takes the code you wrote and
converts it to binary “on the Fly” each time you run it. This is
slower.
5
Python Features
∙ It is simple to use: Python syntax is clearly defined which makes it
easily readable.
∙ It is interactive: you can write and test your programs directly
from a terminal window.
∙ It has a large standard library: Python’s library of built-in
functions offers a wide range of programs that are already written
for you.
∙ It is portable: Python runs on many Unix variants, on Mac OS, and
on Windows.
∙ It is extensible: you can use it as an extension language for
applications that need a programmable interface.
∙ It is scalable: you can use it for very small or very large programs.
6
Python Programs
7
Python Statements
∙ A command, often called a statement, instructs the interpreter to do something.
∙ Consider the sequence of commands
print('Yankees rule!')
print('But not in Boston!')
print('Yankees rule,', 'but not in Boston!')
∙ Which causes the interpreter to produce the output
Yankees rule!
But not in Boston!
Yankees rule, but not in Boston!
∙ The print function takes a variable number of arguments separated by commas,
and prints them, separated by a space character, in the order in which they appear.
– Two values were passed to print in the third statement.
8
Starting Python..
∙ Using Python IDLE
− click on Start 🡪 Programs 🡪 Python 3.x 🡪 IDLE (Python
GUI).
∙ Using PyCharm
∙ Using Jupyter Notebook
∙ Using Google Colab
9
Exercise 1
∙ Type the following commands:
print (“Hello, World”)
print (2 + 3)
print(“2 + 3 =”, 2 + 3)
print (“Hi! How are you?”)
print (“I am now in the Computer Lab at UoM.”)
print( “Hi! How are\n you?”)
print (“I am now \t in the Computer Lab at UoM.”)
x=2
print( x)
x=2
y=3
print( x + y)
Note: Press the Enter key after each command to view their result.
10
Exercise 2
∙ Use the Python Interpreter to display the
following:
Hello Sam! How are you?
11
Exercise 3
∙ Use the Python Interpreter to find each of
the following:
(1.) The sum of 24, 55, 28 and 42
(2.) The difference between 456 and 129
(3.) The product of 47 and 25
(4.) The average of 25, 32, 35, 56, and 78
12
Exercise 4 - Python IDLE
∙ Use the Python Editor to type in the required code statements for
Exercise 1.3 in a file. You should proceed as follows:
− From the menu, choose File … New Window.
− Type in the required statements.
− Choose File … Save
− For the file name, give a name of your choice to the file. The extension
should be .py
− Having saved the file, now run it as follows: From the menu, choose Run ..
Run Module.
− If the statements are all correctly written, the program will yield the
required outputs. If you have errors, you have to correct them and try to
Run again.
13
Exercise 5
∙ Write a program to display the following two lines:
I like going to movies
but I hate popcorns
∙ Note that the two statements should appear on different
lines
14
What are variables?
15
Exercise on Variables
∙ Type in the program below and run it.
x=5
y=10
z=x+5
print(x)
print(y)
print(z)
16
Displaying variables names and
values
∙ Consider
x =5
∙ What is the difference between the following two statements
print(“x”)
print(x)
How do we display x= 5 ?
print(“x=“,x)
17
Arithmetic Operations
∙ Programs need to be able to perform Arithmetic Operations.
− This is an important part of processing
∙ For basic Arithmetic Operations, the following operators are
available: +, -, *, /
∙ More operators will be discussed in due course
∙ What will be the output of the following program?
value1 =35
value2 = 18
sum = value1 + value2
print (“The sum of “, value1,“ and ”, value2, “ is”, sum)
18
Exercise 6
∙ Write a program to assign values 10 to variable x and 12 to
variable y and it displays the value of x+y, x*y, y-x, y/x, y//x
and y%x.
19
Order of precedence
The precedence order is described in the table below, starting
with the highest precedence at the top.
If two operators have the same precedence, the expression is
evaluated from left to right.
Operator Description
() Parentheses
** Exponentiation
== != > >= < <= is is not in not in Comparisons, identity, and membership operators
and AND
or OR 20
Assigning string values
∙ In the previous exercise, numerical values had been
assigned to variables.
∙ To assign non-numerical (string) values, the values should
be between single or double quotes, eg.:
student = "John Smith"
course= "Problem Solving Techniques"
∙ If we run the statement
print(student,course)
∙ We will see the output
John Smith Problem Solving Techniques
21
Exercise 7
Write a program that assigns the value “Pizza” to the
variable menu and “Cheese and Capsicum” to the variable
topping and makes use of the variables menu and topping
to display the following output:
The menu Pizza has topping Cheese and Capsicum
22
Programs with Input
∙ Consider the following program:
lecturer_name= "SomeLecturer"
module= "Programming Principles"
print (lecturer_name, "teaches", module)
lecturer_name=input()
print("lecturer is", lecturer_name)
24
Performing String Inputs
The following lines allow the user to input <lecturer_name>
and <module> and displays back : <lecturer_name>
<module>
lecturer_name=input()
module=input()
print (lecturer_name, "teaches", module)
25
String Inputs with prompt for user
∙ In the previous programs, when the program waits for inputs
from the user, the user sees only a blinking cursor ( | ).
− The user doesn’t know what input the program is waiting for.
∙ The input() function allows the programmer to specify a
message (prompt) that will be displayed for the user, when
the program waits for input.
26
Input of Numerical values
∙ The input() function is used as such for string inputs.
∙ For numerical values, the input statement is slightly different.
∙ We use eval(input())
∙ The program below allows the input of two numerical values
and displays their sum.
x= eval(input())
y= eval(input())
print("The Value of x is", x)
print ("The value of y is",y)
print(“The sum of “,x,”and”,y,” is”,x+y)
27
Numerical Input- With Message for User
∙ Even with eval(input()), we can include a message for the user.
28
Exercise 8
29
Exercise 1.9
30
Python Basics Part 2
The Python Shell
>>> 3 != 2
True
32
Identifiers (Variable Names)
33
Identifiers (Variable Names)
∙ (valid) identifiers in Python:
x
studentName
student_name
function
Function_and_product
ExamMARKS
pizza_topping
∙ invalid as identifiers:
1x
First name
exam_code$
lecturer-name
lecturerName&Phone
34
Identifiers (Variable Names)
• In Python, a variable is just a name, nothing more.
• An assignment statement associates the name to the left of the = symbol
with the object denoted by the expression to the right of the = .
• An object can have one, more than one, or no name associated with it.
• Consider the two code fragments below:
• In Python, variable names can contain uppercase and lowercase letters, digits
(but they cannot start with a digit), and the special character _.
• Python variable names are case-sensitive e.g., Julie and julie are different
names.
• Finally, there are a small number of reserved words (sometimes called
keywords) in Python that have built-in meanings and cannot be used as
variable names.
• Different versions of Python have slightly different lists of reserved words.
• The reserved words in Python 3 are:
– and , as , assert , break , class , continue , def , del , elif , else , except ,
False , finally , for , from , global , if , import , in , is , lambda ,
nonlocal , None , not , or , pass , raise , return , True , try , while ,
with , and yield .
36
Objects and Numerical Types
38
Data Types
∙ Data type of an object determines what values it can have and
what operations can be performed on it
∙ Example:
− Integer (int in Python): Positive or negative whole
numbers
− Floating point values (float in Python): Positive or
negative numbers with a fractional part
39
Data Types
• The built-in Python function type can be used to find out the
type of an object:
>>> type(3)
<class 'int'>
>>> type(3.142)
<class 'float'>
40
Data Types
∙ Program style
− Example: Values representing count can’t be fractional
· Note:
− Float type only stores approximations
− There’s a limit to the precision or accuracy of the stored float
values
− int are always exact 41
Data Types
43
Data Types
∙ Boolean values
− True and False. Their type is bool. Python names are “case-sensitive,”
so true is not the same as True:
>>> True
True
>>> False
False
∙ Integers
− Their type is int, and they can have as many digits as you want. They
may be preceded by a plus or minus sign. Separators such as commas
or periods are not used:
>>> 14
14
>>> −1
−1
>>> 1112223334445556667778889990000000000000 # a very large integer!
1112223334445556667778889990000000000000 44
Data Types
∙ Floats
− “Float” is an abbreviated version of the term “floating point,”
which refers to a number that is represented in computer
hardware in the equivalent of scientific notation.
− Such numbers consist of two parts: digits and an exponent.
− The exponent is adjusted so the decimal point “floats” to just
after the first digit (or just before, depending on the
implementation), as in scientific notation.
− The written form of a float always contains a decimal point and
at least one digit after it:
>>> 2.5
2.5
∙ Integer and Float are referred to as numerical types
45
Type Conversion
46
Type Conversion -- Examples
>>> int(4.5)
4 >>> round(3.14)
>>> int(3.9) 3
3 >>> round(-3.14)
>>> float(int(3.3)) -3
3.0 >>> round(3.5)
>>> int(float(3.3)) 4.0
3 >>> round(-3.5)
>>> int(float(3)) -4
3 >>> int(round(-3.14))
-3
47
Operators and Expressions
48
Operators and Expressions
∙ An operator is a symbol that indicates a calculation using one or more
operands.
∙ The combination of the operator and its operand(s) is an expression.
∙ Expressions produce or calculate new data values.
∙ The simplest kind of expression is a literal.
∙ A literal is used to indicate a specific value.
− Eg. 5
− In x=5, The RHS expression is being assigned to the variable x.
OR
− “James” is a literal
− name=“James”, The RHS expression is being assigned to the
variable name.
∙ A simple identifier can also be an expression.
− Eg. name OR module
49
Operators and Expressions
∙ There are two types of operators:
− A unary operator is one that is followed by a single operand.
− A binary operator is one that appears between two operands.
− It isn’t necessary to surround operators with spaces, but it is good style to do so.
− Plus and minus can be used as either unary or binary operators:
>>> −1
-1
>>> 4 + 2
6
>>> 4 − 1
3
>>> 4 * 3
12
∙ The power operator is ** (i.e., nk is written n ** k):
>>> 2 ** 10
1024
50
Operators and Expressions
∙ There are three operators for the division of one integer by another:
− / produces a float,
− // (floor division) an integer with the remainder ignored,
− and % (modulo) the remainder of the floor division.
∙ The formal definition of floor division is “the largest integer not
greater than the result of the division”:
>>> 11 / 4
2.75
>>> 11 // 4 # "floor" division
2
>>> 11 % 4 # remainder of 11 // 3
3
51
Operators and Expressions
a=222
b=365
a*a + b*b
52
Operators and Expressions
53
Operators and Expressions
Operators on objects of type int and float are:
Operator Operation
+ Addition
– Subtraction
* Multiplication
/ Division
// Integer Division
** Exponentiation
% Remainder
abs() Absolute value
54
Operators and Expressions
55
Boolean Operators
56
Variables and Assignments
∙ Assignment statements assign values to variables.
∙ An assignment statement binds a name to an object. Assignment
is denoted by a single equals sign:
name = value
∙ The assignment statement should be read from left to right as
assigning a name to an existing value.
∙ The basic assignment statement has this form:
<variable> = <expr>
− variable is an identifier, expr is an expression.
∙ The semantics of the assignment is that the expression on the right
side is evaluated to produce a value.
− The value is then associated with the variable named on the left side.
57
Variables and Assignments
∙ All an assignment statement does is name a value.
− That value can also have other names.
− Assigning a name to a value never changes that value, or any of its
other names.
− Examples:
>>> module1 = 'Problem Solving Techniques' # no value printed
>>> module2 = 'Programming and Data Structures'
>>> module2
'Programming and Data Structures’
>>> len(module2)
31
∙ Assignment statements may be chained together. This feature is used primarily to bind several names
to some initial value:
>>> a = b = c = 0
∙ Short-hand versions
>>> a = a + 1
>>> a += 1
58
Variables and Assignments
● It first binds the names pi and radius to different objects of type int. It then
binds the name area to a third object of type int.
● If the program then executes radius = 14 , the name radius is rebound to a
different object of type int , as shown in the right panel of the figure.
● Note : this assignment has no effect on the value to which area is bound. It
∙ As you can see from the final values of x and y, the swap was
successful in this case.
∙ This sort of three-way shuffle is common in other
programming languages.
∙ In Python, the simultaneous assignment statement offers an
elegant alternative. Here is a simpler Python equivalent:
x, y = y, x
65
Assigning Input
∙ The exercises and examples that we've seen so far have used assigned
values.
− For small bits of data, like short text sequences etc, we've simply
stored the data directly in a variable like this:
country = "Mauritius"
∙ When data is mixed in with the code in this manner, it is said to be
hard-coded.
∙ To get interactive input from the user in our programs, we can use the
input function.
∙ The purpose of an input statement is to get some information from the
user of a program and store it into a variable.
∙ User input makes our programs more flexible.
66
Assigning Input
67
Assigning Input
69
Assigning Input
70
Output statement
71
Output statement
∙ Using the meta-language, the following are the possible forms of print
statements:
− print()
− print (<expr>)
− print (<expr>, <expr>, ..., <expr>)
− print( <expr>, <expr>, ..., <expr>, end=“ ”)
∙ These templates essentially show that a print statement consists of the
keyword print followed by zero or more expressions, separated by
commas, within parentheses.
∙ The last print statement is to allow the next print to display on the
same line.
72
Exercise 10
∙ Predict the output of the program below when the
following inputs are given: 7,5
x,y= eval(input(“Give values for x and y: ”))
y= x*y
z=x+y
x,y,z=z+x, y+z, 2*z
print(“x=“,x, “y=“,y,”z=“,z)
73
Exercise 11
74
Math Library
75
Math Library - Exercise
# quadratic.py
# A program that computes the real roots of a quadratic equation
# Note: This program crashes if the equation has no real roots.
∙ Sample output:
This program finds the real roots to a quadratic
77
Acknowledgments
● DGT1039Y lectures notes by Dr. Shakun Baichoo,
FoICDT