[go: up one dir, main page]

0% found this document useful (0 votes)
6 views65 pages

Chap 1

The document outlines the software development process, including stages such as problem analysis, design, implementation, testing, and maintenance, using a temperature converter example for illustration. It also covers elements of programs, including names, expressions, output statements, assignment statements, and Python's core data types like numbers, strings, lists, dictionaries, and tuples. Additionally, it discusses the importance of input statements and file handling in Python programming.

Uploaded by

Nguyen Thu Thao
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)
6 views65 pages

Chap 1

The document outlines the software development process, including stages such as problem analysis, design, implementation, testing, and maintenance, using a temperature converter example for illustration. It also covers elements of programs, including names, expressions, output statements, assignment statements, and Python's core data types like numbers, strings, lists, dictionaries, and tuples. Additionally, it discusses the importance of input statements and file handling in Python programming.

Uploaded by

Nguyen Thu Thao
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
You are on page 1/ 65

Chap 1.

Basic Information

TS. Trần Vũ Hoàng


Outlines
• Software Development Process
• Elements of Programs
• Basic Assignments
• Python Object Types
Software Development Process
• The process of creating a program is often broken down into stages
according to the information that is produced in each phase.
• Analyze the Problem
• Determine Specifications
• Create a Design
• Implement the Design
• Test/Debug the Program
• Maintain the Program
Software Development Process
• Analyze the Problem
• Figure out exactly the problem to be solved. Try to understand it as much
as possible.
• Temperature Converter Example: the temperature is given in Celsius, user
wants it expressed in degrees Fahrenheit.
• Determine Specifications
• Describe exactly what your program will do.
• Don’t worry about how the program will work, but what it will do.
• Includes describing the inputs, outputs, and how they relate to one another.
• Temperature Converter Example :
• Input – temperature in Celsius
• Output – temperature in Fahrenheit
• Output = 9/5(input) + 32
Software Development Process
• Create a Design
• Formulate the overall structure of the program.
• This is where the how of the program gets worked out.
• You choose or develop your own algorithm that meets the specifications.
• Temperature Converter Example:
• Input, Process, Output (IPO)
• Prompt the user for input (Celsius temperature)
• Process it to convert it to Fahrenheit using F = 9/5(C) + 32
• Output the result by displaying it on the screen
Software Development Process
• Implement the Design
• Translate the design into a computer language.
• In this course we will use Python.
• Temperature Converter Example:
• Before we start coding, let’s write a rough draft of the program in
pseudocode
• Pseudocode is precise English that describes what a program does, step
by step.
• Using pseudocode, we can concentrate on the algorithm rather than the
programming language.
Software Development Process
• Pseudocode:
• Input the temperature in degrees Celsius (call it celsius)
• Calculate Fahrenheit as (9/5)*celsius+32
• Output Fahrenheit
• Now we need to convert this to Python!
#convert.py
# A program to convert Celsius temps to Fahrenheit
# by: Susan Computewell
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = (9/5) * celsius + 32
print("The temperature is ",fahrenheit," degrees Fahrenheit.")
main()
Software Development Process
• Test/Debug the Program
• Try out your program to see if it worked.
• If there are any errors (bugs), they need to be located and fixed. This process is called
debugging.
• Your goal is to find errors, so try everything that might “break” your program!
• Temperature Converter Example:
• Once we write a program, we should test it!
>>>
What is the Celsius temperature? 0
The temperature is 32.0 degrees Fahrenheit.
>>> main()
What is the Celsius temperature? 100
The temperature is 212.0 degrees Fahrenheit.
>>> main()
What is the Celsius temperature? -40
The temperature is -40.0 degrees Fahrenheit.
>>>
Software Development Process
• Maintain the Program
• Continue developing the program in response to the needs of your users.
• In the real world, most programs are never completely finished – they
evolve over time.
• Example:
• convert more units of measurement
•…
Outlines
• Software Development Process
• Elements of Programs
• Basic Assignments
• Python Object Types
Elements of Programs
• Names
• Expressions
• Output Statements
Elements of Programs
• Names
• Names are given to variables (celsius, fahrenheit), modules (main,
convert), etc.
• These names are called identifiers
• Every identifier must begin with a letter or underscore (“_”), followed by
any sequence of letters, digits, or underscores.
• Identifiers are case sensitive.
• Spam
• spam
• Some identifiers are part of Python itself. This means they are not
available for you to use as a name for a variable
• and, del, for, is, raise, assert, elif, in, print, etc.
Elements of Programs
• Expressions
• The fragments of code that produce or calculate new data values are
called expressions.
• Literals are used to represent a specific value, e.g. 3.9, 1, 1.0
• Simple identifiers can also be expressions.
>>> x = 5
>>> x
5
>>> print(x)
5
>>> print(spam)

Traceback (most recent call last):


