Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

10/01/21

Constants
Variables, Expressions, and • Fixed values such as numbers, letters, and strings, are called
Statements “constants” because their value does not change
• Numeric constants are as you expect
Chapter 2 >>> print(123)
• String constants use single quotes (') 123
or double quotes (") >>> print(98.6)
98.6
Python for Everybody >>> print('Hello world')
www.py4e.com Hello world

1 2

Reserved Words Variables


• A variable is a named place in the memory where a programmer can store
You cannot use reserved words as variable names / identifiers data and later retrieve the data using the variable “name”

• Programmers get to choose the names of the variables


False class return is finally
None if for lambda continue • You can change the contents of a variable in a later statement
True def from while nonlocal
and del global not with
as elif try or yield
x = 12.2 x 12.2
assert else import pass y = 14
break except in raise
y 14

3 4

1
10/01/21

Variables Python Variable Name Rules


• A variable is a named place in the memory where a programmer can store • Must start with a letter or underscore _
data and later retrieve the data using the variable “name”
• Must consist of letters, numbers, and underscores
• Programmers get to choose the names of the variables

• You can change the contents of a variable in a later statement


• Case Sensitive

x = 12.2 x 12.2 100 Good: spam eggs spam23 _speed


y = 14 Bad: 23spam #sign var.12
Different: spam Spam SPAM
x = 100 y 14

5 6

Mnemonic Variable Names


x1q3z9ocd = 35.0
x1q3z9afd = 12.50
• Since we programmers are given a choice in how we choose our x1q3p9afd = x1q3z9ocd * x1q3z9afd
variable names, there is a bit of “best practice” print(x1q3p9afd)

• We name variables to help us remember what we intend to store


in them (“mnemonic” = “memory aid”)
• This can confuse beginning students because well-named
variables often “sound” so good that they must be keywords What is this bit of
code doing?
http://en.wikipedia.org/wiki/Mnemonic

7 8

2
10/01/21

x1q3z9ocd = 35.0 a = 35.0 x1q3z9ocd = 35.0 a = 35.0


x1q3z9afd = 12.50 b = 12.50 x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c) print(x1q3p9afd) print(c)

hours = 35.0
What are these bits What are these bits rate = 12.50
of code doing? of code doing? pay = hours * rate
print(pay)

9 10

Sentences or Lines Assignment Statements


• We assign a value to a variable using the assignment statement (=)

x = 2 Assignment statement • An assignment statement consists of an expression on the


right-hand side and a variable to store the result
x = x + 2 Assignment with expression
print(x) Print statement
x = 3.9 * x * ( 1 - x )
Variable Operator Constant Function

11 12

3
10/01/21

A variable is a memory location used to


A variable is a memory location x 0.6 store a value. The value stored in a x 0.6 0.936
used to store a value (0.6) variable can be updated by replacing the
old value (0.6) with a new value (0.936).
0.6 0.6 0.6 0.6
x = 3.9 * x * ( 1 - x ) x = 3.9 * x * ( 1 - x )

0.4 0.4
The right side is an expression. Once the
The right side is an expression. expression is evaluated, the result is
0.936 placed in (assigned to) the variable on the
0.936
Once the expression is evaluated, the
result is placed in (assigned to) x. left side (i.e., x).

13 14

Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
Expressions… use “computer-speak” to express the - Subtraction
classic math operations
* Multiplication
• Asterisk is multiplication / Division

• Exponentiation (raise to a power) looks ** Power


different than in math % Remainder

15 16

4
10/01/21

Numeric Expressions Order of Evaluation


>>> xx = 2 >>> jj = 23 • When we string operators together - Python must know which one
>>> xx = xx + 2 >>> kk = jj % 5 Operator Operation
>>> print(kk)
to do first
>>> print(xx)
+ Addition
4 3
>>> yy = 440 * 12 >>> print(4 ** 3) - Subtraction • This is called “operator precedence”
>>> print(yy) 64 * Multiplication
5280 • Which operator “takes precedence” over the others?
>>> zz = yy / 1000 4R3 / Division
>>> print(zz) 5 23 ** Power
5.28 20 % Remainder
x = 1 + 2 * 3 - 4 / 5 ** 6
3

17 18

Operator Precedence Rules >>> x = 1 + 2 ** 3 / 4 * 5


1 + 2 ** 3 / 4 * 5

>>> print(x)
Highest precedence rule to lowest precedence rule: 1 + 8 / 4 * 5
11.0
• Parentheses are always respected Parenthesis >>>
Power 1 + 2 * 5
• Exponentiation (raise to a power) Multiplication Parenthesis
Addition Power
• Multiplication, Division, and Remainder
Left to Right Multiplication 1 + 10
• Addition and Subtraction Addition
Left to Right
• Left to right 11

19 20

5
10/01/21

Operator Precedence Parenthesis


What Does “Type” Mean?
Power
• Remember the rules top to bottom Multiplication
Addition • In Python variables, literals, and
• When writing code - use parentheses Left to Right constants have a “type” >>> ddd = 1 + 4
>>> print(ddd)
• When writing code - keep mathematical expressions simple enough • Python knows the difference between 5
that they are easy to understand an integer number and a string >>> eee = 'hello ' + 'there'
>>> print(eee)
hello there
• Break long series of mathematical operations up to make them • For example “+” means “addition” if
more clear something is a number and
“concatenate” if something is a string
concatenate = put together

21 22

Type Matters Several Types of Numbers


• Python knows what “type” >>> eee = 'hello ' + 'there' >>> xx = 1
>>> eee = eee + 1 • Numbers have two main types >>> type (xx)
everything is
Traceback (most recent call last):
<class 'int'>
File "<stdin>", line 1, in - Integers are whole numbers:
• Some operations are <module>TypeError: Can't convert >>> temp = 98.6
-14, -2, 0, 1, 100, 401233 >>> type(temp)
prohibited 'int' object to str implicitly
>>> type(eee) <class'float'>
<class'str'> - Floating Point Numbers have
• You cannot “add 1” to a string >>> type(1)
>>> type('hello') decimal parts: -2.5 , 0.0, 98.6, 14.0 <class 'int'>
<class'str'>
• We can ask Python what type >>> type(1.0)
>>> type(1) • There are other number types - they
something is by using the <class'int'> <class'float'>
are variations on float and integer
type() function >>> >>>

23 24

6
10/01/21

Type Conversions Integer Division


>>> print(float(99) + 100)

• When you put an integer and


199.0 >>> print(10 / 2)
>>> i = 42 5.0
floating point in an >>> type(i) >>> print(9 / 2)
Integer division produces a floating 4.5
expression, the integer is <class'int'>
>>> f = float(i) point result >>> print(99 / 100)
implicitly converted to a float
>>> print(f) 0.99
• You can control this with the 42.0
>>> type(f)
>>> print(10.0 / 2.0)
5.0
built-in functions int() and >>> print(99.0 / 100.0)
<class'float'>
float() 0.99
>>>
This was different in Python 2.x

25 26

String
>>> sval = '123'
>>> type(sval)
<class 'str'>
User Input
Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object • We can instruct Python to
nam = input('Who are you? ')
• You can also use int() and to str implicitly
>>> ival = int(sval)
pause and read data from
the user using the input()
print('Welcome', nam)
float() to convert between >>> type(ival)

strings and integers


<class 'int'> function
>>> print(ival + 1)

• You will get an error if the string


124
>>> nsv = 'hello bob'
• The input() function
>>> niv = int(nsv) returns a string Who are you? Chuck
does not contain numeric Traceback (most recent call last):
characters File "<stdin>", line 1, in <module>
Welcome Chuck
ValueError: invalid literal for int()
with base 10: 'x'

27 28

7
10/01/21

Converting User Input Comments in Python


• If we want to read a number • Anything after a # is ignored by Python
from the user, we must inp = input('Europe floor?') • Why comment?
convert it from a string to a usf = int(inp) + 1
number using a type print('US floor', usf)
- Describe what is going to happen in a sequence of code
conversion function
• Later we will deal with bad
Europe floor? 0
- Document who wrote the code or other ancillary information
input data - Turn off a line of code - perhaps temporarily
US floor 1

29 30

# Get the name of the file and open it


name = input('Enter file:')
handle = open(name, 'r') Summary
# Count word frequency
counts = dict()
for line in handle: • Type • Integer Division
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1 • Reserved words • Conversion between types
# Find the most common word
bigcount = None
• Variables (mnemonic) • User input
bigword = None
for word,count in counts.items(): • Operators • Comments (#)
if bigcount is None or count > bigcount:
bigword = word
bigcount = count • Operator precedence
# All done
print(bigword, bigcount)

31 32

8
10/01/21

Exercise Acknowledgements / Contributions

These slides are Copyright 2010- Charles R. Severance


(www.dr-chuck.com) of the University of Michigan School of ...
Write a program to prompt the user for hours Information and made available under a Creative Commons
Attribution 4.0 License. Please maintain this last slide in all
and rate per hour to compute gross pay. copies of the document to comply with the attribution
requirements of the license. If you make a change, feel free to
add your name and organization to the list of contributors on this
page as you republish the materials.
Enter Hours: 35 Initial Development: Charles Severance, University of Michigan
Enter Rate: 2.75 School of Information

… Insert new Contributors and Translators here

Pay: 96.25

33 34

You might also like