0% found this document useful (0 votes)
23 views44 pages

Introduction to Python Programming Basics

This document serves as an introductory lesson to Python programming, covering essential topics such as programming style, data types, arithmetic operations, and Python's standard library. It emphasizes the modular nature of Python programs, the importance of identifiers, and the rules governing their use. Additionally, it discusses execution modes, logical structures, and operator precedence, providing a foundational understanding for beginners in Python programming.

Uploaded by

alanwong008
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)
23 views44 pages

Introduction to Python Programming Basics

This document serves as an introductory lesson to Python programming, covering essential topics such as programming style, data types, arithmetic operations, and Python's standard library. It emphasizes the modular nature of Python programs, the importance of identifiers, and the rules governing their use. Additionally, it discusses execution modes, logical structures, and operator precedence, providing a foundational understanding for beginners in Python programming.

Uploaded by

alanwong008
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

Lesson 2

Getting Start with Python Programming

Introduction to Computer Programming (CCIT4020), 2019-2020


Objectives

• Introduction to Python Programming


• Python’s Standard Library
• Identifiers
• Programming Style
• Data Types
• Arithmetic Operations
• Operator Precedence
and Associativity
• Variables

2
Introduction to Python Programming
• Python programs are modular which means that a program is
constructed from one or more functions or programs.

• To make a complicated problem more understandable


− Divide it into smaller, less complex sub-problems.

• Advantages
− Easy to write
− Easy to debug
− Easy to understand
− Easy to change

Figure 1. Python programs are modular

3
Introduction to Python Programming
(Continued)
• Top-down design and structured programming
– Techniques to enhance programming productivity

• Design should be easily readable and emphasize small module size.

Figure 2 Beginning of a hierarchy


chart for the car loan program.

Figure 3 Hierarchy chart for the car loan


4
program.
Introduction to Python Programming
(Continued)
• Apply four types of logical structures (programming techniques):

– Sequence – Statements executed one after the other

– Selection – blocks of code executed based on test of some


condition

– Repetition – blocks of coded executed repeatedly based on


some condition

– Function – blocks of coded that solves a specific problem by


using built-in functions or programmer created functions.

5
Introduction to Python Programming
(Continued)
• Execution Modes in Python
– File: A Python file is any file that contains code. Most Python files have the
extension .py.

– Script: A Python script is a group of statements that you intend to execute


from the command line to accomplish a task.

– Module: A Python module is a file that you intend to import from within
another module or a script

File

Script

6
Figure 4 IDLE
Introduction to Python Programming
(Continued)
• Block structure
– Python is referred to as a block-structured language. Blocks can be nested within
other blocks.

Block structure

Figure 5. Program example above, the decision structure block is


nested inside the repetition block.

7
Python’s Standard Library
• Python comes with a library of standard modules, described in a separate
document, the Python Library Reference.

• Some modules are built into the interpreter


– These provide access to various operations that are not part of the core
of the language

• Modules can import other modules

• Example: To import a module, keyword import is typed at the top of a


program.

import math

8
Python’s Standard Library (Continued)
• Python’s standard library is very extensive, offering a wide range of functionalities.

• Python standard library has large collection of modules or built-in functions


Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() import()
complex() hash() min() set()
delattr() help() next() setattr()
dict() hex() object() slice()
9
Table 1. Built-in functions
Identifiers
• Program consists of Words and Symbols, such as
- Words for the name of function print, and variables dollars
- Symbols pound sign # and brackets ‘ ’

• These words are collectively referred to as identifiers

Program 2.1
Words

Symbols

Identifiers

