CS计算机代考程序代写 python algorithm chain interpreter Title arial bold 28pt

Title arial bold 28pt

Lecture 1
Introduction & Preliminaries
SMM283
Introduction to Python

www.cass.city.ac.uk

1

QUESTIONS AND ANSWERS
How do we communicate with the computer?

Programming languages

How do we get computers to perform complicated tasks?

Tasks are broken down into a sequence of instructions

Why Python?

Powerful, easy to download, write and read

www.cass.city.ac.uk
QUESTIONS AND ANSWERS
When was Python invented and by whom?

Early 1990s: Guido van Rossum

invented the Python programming language

Python is a high-level, general-purpose programming language for solving problems on modern computer systems

Useful resources at www.python.org

www.cass.city.ac.uk
How did the language Python get its name?

Named for the British comedy group Monty Python (really!)

We will be using the editor IDLE to create programs. How did IDLE get its name?

Stands for Integrated DeveLopment Environment

What is an interpreted language?

Uses an interpreter, translates high-level language one statement at a time into machine language and then runs
QUESTIONS AND ANSWERS

www.cass.city.ac.uk
QUESTIONS AND ANSWERS
What are the meanings of the terms “programmer” and “user”?

Programmer: a person who solves problems by writing programs on a computer

User: any person who runs a program

What is the meaning of the term “code”?

Python statements that the programmer writes

www.cass.city.ac.uk
QUESTIONS AND ANSWERS
Are there certain characteristics that all programs have in common?

Input, processing, output

What are the meanings of the terms “hardware” and “software”?

Hardware: physical components of the computer

Software: the programs

www.cass.city.ac.uk
QUESTIONS AND ANSWERS
How are problems solved with a program?

Step-by-step procedure devised to process given data and produce requested output.

What is a zero-based numbering system?

Numbering begins with zero instead of one

Prerequisites to learning Python?

Be familiar with how folders and files are managed

www.cass.city.ac.uk
QUESTIONS & ANSWERS
What conventions are used to show keystrokes?

key1+key2 means “hold down key1 and then press key2”

Ctrl+C places selected material into the Clipboard

key1/key2 means “Release key1 and then press key2”

Alt/F opens the FILE menu on a menu bar.

www.cass.city.ac.uk
QUESTIONS AND ANSWERS
How can the programs for the examples in the lectures be obtained?

They will be uploaded on Moodle after each class.

Where will new programs be saved?

Create a special folder to hold your programs

Where can I research questions I have about Python?

Documentation at https://www.python.org/doc/

www.cass.city.ac.uk
PROGRAM DEVELOPMENT CYCLE
FIGURE 1.0 The problem solving process.

www.cass.city.ac.uk
PROGRAM PLANNING
Analyze: Define the problem.

Design: Plan the solution to the problem.

Code: Translate the algorithm into a programming language.

Test and correct: Locate and remove any errors in the program.

Complete the documentation: Organize all the material that describes the program.

www.cass.city.ac.uk
PROGRAMMING TOOLS
Algorithms

Flowcharts

Pseudocode

Hierarchy charts

www.cass.city.ac.uk
FLOWCHART SYMBOLS

www.cass.city.ac.uk
PSEUDOCODE
Abbreviated plain English version of actual computer code

Symbols used in flowcharts replaced by English-like statements

Allows programmer to focus on steps required to solve problem

www.cass.city.ac.uk
HIERARCHY CHART
Shows the overall program structure

Depict organization of program, omit specific processing logic

Describe what each part, or module, of the program does

Each module subdivided into a succession of submodules

www.cass.city.ac.uk
DECISION STRUCTURE
FIGURE 1.1 Pseudocode and flowchart for a decision structure.

www.cass.city.ac.uk
REPETETIVE STRUCTURE
FIGURE 1.2 Pseudocode and flowchart for a loop.

www.cass.city.ac.uk
BEHIND THE SCENES: HOW DOES PYTHON WORK?

FIGURE 1.3 Steps in interpreting a Python program

www.cass.city.ac.uk
DETECTING AND CORRECTING SYNTAX ERRORS
Programmers inevitably make typographical errors when editing programs, called syntax errors

The Python interpreter will usually detect these

Syntax: rules for forming sentences in a language

When Python encounters a syntax error in a program, it halts execution with an error message

