EMT1111-Lecture 3
Download
Report
Transcript EMT1111-Lecture 3
Introduction to Python
Dr. José M. Reyes Álamo
Three Rules of Programming
• Rule 1: Think before you program
• Rule 2: A program is a human-readable essay on
problem solving that also happens to execute on a
computer
• Rule 3: The best way to improve your
programming and problem solving skills is to
practice.
2
Computer Programs
• A program is a sequence of instructions.
• To run a program is to:
– create the sequence of instructions according to your
design and the language rules
– turn that program into the binary code that the
processor understands
– give the binary code to the OS, so it can pass it to the
processor
– OS tells the processor how to run the program
– when finished, OS cleans up.
3
Code Listing (circle.py, available in the
course website)
import math
radiusString = raw_input("Enter the radius of your circle:")
radiusFloat = float(radiusString)
circumference = 2 * math.pi * radiusFloat
area = math.pi * radiusFloat * radiusFloat
print
print "The cirumference of your circle is:",circumference,\
", and the area is:",area
The Practice of Computing Using Python, Punch, Enbody, ©2011 Pearson
Aaddison-Wesley. All rights reserved
4
Interpreted
• Python is an interpreted language
• Interpreted means that Python looks at each
instruction, one at a time, and translate it into
machine language.
• That means that you can simply open the Python
interpreter and enter instructions one-at-a-time.
• You can also create a file with several instructions
called a script, and later on import it and executing
all the instruction as if you had typed them in.
• To rerun an script, reload it.
5
Interactive mode vs scripting
mode
Two ways to work: Interactive and scripting
• One of the benefits of working with an interpreted
language is that you can test bits of code in
interactive mode before you put them in a script.
• But there are differences between interactive
mode and script mode that can be confusing.
7
Interactive mode
• For example, if you are using Python as a
calculator, you might type
>>> miles = 26.2
>>> miles * 1.61
42.182
8
Scripting mode
• But if you type the same code into a script and run it, you
get no output at all.
• In script mode an expression, all by itself, has no visible
effect.
• Python actually evaluates the expression, but it doesn’t
display the value unless you tell it to do so:
miles = 26.2
print miles * 1.61
9
Calculating area and
circunference
Remember the program circle’s area
# 1. prompt user for the radius,
# 2. apply the area formula
# 3. print the results
11
Code Listing (circle.py)
import math
radiusString = raw_input("Enter the radius of your circle:")
radiusFloat = float(radiusString)
circumference = 2 * math.pi * radiusFloat
area = math.pi * radiusFloat * radiusFloat
print
print "The cirumference of your circle is:",circumference,\
", and the area is:",area
The Practice of Computing Using Python, Punch, Enbody, ©2011 Pearson
Aaddison-Wesley. All rights reserved
12
Import of Math
• One thing we did was to import the math module
with import math
• This imported python math statements (try it in
the python window)
• We precede all operations of math with
math.OPERATION
– e.g. math.pi, math.pow(x, y)
13
Code Listing (circle.py)
import math
radiusString = raw_input("Enter the radius of your circle:")
radiusFloat = float(radiusString)
circumference = 2 * math.pi * radiusFloat
area = math.pi * radiusFloat * radiusFloat
print
print "The cirumference of your circle is:",circumference,\
", and the area is:",area
The Practice of Computing Using Python, Punch, Enbody, ©2011 Pearson
Aaddison-Wesley. All rights reserved
14
Getting Input
The function:
raw_input(“Give me a value”)
•
prints “Give me a value” on the python screen
and waits until the user types anything and
presses Enter
•
After pressing enter, the result is a string even
for numbers
15
Assignment Statements
• The ‘=‘ is the assignment statement
• The value to the right is associated with the
variable name on the left
• It does not stand for equality!
16
Convert from string to integer
• To do math, Python requires converting the
sequence of characters into an integer
17
Printing Output
myVar = 12
print ‘My var has a value of:’,myVar
•print takes a list of elements to print, separated by
commas
– if the element is a string, prints it as is
– if the element is a variable, prints the value associated with
the variable
– after printing, moves on to a new line of output
18
Save as a script
• When you save a file, such as our first program,
and place a .py suffix on it, it becomes a python
module or script
• You “run” the module from the IDLE menu to see
the results of the operation
• A module is just a file with a bunch of python
commands
19
Errors!!!
• If Python interpreter does not understand your
code you will get an error (or errors)
• Check the syntax and correct it
• You can them import the program again until there
are no more errors
20
Common Error
• When using IDLE, if you save a file without
a .py extension, it will not colorize and
format the file.
• Resave with the .py extension
21
Modules (Scripts)
• We’ve seen modules already, they are essentially files with
Python statements.
• There are modules provided by Python to perform
common tasks (math, database, web interaction, etc.)
22
Formal Elements of Programming
• These apply to any computer programming
language
23
Statements
• Statements are commands.
• They perform some action, often called a side effect, but
they do not have a value
n = n + n ** 3
n = 3
print ‘Hello!’
24
Expressions
• Expressions perform some operation and have a value
• Expressions typically do not modify values in the
interpreter
3
n + 3
n ** 3
25
Code as Essay, an Aside
• What is the primary goal of writing code:
– to get it to do something
– an essay on my problem solving thoughts
• Code is something to be read. You provide
comments to help readability.
n + 3
n = n ** 3
#this an expression
#this is an statement
print ‘Hello!’ #this is another statement
26
Literals
• Literal is a programming notation for a fixed
value.
• Integer numbers are literals because they
have fixed values
–e.g. 123, 999, 1000.
27
Operators
• Integer
– addition and subtraction: +,
-
– multiplication: *
– Division (quotient): /
– remainder: %
• Floating point
– add, subtract, multiply, divide: +,
-, *, /
28
Variables
Variables
• A variable is a name we use to designate data in
our program
• We use names to make our program more
readable
30
Variables
• Python maintains a list of pairs for every variable:
– variable’s name
– variable’s value
• A variable is created when a value is assigned the first
time. It associates a name and a value
• Subsequent assignments update the associated value.
• We say the variable name references the value
• A variable type depends on the value assigned to it.
X=7
Name
Value
X
7
31
32
Python Naming Conventions
• must begin with a letter or _
– Ab123 is OK, but 123ABC is not.
• may contain letters, digits, and underscores
– this_is_an_identifier_123
• may be of any length
• upper and lower case letters are different
– LengthOfRope is not the same as lengthofrope
• names starting with _ have special meaning. Be careful!!!
33
When = Doesn’t Mean Equal
• It is most confusing at first to see the following
kind of expression:
–myInt = myInt + 7
• What’s looks strange here is that the = doesn’t
mean equal, but assignment
34
= sign means assignment
• In many computer languages, = means
assignment.
– myInt = myInt + 7
– lhs = rhs
• What assignment means is:
– evaluate the expression on the right-hand-size of the =
sign
– take the resulting value and associate it with the
variable name on the left-hand-size
35
More on Assignment
• Example: x = 3 * 5 + 2
–evaluate expression (3*5 + 2) = 17
–change the value of x to 17
• Example (if y has value 2): y = y + 3
–evaluate the expression (y+3): 5
–change the value of y to 5
36
37
Variables and Types
• Python does not require you to pre-define the
data type of a variable
• The data type of a variable can change
• Nonetheless, knowing the data type can be
important for using the correct operation on a
variable. Thus proper naming is important!
38
What Can Go on the lhs
• There are rules as to what can go on the lefthand-size of an assignment statement.
• You must indicate the name of a variable to be
associated with the resulting of the expression
• must follow the naming convention
– myInt = 5, Yes
– myInt + 5 = 7, No
39
Types (data types)
Python Data Types
• integer: 5
• float: 1.2
• boolean: True, False
• string: “anything” or ‘something’
• list: [,]: [‘a’,1,1.3]
• others
41
What is a Type?
• A Python data type essentially defines two things:
– the internal structure of the type (what it contains)
– the operations you can perform on it
• ‘abc’.capitalize() is an operation you can call on
strings, but not integers
42
Fundamental Types
• Integers
– 1, -27 ( to +/- 232 – 1)
• Floating Point
– 3.14, 10.0, .001, 3.14e-10, 0e0
• Boolean (True or False values)
– True, False (notice the use of caps)
43
Converting Types
• A character ‘1’ is not the same as the
integer 1
• You need to convert the value returned by
the raw_input command (characters) into
an integer
•int(“123”) yields the integer 123
44
Type Conversion
• int(someVar) converts to an integer
• float(someVar) converts to a float
• str(someVar) converts to a string
• should check out what works:
– int(2.1) 2, int(‘2’) 2, but int(‘2.1’) fails
– float(2) 2.0, float(‘2.0’) 2.0, float(‘2’) 2.0,
float(2.0) 2.0
– str(2) ‘2’, str(2.0) ‘2.0’, str(‘a’) ‘a’
45
Types and Division
Python does binary operations on two values
of the same type, yielding a value of that
type:
• 2/3, integer types, yield integer (0).
– 2%3 is the remainder, an integer (2)
• 2.0/3.0, float types, yield float (0.66666)
46
Mixed Types
• You know that 4/3 is 1 (integer division)
• You know that 4.0/3.0 is 1.3333333 (float)
• What is 4/3.0?
–no mixed type operations. Must convert
–Python will automatically convert to the most
detailed result. Thus 4 4.0, the result is
1.3333333
47
LAB2_Python1