0% found this document useful (0 votes)
7 views78 pages

02 Python Intro

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 78

Introduction to Python

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

∙ A Python program, sometimes called a script, is a


sequence of definitions and commands.
∙ a program is a sequence of definitions and commands
– definitions evaluated
– commands executed by Python interpreter in a shell
∙ commands (statements) instruct interpreter to do
something
– can be typed directly in a shell or stored in a file that is
read into the shell and evaluated

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?

∙ Storing Data values


− To store data values, programs make use of variables
∙ Variables have a type but are never declared in Python.
∙ They are instantiated when they are assigned for the first
time.
− Example
x =5
y=10
z=x+5

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

* / // % Multiplication, division, floor division, and modulus

+ - Addition and subtraction

== != > >= < <= is is not in not in Comparisons, identity, and membership operators

not Logical NOT

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)

∙ What do we expect to see when the program is run?


∙ The program always gives the same output because the
variables lecturer_name and module always have the same
values.
∙ In general, we want programs to obtain values from the user
and the outputs will depend on values given by the user.
∙ To obtain values from the user, a program has to perform
inputs.
23
Performing String Inputs
∙ In Python versions 3.x, the input of string (i.e
non-numerical) values can be performed through the
function input()
∙ Eg. The following lines allow the user to input a sequence
and display back the same:

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.

lecturer_name=input("Name of lecturer: ")


module=input("Module: ")
print (lecturer_name, "teaches", module)

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.

x=eval(input(“Give a value for x:”))


y= eval(input(“Give a value for y:”))
print ("The Value of x is:", x)
print ("The value of y is:",y)
print("The sum of the values is", x+y)

28
Exercise 8

∙ Write a program that allows the input of


numerical values for variables x and y and then
calculates and displays the product of x and y

29
Exercise 1.9

∙ Write a program that allows the input of the


radius of a circle and calculates and displays
the area of that circle

30
Python Basics Part 2
The Python Shell

• The symbol >>> is a shell prompt indicating that the interpreter


is expecting the user to type some Python code into the shell.
The line below the line with the prompt is produced when the
interpreter evaluates the Python code entered at the prompt, as
illustrated by the following interaction with the interpreter:
>>> 3 + 2
5

>>> 3.0 + 2.0


5.0

>>> 3 != 2
True
32
Identifiers (Variable Names)

∙ Python has some rules about how identifiers are formed.


− Every identifier must begin with a letter which may be
followed by any sequence of letters and digits.
− The only exception is the underscore character (the “_”
character), which is treated in a similar way to a letter.
− This implies that a single identifier cannot contain any
spaces.
∙ It's also important to remember that variable names are
case-sensitive, so my_name, MY_NAME,My_NAME and
My_Name are all separate variables.
− Technically this means that you could use all four of those names in a
Python program to store different values, but please don't do this !!!

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:

• As far as Python is concerned, they are not different.


– When executed, they will do the same thing.
– To a human reader, however, they are quite different.
– Either the variable should have been named radius rather than
diameter, or diameter should have been divided by 2.0 in the
calculation of the area.
35
Identifiers (Variable Names)

• 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

• Objects are the core things that Python programs manipulate.


– Every object has a type that defines the kinds of things that
programs can do with that object.
• Types are either scalar or non-scalar.
– Scalar objects are indivisible.
• Think of them as the atoms of the language.
– Non-scalar objects, for example strings, have internal
structure.
• Many types of objects can be denoted by literals in the text of a
program.
– For example, the text 2 is a literal representing a number
and the text 'abc' a literal representing a string.
37
Objects and Numerical Types

• Python has four types of scalar objects:


– int is used to represent integers. Literals of type int are
written in the way we typically denote integers (e.g., -3 or 5
or 10002 ).
– float is used to represent real numbers. Literals of type float
always include a decimal point (e.g., 3.0 or 3.17 or -28.72).
• For example, the literal 1.6E3 stands for 1.6 * 103 , i.e.,
it is the same as 1600.0 .)
– bool is used to represent the Boolean values True and False
– None is a type with a single value – more details in the next
slides.

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

∙ Efficiency of various operations


− Underlying algorithms that perform computer arithmetic are
simpler, and thus faster, for integers than more general
algorithms required for float values

· 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

∙ Computer programs manipulate data.


∙ An individual item of data is called a value.
∙ Every value in Python has a type that identifies the kind of
value it is.
∙ Simple Values
− Types for some simple kinds of values are an integral part
of Python’s implementation. Four of these are used far
more frequently than others:
· logical (Boolean),
· integer,
· float,
∙ and string (to be discussed in more detail afterwards).
And the special no-value value called None. 42
Data Types
∙ When you enter a value in the Python interpreter, it prints it on
the following line:
>>> 90
90
>>>
∙ When the value is None, nothing is printed, since None means
“nothing”:
>>> None
>>>

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

∙ Sometimes values of one data type need to be converted


to another
− The float() function converts an int to a float
− The int() function converts numbers into ints
− The round() function rounds a float off to the nearest
whole number and returns a float

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

• Objects and operators can be combined to form expressions,


each of which evaluates to an object of some type. We will refer
to this as the value of the expression.
– For example:
• the expression 3 + 2 denotes the object 5 of type int, and
• the expression 3.0 + 2.0 denotes the object 5.0 of type
float.

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

∙ More complex and interesting expressions can be constructed, by


combining simple expressions, through the use of operators.

a=222
b=365
a*a + b*b

52
Operators and Expressions