File "<pyshell#15>", line 1, in -toplevel-
print spam
NameError: name 'spam' is not defined
>>>
Elements of Programs
• Expressions
• Simpler expressions can be combined using operators.
• +, -, *, /, **
• Spaces are irrelevant within an expression.
• The normal mathematical precedence applies.
• ((x1 – x2) / 2*n) + (spam / k**3)
Elements of Programs
• Output Statements
• A print statement can print any number of expressions.
• Successive print statements will display on separate lines.
• A bare print will print a blank line.
print(3+4) 7
print(3, 4, 3+4) 347
print()
print(3, 4, end=" "),
347
print(3 + 4)
print("The answer is", 3+4) The answer is 7
Outlines
• Software Development Process
• Elements of Programs
• Basic Assignments
• Python Object Types
Assignment Statements
• Simple Assignment
• <variable> = <expr>
variable is an identifier, expr is an expression
• The expression on the RHS is evaluated to produce a value which is then
associated with the variable named on the LHS.
• Example:
• x = 3.9 * x * (1-x)
• fahrenheit = 9/5 * celsius + 32
• x=5
Assignment Statements
• Variables can be reassigned as many times as you want!
>>> myVar = 0
>>> myVar
0
>>> myVar = 7
>>> myVar
7
>>> myVar = myVar + 1
>>> myVar
8
>>>
Assignment Statements
• Variables are like a box we can put values in.
• When a variable changes, the old value is erased and a new one is written in.

• Python doesn't overwrite these memory locations (boxes).


• Assigning a variable is more like putting a “sticky note” on a value and
saying, “this is x”.
Assigning Input
• The purpose of an input statement is to get input from the user and store it
into a variable.
• <variable> = eval(input(<prompt>))
• First the prompt is printed
• The input part waits for the user to enter a value and press <enter>
• The expression that was entered is evaluated to turn it from a string of characters
into a Python value (a number).
• The value is assigned to the variable.
Simultaneous Assignment
• Several values can be calculated at the same time
• <var>, <var>, … = <expr>, <expr>, …
• Evaluate the expressions in the RHS and assign them to the variables on the LHS
• sum, diff = x+y, x-y
• How could you use this to swap the values for x and y?
• Why doesn’t this work?
x=y
y=x
• We could use a temporary variable…
Simultaneous Assignment
• We can swap the values of two variables quite easily in Python!
• x, y = y, x
>>> x = 3
>>> y = 4
>>> print x, y
34
>>> x, y = y, x
>>> print x, y
43
Simultaneous Assignment
• We can use this same idea to input multiple variables from a single input
statement!
• Use commas to separate the inputs
def spamneggs():
spam, eggs = eval(input("Enter # of slices of spam followed by # of eggs: "))
print ("You ordered", eggs, "eggs and", spam, "slices of spam. Yum!“)

>>> spamneggs()
Enter the number of slices of spam followed by the number of eggs: 3, 2
You ordered 2 eggs and 3 slices of spam. Yum!
>>>
Outlines
• Software Development Process
• Elements of Programs
• Basic Assignments
• Python’s Core Data Types
Python’s Core Data Types
Numbers
• Python’s core objects set includes the usual suspects
• Integers: numbers without a fractional part
• floating-point numbers: roughly, numbers with a decimal point in them
• complex numbers: with imaginary parts
• fixed-precision decimals
• rational fractions with numerator and denominator
• ...
• Numbers in Python support the normal mathematical operations
• plus sign (+) performs addition
• a star (*) is used for multiplication
• two stars (**) are used for exponentiation
• -, \ …
Numbers
• Besides expressions, there are a handful of useful numeric modules that ship
with Python
• Math module: contains advanced numeric tools as functions
• Random module: performs random number generation and random selections
•…
Strings
• strings are sequences of one-character strings
• we can verify string’s length with the built-in len function

• And fetch its components with indexing expressions

• In Python, indexes start from 0: the first item is at index 0, the second is at
index 1, and so on.
Strings
• we can also index backward, from the end
• positive indexes count from the left
• negative indexes count back from the right:

• extract an entire section (slice) in a single step


Strings
• Their general form, X[I:J], means “give me everything in X from offset I up
to but not including offset J.”
Strings
• strings also support:
• concatenation with the plus sign (joining two strings into a new string)
• repetition (making a new string by repeating another)
Strings
• strings are immutable in Python—they cannot be changed in-place after they
are created
• you can’t change a string by assigning to one of its positions
• but you can always build a new one and assign it to the same name
Strings
Type-Specific Methods
• strings also have operations all their own, available as methods—functions
attached to the object, which are triggered with a call expression
• the string find method: substring search operation, returns the offset of the passed-in
substring, or −1 if it is not present

• the string replace method performs global searches and replacements


Strings
Type-Specific Methods
• split a string into substrings on a delimiter

• upper: perform case conversions

• test the content of the string (digits, letters, and so on)

• strip whitespace characters off the ends of the string


Strings
Type-Specific Methods
• Strings also support an advanced substitution operation known as formatting,
available as both an expression (the original) and a string method call
String
Getting Help
• dir function: returns a list of all the attributes available for a given object
String
Getting Help
• help function: ask what the method do
String
Other Ways to Code Strings
• Python also provides a variety of ways for us to code strings
• special characters can be represented as backslash escape sequences:
String
Other Ways to Code Strings
• Python allows strings to be enclosed in single or double quote characters
• It also allows multiline string literals enclosed in triple quotes (single or
double)
• all the lines are concatenated together
• end-of-line characters are added where line breaks appear
String
Pattern Matching
• import a module called re: do pattern matching in Python
• search for a substring that begins with the word “Hello”, followed by zero or more
tabs or spaces, followed by arbitrary characters to be saved as a matched group,
terminated by the word “world”

• picks out three groups separated by slashes


Lists
• Lists are positionally ordered collections of arbitrarily typed objects
• They have no fixed size
• They are also mutable: can be modified

• we can index, slice, and so on, just as for strings:


Lists
Type-Specific Operations
• Lists have no fixed size: can grow and shrink on demand
• append method: expands the list’s size and inserts an item at the end
• pop method (or an equivalent del statement): removes an item at a given offset
• insert method: insert an item at an arbitrary position
• remove method: remove a given item by value
Lists
Type-Specific Operations
• sort method: orders the list in ascending fashion by default
• reverse method: reverses it—in both cases
Lists
Nesting
• we can have a list that contains a dictionary, which contains another list, and
so on)

