Variables, Expressions, and Statements Chapter 2 Flashcards

1
Q

Variables

A

a named place in the memory where a programmer can
store data and later retrieve the data using the variable “name”
• Programmers get to choose the names of the variables
• You can change the contents of a variable in a later statement.

A variable is a memory location
used to store a value (0.6)
The right side is an expression.
Once the expression is evaluated,
the result is placed in (assigned to)the variable on the
left side (i.e., x).
x = 12.2
y = 14
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Python Variable Name Rules

A
  1. Must start with a letter or underscore _
  2. Must consist of letters and numbers and underscores
  3. Case Sensitive
    • Good: spam eggs spam23 _speed
    • Bad: 23spam #sign var.12
    • Different: spam Spam SPAM
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Reserved Words

A

You cannot use reserved words as variable names / identifiers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Reserved Words

A
and del for is raise assert elif
from lambda return break else
global not try class except if or
while continue exec import pass
yield def finally in print as with
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Sentences or Lines

A

x = 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Assignment Statements

A

• We assign a value to a variable using the assignment statement (=)
• An assignment statement consists of an expression on the
right-hand side and a variable to store the result

Example of an Assignment Statements :
x = 3.9 * x * ( 1 - x )

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Numeric Expressions

A
• Because of the lack of mathematical
symbols on computer keyboards - we
use “computer-speak” to express the
classic math operations
• Asterisk is multiplication
• Exponentiation (raise to a power) looks
different from in math.
\+  Addition
-  Subtraction
*  Multiplication
/  Division
**  Power
%  Remainder
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Numeric Expressions

A

> > > xx = 2
xx = xx + 2
print xx
4

> > > yy = 440 * 12
print yy
5280

> > > zz = yy / 1000
print zz
5

>>> jj = 23
>>> kk = jj % 5
>>> print kk
3
>>> print 4 ** 3
64
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Order of Evaluation

A

• When we string operators together - Python must know which one
to do first
• This is called “operator precedence”
• Which operator “takes precedence” over the others?
x = 1 + 2 * 3 - 4 / 5 ** 6

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Operator Precedence Rules

A

Highest precedence rule to lowest precedence rule:
> Parenthesis are always respected
> Exponentiation (raise to a power)
> Multiplication, Division, and Remainder
> Addition and Subtraction
> Left to Right

 Parenthesis      
 Power
Multiplication
Addition
Left to Right  

> > > x = 1 + 2 ** 3 / 4 * 5
print x
11

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Operator Precedence

A
• Remember the rules top to bottom
• When writing code - use parenthesis
• When writing code - keep mathematical expressions simple enough
that they are easy to understand
• Break long series of mathematical operations up to make them
more clear
Parenthesis
Power
Multiplication
Addition
Left to Right
Exam Question: x = 1 + 2 * 3 - 4 / 5
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Python Integer Division is Weird!

This changes in Python 3.0

A
>>> print 10 / 2
5
>>> print 9 / 2
4
>>> print 99 / 100
0
>>> print 10.0 / 2.0
5.0
>>> print 99.0 / 100.0
0.99
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Mixing Integer and Floating

A
• When you perform an
operation where one
operand is an integer and
the other operand is a
floating point, the result is a
floating point
• The integer is converted to a
floating point before the
operation
>>> print 99 / 100
0
>>> print 99 / 100.0
0.99
>>> print 99.0 / 100
0.99
>>> print 1 + 2 * 3 / 4.0 - 5
-2.5
>>>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does “Type” Mean?

A
• In Python variables, literals and
constants have a “type”
• Python knows the difference
between an integer number and
a string
• For example “+” means
“addition” if something is a
number and “concatenate” if
something is a string
>>> ddd = 1 + 4
>>> print ddd
5
>>> eee = 'hello ' + 'there'
>>> print eee
hello there

concatenate = put together

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Type Matters

A
• Python knows what “type”
everything is
• Some operations are prohibited
• You cannot “add 1” to a string
• We can ask Python what type
something is by using the type()
function