10
Identifiers (Continued)
• Several special Symbols will be found (#, ", ()) in the program.
They are used in almost every program.

Symbol

Table 2. Symbols

11
Identifiers (Continued)
• Identifiers are the names that identify the elements such as variables and
functions in a program.

• All identifiers must obey the following rules:


– An identifier is a sequence of characters that consists of letters, digits, and
underscores (_).
– An identifier must start with a letter or an underscore. It cannot start with a
digit.
– An identifier cannot be a keyword (also called reserved words), have
special meanings in Python.
• For example, import is a keyword, which tells the Python interpreter to
import a module to the program.
– An identifier can be of any length.

12
Identifiers (Continued)
Reserved Words
• The following 33 reserved words (keywords) are reserved by the Python
programming language, and cannot be used for anything other than their
predefined purpose in Python.

Table 3 Reserved words

13
Identifiers (Continued)
• Programmer-created identifiers: Created by the programmer

– Also called programmer-created names

– Used for naming data and functions

– Must conform to Python’s identifier rules

– Can be any combination of letters, digits, or underscores (_)


subject to the naming rules:

14
Identifiers (Continued)
• Examples of legal identifiers
– area,
– radius, and
– number1

• Example of invalid (illegal) identifiers


– 2A
– d+4
– A B

• When Python detects an illegal identifier, it reports a syntax error


and terminates the program.

15
Identifiers (Continued)
• All uppercase letters used to indicate a constant, e.g. MAXSIZE
– A constant is a type of variable whose value cannot be changed
(permanent value).

• A function name must be followed by parentheses , e.g. print()

• An identifier should be descriptive: degToRadians()


– Descriptive identifiers make programs easy to read.
– numberOfStudents is better than numStuds
– Bad identifier choices: easy, duh, justDoIt

• Python is a case-sensitive language


– TOTAL, Total and total represent different identifiers
16
The print() Function
• Used to display data (e.g. numbers and strings) on the monitor
– If n is a number, print(n) displays number n.
– The print function can display the result of evaluated
expressions
– A single print function can display several values

• (More information will be in Unit 3)


Program 2.2 Program 2.3

17
Programming Style
• Programming style deals with what programs look like.

• When you create programs with a professional programming style, they not only
execute properly but are easy for people to read and understand.

• This is very important if other programmers will access or modify your programs.

• A consistent spacing style makes programs clear and easy to read, debug (find and
fix errors), and maintain.

18
Programming Style (Continued)
• Use 4 spaces per indentation and no tabs. (Do not mix tabs and spaces. Tabs create confusion
and it is recommended to use only spaces.)

• Maximum line length : 79 characters which help users with a small display.

• Use blank lines to separate top-level function and class definitions and single blank line to separate
methods definitions inside a class and larger blocks of code inside functions.

• When possible, put inline comments (should be complete sentences).

• Use spaces around expressions and statements.

• Don’t put any punctuation at the end of a statement. For example, the Python interpreter will report
errors for the following code:

# Display two messages


print("Welcome to Python").
print("Python is fun"),

• Python programs are case sensitive. It would be wrong, for example, to replace print in the
program with Print.
19
Programming Style: Indentation
• Except for indentation, strings, function names, and reserved words, Python ignores all
white space
– White space: any combination of one or more blank spaces, tabs, or new lines

• Indentation is another sign of good programming practice, especially if the same


indentation is used for similar groups of statements

• Note that the statements are entered from the first column in the new line. The Python
interpreter will report an error if the program is typed as follows:

# Display two messages


print("Welcome to Python")
print("Python is fun")

20
Programming Style: Comments
• Comments are notes of explanations that document lines or sections of a
program (
– clarify what a program does

• Comments are part of the program, but the Python interpreter ignores
them.

• Python begins a comment with the # character.

• Two types of comments:


– Full line comment
» # This program calculates net pay
– End-line comment
» print (“John Smith”) # Display the name

21
Programming Style: Comments
(Continued)
Program 2.4

Comment

Program 2.5

End line comment

22
Data Types
• Data type: set of values and a set of operations that can be applied to
these values

• Python has two numeric types—integers and floating-point numbers—for


working with the operators +, -, *, /, //, **, and %.

• The information stored in a computer is generally referred to as data.


There are two types of numeric data: integers and real numbers.

– Integer types (int for short) are for representing whole numbers.
– Real types are for representing numbers with a fractional part.

• Inside the computer, these two types of data are stored differently.
– Real numbers are represented as floating-point (or float) values.

23
Data Types (Continued)
• A number that has a decimal point is a float even if its fractional part is 0.

• For example, 1.0 is a float, but 1 is an integer. These two numbers are
stored differently in the computer.

• In the programming terminology, numbers such as 1.0 and 1 are called


literals.

• A literal is a constant value that appears directly in a program.

• The operators for numeric data types include the standard arithmetic
(math) operators.

• The operands are the values operated by an operator.

24
Data Types (Continued)

• Numbers are referred to as numeric literals

• Two Types of numbers: ints and floats


– Whole number written without a decimal point called an int
– Number written with a decimal point called a float

• int: whole numbers (integers)


– For example: 0, -10, 253, -26351
– Not allowed: commas, decimal points, special symbols

• float: A floating-point value (real number) (float type) can be the number zero or any
positive or negative number that contains a decimal point
– For example: +10.625, 5., -6.2, 3251.92, +2
– Not allowed: commas, special symbols

25
Floating-Point Data Type

• Why are they called floating-point numbers?


– These numbers are stored in scientific notation in memory.

– When a number such as 50.534 is converted into scientific notation,


such as 5.0534E+1, its decimal point is moved (floated) to a new
position.

• When a variable is assigned a value that is too large (in size) to be stored
in memory, it causes overflow.
– For example, executing the following statement causes overflow.

>>> 245.0 ** 100000000


OverflowError: 'Result too large'

26
Scientific Notation

• Floating-point values can be written in scientific notation in the form of


a * 10b.
– The scientific notation for 123.456 is 1.23456 x 102 and for 0.0123456 is
1.23456 x 10-2

• Python uses a special syntax to write scientific notation numbers.


– 1.23456 x 102 is written as 1.23456E2 or 1.23456E+2, and 1.23456 x 10-2
as 1.23456E-2.

• The letter E (or e) represents an exponent and can be in either


lowercase or uppercase.

27
Arithmetic Operations
• A programmer’s tools for performing calculations (arithmetic
operations) are math operators, and the following are provided by
Python:
– Addition +
– Subtraction -
– Multiplication *
– Float Division /
– Integer Division //
– Modulus Division (Remainder) %

• Binary operators require two operands

• An operand can be either a literal value or an identifier that has a


value associated with it

28
Arithmetic Operations (continued)

Table 4. Math (arithmetic) operators

Table 5. Examples of math operations 29


Arithmetic Operations (continued)
• The +, -, and * operators are straightforward, but note that the + and -
operators can be both unary and binary.

• A unary operator has only one operand


-5

• A simple binary arithmetic expression consists of a binary


arithmetic operator connecting two literal values in the form:
– literalValue operator literalValue
•3 + 7
• 12.62 - 9.8
• 0.08 * 12.2
• 12.6 / 2.0

• Spaces around arithmetic operators are inserted for clarity and can be
omitted without affecting the value of the expression 30
The /, //, and ** Operators
• The / operator performs a float division that results in a floating
number.
>>> 4 / 2
2.0
>>> 2 / 4
0.5

• The // operator performs an integer division; the result is an integer,


and any fractional part is truncated.
>>> 5 // 2
2
>>> 2 // 4
0

31
The /, //, and ** Operators (Continued)

Integer Division Operator //


• When an integer is divided by an integer with the Integer Division
Operator //, the result will also be an integer.

Program 2.6
num_add = 17 + 5 # the answer will be 22
num_div_int = 3 / 2 # the answer is 1.5;
num_div_intB = 3 // 2 # the answer is 1;
# 0.5 is the fractional part
# and it is truncated.
num_div_real = 3.0 / 2.0 # the answer is 1.5
num_div_realB = 3.0 // 2.0 # the answer is 1.0

32
The /, //, and ** Operators (Continued)
• To compute (a with an exponent of b) for any numbers a and b,
you can write a ** b in Python.
>>> 2.3 ** 3.5
18.45216910555504
>>> (-2.5) ** 2
6.25

• The % operator, known as remainder or modulo operator, yields


the remainder after division.
– E.g. 20 % 13 = 7

33
Figure 6 Remaider after division
Operator Precedence
and Associativity
• Python expressions are evaluated in the same way as arithmetic
expressions.

• Writing a numeric expression in Python involves a straightforward


translation of an arithmetic expression using operators.

• Operators contained within pairs of parentheses are evaluated


first. Parentheses can be nested, in which case the expression in
the inner parentheses is evaluated first.

• When more than one operator is used in an expression, the


operator precedence rule is used to determine the order of
evaluation.

34
Operator Precedence
and Associativity(Continued)
• Expression: any combination of operators and operands that can
be evaluated to yield a value

• Integer expression: contains only integer operands; the result is


an integer

• Floating-point expression: contains only floating-point operands;


– Result of a division is always a float

35
Operator Precedence
and Associativity
• Two binary arithmetic operator symbols must never be placed side
by side
– E.g. 5 * % 6 is INVALID

• Parentheses may be used to form groupings


– Expressions in parentheses are evaluated first
– E.g. (6 + 4) / (2 + 3)

• Parentheses may be enclosed by other parentheses


– E.g. (2 * (3 + 7))/5

• Parentheses cannot be used to indicate multiplication


– E.g. (6 + 4)(2 + 3) is INVALID
36
Operator Precedence
and Associativity (continued)
• In addition to simple expressions as (6 + 4) and with
Parentheses as (6 + 4) / (2 + 3) Parentheses , more
complex arithmetic expressions can be created without
parentheses

• In these cases, the operations will be evaluated according to the


precedence and associativity of the operators
• Precedence is the priority order ranked for a set of operators

• Associativity is related to the order in which operators of the


same precedence are evaluated (from left to right, or from right
to left)

37
Operator Precedence
and Associativity (continued)
• Four levels of precedence:

1. Terms inside parentheses (inner to outer)

2. Exponentiation (**) is applied first.

3. Multiplication (*), float division (/), integer division (//) , and


remainder operators (%) are applied next. If an expression
contains several multiplication, division, and remainder
operators, they are applied from left to right.

4. Addition (+) and subtraction (-) operators are applied last. If an


expression contains several addition and subtraction operators,
they are applied from left to right.
38
Operator Precedence and
Associativity (continued)
• Here is an example of how an expression is
evaluated:

Figure 7 Evaluation

39
Variables
• In mathematics problems, quantities are referred to by names

• Names given to the values are called variables

• A variable is a name that represents a value stored in the


computer’s memory.

Program 2.7: uses speed, time … calculates distance

Assignment statement
(Value is assigned to a variable)

40
Variables (Continued)
• Variable names in Python
– Begin with letter or underscore _
– Can only consist of letters, numbers, underscores

• Recommend using descriptive variable names

• Use the underscore character to represent a space

• Convention will be
– Begin with lowercase
– Use cap for additional “word” in the name
– Example: rateOfChange (camelCase naming convention)

41
Variables (Continued)
• Use variable names that indicate what the variable corresponds to, rather
than how it is computed

• Add qualifiers, such as Avg, Min, Max, and Sum to complete a variable’s
name where appropriate

• Use single-letter variable names, such as i, j, and k, for loop indexes

A retail business is planning to have a storewide sale where the prices of all
items will be 20 percent off. Write a program to calculate the sale price of an
item after the discount is subtracted.
Program 2.8 Output
original_price = 300.0
discount = original_price * 0.2
sales_price = float(original_price – discount)
print("The sale price is " , sales_price)

42
Dot Notation in Python
• The dot notation (or dot operator (.) ) is used to refer to related functions (or methods), classes etc.
that is inside a Python module.

• All data in Python are actually objects.

• Objects not only store data, but they respond to special functions that only the objects of the same
type/class understand.
– It is used to access the instance variable and methods of the class using objects (Unit 11)

[Link](…)

object in front of the dot (.) is calling a method that is


associated with that object’s type.

Program 2.9

43
References

• Contents of this note are extracted and modified


from:
– David I. Schneider (2016). An Introduction to
Programming Using Python(Global Edition) Pearson
(Chapter 2)
– Python Official Website: [Link]

• This set of slides is for teaching purpose only.

44

You might also like