www.cass.city.ac.uk
THE IDLE – PYTHON PROGRAMMING INTERACTIVE SHELL

www.cass.city.ac.uk
STARTING THE IDLE

Windows:
Invoke with double click of

MAC:
Open Finder, select Applications, select the Utilities folder, select Terminal, and then enter IDLE at the prompt

LINUX and UNIX: usually be found at /usr/bin/idle3

FIGURE 1.0 IDLE tile from Windows

www.cass.city.ac.uk
STARTING THE IDLE
FIGURE 1.1 The Python shell.

www.cass.city.ac.uk
STARTING THE IDLE
FIGURE 1.1 The Python shell after the
expression 4 + 10 has been evaluated.

www.cass.city.ac.uk
FIGURE 1.2 The Python shell after the
statement print(“Hello World!”) has been executed.
STARTING THE IDLE

www.cass.city.ac.uk
A PYTHON CODE EDITOR WALKTHROUGH
FIGURE 1.3 The File drop-down list; new file and the editor.

Type Python code here

www.cass.city.ac.uk
FIGURE 1.4 The code editor window
containing a three-line Python program.
A PYTHON CODE EDITOR WALKTHROUGH

www.cass.city.ac.uk
A PYTHON CODE EDITOR WALKTHROUGH
FIGURE 1.4 A Save As dialog box.

Name it
Browse in a folder you wish to save it to.

www.cass.city.ac.uk
A PYTHON CODE EDITOR WALKTHROUGH
FIGURE 1.5 The code editor window containing
a three-line Python program.

DO NOT WORRY IF YOU DO NOT UNDERSTAND EVERYTHING IN THE CODE AT THIS POINT!
WE WILL COVER THEM IN DETAIL LATER.

www.cass.city.ac.uk
FIGURE 1.6 Press the F5 key to execute.
The outcome of the Python program in Fig. 1.3.
A PYTHON CODE EDITOR WALKTHROUGH

www.cass.city.ac.uk
A PYTHON CODE EDITOR WALKTHROUGH
FIGURE 1.7 A Save message box.

Notice the program is not previously saved

DO NOT WORRY IF YOU DO NOT UNDERSTAND EVERYTHING IN THE CODE AT THIS POINT!.
WE WILL COVER THEM IN DETAIL LATER.

www.cass.city.ac.uk

30

AN OPEN-A-PROGRAM WALKTHROUGH
FIGURE 1.8 An Open dialog box.

Click on desired program

www.cass.city.ac.uk
AN OPEN-A-PROGRAM WALKTHROUGH
FIGURE 1.9 Example

www.cass.city.ac.uk
AN OPEN-A-PROGRAM WALKTHROUGH
FIGURE 2.0 Example

DO NOT WORRY IF YOU DO NOT UNDERSTAND EVERYTHING IN THE CODE AT THIS POINT!
WE WILL COVER THEM IN DETAIL LATER.

www.cass.city.ac.uk
AN OPEN-A-PROGRAM WALKTHROUGH
FIGURE 2.1 Example

DO NOT WORRY IF YOU DO NOT UNDERSTAND EVERYTHING IN THE CODE AT THIS POINT.!
WE WILL COVER THEM IN DETAIL LATER.

www.cass.city.ac.uk
The File Drop-down Menu
FIGURE 2.3 The File drop-down menu.

www.cass.city.ac.uk
CORE OBJECTS, VARIABLES, INPUT, AND OUTPUT

www.cass.city.ac.uk
NUMBERS IN PYTHON
Numbers are referred to as numeric literals

Two broad 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

www.cass.city.ac.uk
NUMBERS IN PYTHON
Arithmetic Operators

Addition, subtraction, multiplication, division, and exponentiation.

Result of a division is always a float

Result of the other operations is a float if …

Either of the numbers is a float

Otherwise is an int.

www.cass.city.ac.uk
THE print FUNCTION
Used to display numbers 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

Example: Program demonstrates operations

www.cass.city.ac.uk

39

VARIABLES IN PYTHON

In mathematics problems, quantities are referred to by names

Names given to the values are called variables

Example: Program uses revenue, costs … calculates profit

Example: Program uses stock spot price, outstanding shares … calculates the equity value

www.cass.city.ac.uk
VARIABLES IN PYTHON
Assignment statements

Expression on right evaluated

That value assigned to variable

www.cass.city.ac.uk
VARIABLES IN PYTHON
Variable names in Python