> > > eee = ‘hello ‘ + ‘there’
eee = eee + 1
Traceback (most recent call last):
File “”, line 1, in

TypeError: cannot concatenate
‘str’ and ‘int’ objects
»> type(eee)

> > > type(‘hello’)

> > > type(1)

> > >

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Several Types of Numbers

A
Numbers have two main types
> Integers are whole numbers:
-14, -2, 0, 1, 100, 401233
> Floating Point Numbers have decimal
parts: -2.5 , 0.0, 98.6, 14.0
• There are other number types - they
are variations on float and integer.
>>> xx = 1
>>> type (xx)

> > > temp = 98.6
type(temp)

> > > type(1)

> > > type(1.0)

> > >

17
Q

Type Conversions

A
• When you put an integer and
floating point in an expression,
the integer is implicitly
converted to a float
• You can control this with the
built-in functions int() and
float()
>>> print float(99) / 100
0.99
>>> i = 42
>>> type(i)

> > > f = float(i)
print f
42.0
type(f)

> > > print 1 + 2 * float(3) / 4 - 5
-2.5

18
Q

String

Conversions

A
• You can also use int() and
float() to convert between
strings and integers
• You will get an error if the
string does not contain
numeric characters

> > > sval = ‘123’
type(sval)

>>> print sval + 1
Traceback (most recent call last):
File "", line 1, in 
TypeError: cannot concatenate 'str'
and 'int'
>>> ival = int(sval)
>>> type(ival)
>>> print ival + 1
124
>>> nsv = 'hello bob'
>>> niv = int(nsv)
Traceback (most recent call last):
File "", line 1, in 
ValueError: invalid literal for int()
19
Q

User Input

A

• We can instruct Python
to pause and read data
from the user using the
raw_input() function

• The raw_input() function
returns a string

nam = raw_input(‘Who are you?’)
print ‘Welcome’, nam

Who are you? Chuck

Welcome Chuck

20
Q

Converting User Input

A
• If we want to read a
number from the user,
we must convert it from
a string to a number
using a type conversion
function
• Later we will deal with
bad input data

inp = raw_input(‘Europe floor?’)
usf = int(inp) + 1
print ‘US floor’, usf

Europe floor? 0
US floor 1

21
Q

Comments in Python

A

• Anything after a # is ignored by Python

• Why comment?
> Describe what is going to happen in a sequence of code
> Document who wrote the code or other ancillary information
> Turn off a line of code - perhaps temporarily

22
Q

Comments in Python

A
# Get the name of the file and open it
name = raw_input('Enter file:')
handle = open(name, 'r')
text = handle.read()
words = text.split()
# Count word frequency
counts = dict()
for word in words:
counts[word] = counts.get(word,0) + 1
# Find the most common word
bigcount = None
bigword = None
for word,count in counts.items():
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
# All done
print bigword, bigcount
23
Q

String Operations

A

• Some operators apply to strings
> + implies “concatenation”
> * implies “multiple concatenation”

• Python knows when it is dealing with
a string or a number and behaves
appropriately

>>> print 'abc' + '123’
abc123
>>> print 'Hi' * 5
HiHiHiHiHi
>>>
24
Q

Mnemonic Variable Names

A

• Since we programmers are given a choice in how we choose our
variable names, there is a bit of “best practice”

• 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

25
Q

What is this bit of

code doing?

A

x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print x1q3p9afd

What is this bit of
code doing?

26
Q

What are these

bits of code doing?

A

x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print x1q3p9afd

a = 35.0
b = 12.50
c = a * b
print c

hours = 35.0
rate = 12.50
pay = hours * rate
print pay

27
Q

Exercise

A

Exercise

Write a program to prompt the user for hours and
rate per hour to compute gross pay.
Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
28
Q

Summary

A
  • Type
  • Reserved words
  • Variables (mnemonic)
  • Operators
  • Operator precedence
  • Integer Division
  • Conversion between types
  • User input
  • Comments (#)