• The == operator is used to test whether two expressions evaluate


to the same value,
– and the != operator is used to test whether two expressions
evaluate to different values.
• While a single = means something quite different
– Be careful, people make the mistake of typing “ = ” when
s/he actually meant to type “ == ”.
– Keep an eye out for this error.

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

• The arithmetic operators have the usual mathematical


precedence.
– For example, * binds more tightly than + ,
• so the expression x+y*2 is evaluated by first multiplying
y by 2 and then adding the result to x. The order of
evaluation can be changed by using parentheses to
group subexpressions, e.g., (x+y)*2 first adds x and y ,
and then multiplies the result by 2 .

55
Boolean Operators

• The primitive operators on type bool are and , or , and not :


– a and b is True if both a and b are True , and False otherwise.
– a or b is True if at least one of a or b is True , and False
otherwise.
– not a is True if a is False , and False if a is True .
A B A or B A and B not A

True True True True False

True False True False False

False True True False True

False False False False True

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

• Variables provide a way to


associate names with objects.
Consider the code
pi = 3
radius = 11
area = pi * (radius**2)
radius = 14

● 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

is still bound to the object denoted by the expression 3*(11**2) .


59
Variables and Assignments

∙ A variable can be assigned many times.


∙ It always retains the value of the most recent assignment.
∙ Here is another interactive Python session that demonstrates the
point:
>>> myVar = 0
>>> myVar
0
>>> myVar = 7
>>> myVar
7
>>> myVar = myVar + 1
>>> myVar
8
60
Comments

• A good way to enhance the readability of code is to add comments.


• Text following the symbol # is not interpreted by Python.
• For example, one might write:
side = 1 #length of sides of a unit square
radius = 1 #radius of a unit circle
#subtract area of unit circle from area of unit square
areaC = pi*radius**2
areaS = side*side
difference = areaS – areaC
• Can also have multiple-line comments, enclosed between """ """
"""
This is a sample
Multi-line comment
""" 61
Simultaneous Assignments
∙ There is an alternative form of assignment statement which allows multiple
variables to be assigned at the same time
− A Simultaneous assignment allows us to calculate several values all at
the same time
∙ The general format is:
<var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>
∙ Eg.
sum, diff = x+y, x-y
student_name, module=“James”,”Problem Solving Techniques”
∙ This tells python to evaluate the expressions on the RHS and then assign
these values to the variables on the LHS.
− Although this form of assignment statement can look strange, initially, it
can actually prove extremely useful, as shown in the next slide.
62
Simultaneous Assignments
∙ Example of use of simultaneous assignment
− Suppose you have two variables x and y and you want to swap
the values.
− We can consider the following
x=y
y=x
− Let initial value of x be 2 and that of y be 4
# variables x y
# initial values 2 4
x=y
# now 4 4
y=x
# final 4 4
63
Simultaneous Assignments
∙ One way to make the swap work is to introduce an additional
variable that temporarily remembers the original value of x.
temp = x
x=y
y = temp
# variables x y temp
# initial values 2 4 no value yet
temp = x
# 2 4 2
x=y
# 4 4 2
y = temp
# 4 2 2 64
Simultaneous Assignments

∙ 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

∙ Input of string values is accomplished using an assignment


statement combined with a special expression called input.
∙ The standard form is
<variable> = input(<prompt>)
∙ Here prompt is an expression that serves to prompt the user for
input; this is almost always a string literal
− (i.e., some text inside of quotation marks).
− Example
>>>name = input("Student name: ")
# do something with the name variable

67
Assigning Input

∙ When Python encounters an input expression, it displays the prompt on


the screen.
∙ Python then pauses and waits for the user to type one or more values and
press the <Enter> key.
∙ Eg.
>>> module = input("Enter module name: ")
∙ When this statement is executed, the user will see the prompt
"Enter module name:
∙ When the user gives the value, it will be stored in the variable module.
Note: The prompt in the input statement is optional. In the absence of a
prompt, the program will wait for input without any message to the user.
68
Assigning Input

∙ To input numerical values, we need to use eval(input()).


∙ The general form is: eval(input(<prompt>))
Eg.
x = eval(input("Please enter a number between 0 and 1: "))
seqLen=eval(input(”Enter length of sequence: "))

69
Assigning Input

∙ Simultaneous assignment can also be used to get multiple values


from the user in a single input.
∙ Eg.
score1, score2 =eval( input("Enter two scores separated by a comma: "))

70
Output statement

∙ What is the general syntax (rules) of Output Statements?


− i.e What exactly can a print statement contain?
∙ We need a way to express general syntax.
− Computer Scientists have developed what are known as
meta-languages, for describing programming languages.

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

∙ Write a program that allows the input of two integer


values, x and y and displays the quotient and remainder
obtainable when x is divided by y.

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.

import math # Makes the math library available


print(“This program finds the real roots to a quadratic”)
print()
a, b, c = eval(input(“Please enter the coefficients (a, b, c): ”))
discRoot = math.sqrt(b * b - 4 * a * c)
root1 = (–b + discRoot) / (2 * a)
root2 = (–b - discRoot) / (2 * a)
print()
print( “The solutions are: ”, root1, “ and ”, root2)
76
Math Library

∙ Sample output:
This program finds the real roots to a quadratic

Please enter the coefficients (a, b, c): 3, 4, -2

The solutions are: 0.387425886723 and -1.72075922006

77
Acknowledgments
● DGT1039Y lectures notes by Dr. Shakun Baichoo,
FoICDT

You might also like