• M represent a 3 × 3 matrix of numbers. Such a structure can be accessed in a


variety of ways:
Lists
Comprehensions
• It’s easy to grab rows by simple indexing because the matrix is stored by
rows, but it’s almost as easy to get a column with a list comprehension:

• List comprehensions can be more complex in practice:


Lists
Comprehensions
• they can be used to iterate over any iterable object:

• create generators that produce results on demand


Lists
Comprehensions
• The map built-in can do similar work:

• comprehension syntax can also be used to create sets and dictionaries:

• In fact, lists, sets, and dictionaries can all be built with comprehensions
Dictionaries
• Python dictionaries are not sequences at all, but are instead known as
mappings
• collections of other objects
• store objects by key instead of by relative position
• simply map keys to associated values
• Dictionaries are also mutable
• dictionaries
• are coded in curly braces
• consist of a series of “key: value” pairs
Dictionaries
Mapping Operations
• We can index this dictionary by key

• We can build up dictionaries


in different way:
Dictionaries
Nesting Revisited
• the values can become more complex: a nested dictionaries

• We can access the components of this structure much as we did for our
matrix
Dictionaries
Sorting Keys: for Loops
• dictionaries are not sequences, they don’t maintain any dependable left-to-
right order
• if we make a dictionary and print it back, its keys may come back in a
different order than that in which we typed them:
Dictionaries
Sorting Keys: for Loops
• What do we do, though, if we do need to impose an ordering on a
dictionary’s items?
Dictionaries
Sorting Keys: for Loops
• We also can use newer sorted built-in function
Dictionaries
Missing Keys: if Tests
• We can test if the key is in the dictionary:
Tuples
• roughly like a list that cannot be changed
• tuples are sequences, like lists,
• but they are immutable, like strings
Tuples
• Tuples also have two type-specific callable methods

• Like lists and dictionaries, tuples support mixed types and nesting, but they
don’t grow and shrink because they are immutable
Why Tuples?
• their immutability is the whole point
• If you pass a collection of objects around your program as a list, it can be
changed anywhere; if you use a tuple, it cannot
Files
• file objects are Python code’s main interface to external files on your
computer
• call the built-in open function: to create a file object
• pass in its name and the 'w' processing mode string to write data
Files
• To read back what you just wrote
• reopen the file in 'r' processing mode
• read the file’s content into a string, and display it
• A file’s contents are always a string in your script
Files
• if you want a quick preview file object methods, run a dir call on any open
file and a help on any of the method names
Other Core Types
• Sets: unordered
collections of
unique and
immutable objects
• created by
calling the built-
in set function
• or using set
literals and
expressions
• support the usual
mathematical set
operations
Other Core Types
• decimal numbers: fixed- precision floating-point numbers
• fraction numbers: rational numbers with both a numerator and a denominator
Other Core Types
• Booleans: True and False objects
• None: used to initialize names and objects
User-Defined Classes
• classes define new types of objects that extend the core set
• you wish to have a type of object that models employees

• Worker class has name and pay attributes and two functions: lastName and
giveRaise
User-Defined Classes
• Calling the class like a function generates instances of our new type

You might also like