Begin with letter or underscore _

Can only consist of letters, numbers, underscores

Recommend using descriptive variable names

Convention will be

Begin with lowercase

Use cap for additional “word” in the name

Example: rateOfChange

www.cass.city.ac.uk
VARIABLES IN PYTHON
Names in Python are case-sensitive

There are thirty-three words, called reserved words (or keywords)

Have special meanings in Python

Cannot be used as variable names

www.cass.city.ac.uk
THE abs(),int(),round() FUNCTIONS

Example: Program evaluates functions, prints results

www.cass.city.ac.uk
AUGMENTED ASSIGNMENTS
Remember: expression on right side of assignment statement evaluated before assignment is made

var = var + 1

Python has special operator to accomplish same thing

var += 1

Often referred as short-cut operators

www.cass.city.ac.uk
AUGMENTED ASSIGNMENTS
Example:
Program illustrates different augmented assignment operators.

[Run]

www.cass.city.ac.uk
TWO OTHE INTEGER OPERATORS
Integer division operator

Written //

Modulus operator

Written %

Example:

[Run]

www.cass.city.ac.uk
PARENTHESES, ORDER OR PRECEDENCE
Parentheses used to clarify meaning of an expression

Order of precedence

Terms inside parentheses (inner to outer)

Exponentiation

Multiplication, division (ordinary and integer), modulus

Addition and subtraction

www.cass.city.ac.uk
SYNTAX ERRORS
Grammatical and punctuation errors are called syntax errors.
TABLE 1.0 Three Syntax Errors

FIGURE 1.1 Syntax error message boxes.

www.cass.city.ac.uk
Runtime Errors
Errors discovered while program is running called runtime errors or exceptions
Table 2.2 Three Runtime Errors

www.cass.city.ac.uk
RUNTIME ERRORS
When Python encounters exception

Terminates execution of program, displays message
FIGURE 1.2 An Error Message for an Exception Error

www.cass.city.ac.uk
LOGIC ERRORS
Occurs when a program does not perform the way it was intended

Example
average = firstNum + secondNum / 2

Syntax correct, logic wrong: should be

average = (firstNum + secondNum) / 2

Logic errors are most difficult type of error to locate

www.cass.city.ac.uk
NUMERIC OBJECTS IN MEMORY
Consider this code:

This is
what
happens:

FIGURE 1.3 Numeric objects in memory.

www.cass.city.ac.uk
STRINGS IN PYTHON

www.cass.city.ac.uk
STRING LITERALS
Sequence of characters that is treated as a single item

Written as a sequence of characters surrounded by either single quotes (‘) or double quotes (“).

Opening and closing quotation marks must be the same type

www.cass.city.ac.uk
STRING VARIABLES
Variables also can be assigned string values

Created (come into existence) the first time they appear in assignment statements

When an argument of a print statement

Quotation marks not included in display

www.cass.city.ac.uk
INDICES AND SLICES
Position or index of a character in a string

Identified with one of the numbers 0, 1, 2, 3, . . . .
FIGURE 1.0 Indices of the characters of
the string “spam & eggs”.

If str1 is a string, then str1[m:n] is the substring beginning at position m and ending at position n – 1
Example “spam & eggs”[2:7]

FIGURE 1.1 Aid to visualizing slices.

www.cass.city.ac.uk
INDICES AND SLICES
Example: Program shows use of indices

Run

www.cass.city.ac.uk
NEGATIVE INDECES
Python allows strings to be indexed by their position with regards to the right

Use negative numbers for indices.

FIGURE 1.2 Negative indices of the characters of
the string “spam & eggs”.

www.cass.city.ac.uk
NEGATIVE INDICES
Program illustrates negative indices.
Program illustrates default bounds

Run

Run

www.cass.city.ac.uk
STRING CONCATENATION & REPETITION
Two strings can be combined to form a new string

Consisting of the strings joined together

Represented by a plus sign

Combination of strings, plus signs, functions, and methods can be evaluated

Called a string expression

Asterisk operator can be used with strings to repeatedly concatenate a string with itself

www.cass.city.ac.uk
STRING FUNCTIONS AND METHODS
Table 1.3 String Operations (str1 = “Python”)

www.cass.city.ac.uk
CHAINED METHODS
Lines can be combined into a single line said to chain the two methods

Executed from left to right

www.cass.city.ac.uk
THE input FUNCTION
Prompts the user to enter data

User types response, presses ENTER key

Entry assigned to variable on left

Note:
In Python 2.7, raw_input() returns a string, and input() tries to run the input as a Python expression.
In Python 3 .4  input() returns a string. If you want the old behavior try, eval(input()).

www.cass.city.ac.uk
THE input FUNCTION
Example: Program parses a name

Run
Note: if you are using Python 3.4, then use the function input(), instead of raw_input().

www.cass.city.ac.uk
More String Functions
Example: Program shows use of int, float, and eval functions

Note: The eval() function lets a python program run python code within itself

Run

www.cass.city.ac.uk
STRING FUNCTIONS WITH NUMBERS

int and float also work with numbers

The str function converts a number to its string representation

www.cass.city.ac.uk
INTERNAL DOCUMENTATION
Benefits of documentation:

Other people easily understand program.

You can better understand program when you read it later.

Long programs are easier to read

Purposes of individual pieces can be determined at a glance.

www.cass.city.ac.uk
INTERNAL DOCUMENTATION
Example: Program shows use of documentation.

Note: if you are using Python 3.4, then use the function input(), instead of raw_input().

www.cass.city.ac.uk
LINE CONTINUATION
A long statement can be split across two or more lines

End each line with backslash character ( \ )

Alternatively any code enclosed in a pair of parentheses can span multiple lines.

This is preferred style for most Python programmers

www.cass.city.ac.uk
INDEXING AND SLICING OUT OF BOUNDS
Python does not allow out of bounds indexing for individual characters of strings

Does allow out of bounds indices for slices

Given: str1 = “Python”

Then print(str1[7]) print(str1[-7])

These are OK

www.cass.city.ac.uk
OUTPUT IN PYTHON

www.cass.city.ac.uk
OPTIONAL print ARGUMENT sep
Consider statement: print(value0, value1, …, valueN)

Print function uses string consisting of one space character as separator

Optionally change the separator to any string we like with the sep argument

Note: If you are using Python 2.7, unlike in Python 3.5, the sep argument is not supported because print is not a function and is treated as a keyword i.e. use

www.cass.city.ac.uk
OPTIONAL print ARGUMENT end
Print statement ends by executing a newline operation.

Optionally change the ending operation with the end argument

www.cass.city.ac.uk
ESCAPE SEQUENCES
Short sequences placed in strings

Instruct cursor or permit some special characters to be printed.

First character is always a backslash (\).

\t induces a horizontal tab

\n induces a newline operation

Example: Program demonstrates the use of the escape sequences \t and \n.

www.cass.city.ac.uk
ESCAPE SEQUENCES
Backslash also used to treat quotation marks as ordinary characters.

\” causes print function to display double quotation mark

\\ causes print function to display single backslash

www.cass.city.ac.uk
JUSTIFYING OUPUT IN A FIELD

Example: Program demonstrates methods ljust(n), rjust(n), and center(n)

www.cass.city.ac.uk
JUSTIFY OUTPUT WITH format
Given: str1 is a string and w is a field width

Given: num is a number and w is a field width

www.cass.city.ac.uk
JUSTIFY OUTPUT WITH format
Example: Program illustrates formatting

www.cass.city.ac.uk
JUSTIFY OUTPUT WITH format
Table 1.0 Demonstrate number formatting.

www.cass.city.ac.uk
Justify Output with format

Example: Program formatting with curly brackets

www.cass.city.ac.uk
READING THIS WEEK
Lecturer notes, which map to

SCHNEIDER, I. D., (2015), An Introduction to Programming Using Python, Global Edition
Chapter 1 & 2

LAMBERT, A. K., (2012), Fundamentals of Python: First Programs, 1st Edition
Chapter 1 & 2

DEITEL M., H., DEITEL & ASSOCIATES, (2002), Python How to Program
Chapter 1

Additional Resources
 
History and evolution of computer languages:
www.scriptol.org/history.php
 
Algorithm:
http://www.wisegeek.com/what-is-an-algorithm.htm
 
Software:
http://www.wordiq.com/definition/Software
 
Python Tutorial:
http://docs.python.org/tut/

82

www.cass.city.ac.uk
HOMEWORK THIS WEEK

See separate file on Moodle.
83

www.cass.city.ac.uk