You are on page 1of 32

Variables, expressions,

statements

Chapter 2
Constants

• Fixed values such as numbers, letters, and strings, are called


“constants” because their value does not change
• Numeric constants are as you expect
>>> print(123)
• String constants use single quotes (') 123
or double quotes (") >>> print(98.6)
98.6
>>> print('Hello world')
Hello world
Reserved Words
You cannot use reserved words as variable names / identifiers

False class return is finally


None if for lambda continue
True def from while nonlocal
and del global not with
as elif try or yield
assert else import pass
break except in raise
Variables
• A variable is 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

x = 12.2 x 12.2
y = 14
y 14
Variables
• A variable is 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

x = 12.2 x 12.2 100


y = 14
x = 100 y 14
Python Variable Name Rules
• Must start with a letter or underscore _
• Must consist of letters, numbers, and underscores
• Case Sensitive

Good: spam eggs spam23 _speed


Bad: 23spam #sign var.12
Different: spam Spam SPAM
Mnemonic Variable Names
• Since programmers are given a choice in how to choose 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”)
x1q3z9ocd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd
print(x1q3p9afd)

What is this bit of


code doing?
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

What are these bits


of code doing?
x1q3z9ocd = 35.0 a = 35.0
x1q3z9afd = 12.50 b = 12.50
x1q3p9afd = x1q3z9ocd * x1q3z9afd c = a * b
print(x1q3p9afd) print(c)

hours = 35.0
What are these bits rate = 12.50
of code doing? pay = hours * rate
print(pay)
Assignment Statements
• 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

x = 3.9 * x * ( 1 - x )
A variable is a memory location x 0.6
used to store a value (0.6)

0.6 0.6
x = 3.9 * x * ( 1 - x )

0.4

The right side is an expression.


0.936
Once the expression is evaluated, the
result is placed in (assigned to) x.
Numeric Expressions
Operator Operation
• Because of the lack of mathematical
symbols on computer keyboards - we + Addition
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
Numeric Expressions
>>> x = 2 >>> j = 23
>>> x = x + 2 >>> k = j % 5 Operator Operation
>>> print(x) >>> print(k)
+ Addition
4 3
>>> y = 440 * 12 >>> print(4 ** 3) - Subtraction
>>> print(y) 64 * Multiplication
5280
>>> z = y / 1000 4R3 / Division

>>> print(z) 5 23 ** Power


5.28 20 % Remainder

3
Order of Evaluation
• When we write operators without parentheses - 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
Operator Precedence Rules
Highest precedence rule to lowest precedence rule:

• Parentheses are always respected


Parenthesis
Power
• Exponentiation (raise to a power) Multiplication
Addition
• Multiplication, Division, and Remainder Left to Right
• Addition and Subtraction

• Left to right
1 + 2 ** 3 / 4 * 5
>>> x = 1 + 2 ** 3 / 4 * 5
>>> print(x)
11.0 1 + 8 / 4 * 5
>>>
1 + 2 * 5
Parenthesis
Power
Multiplication 1 + 10
Addition
Left to Right
11
Operator Precedence Parenthesis
Power
• Remember the rules top to bottom Multiplication
Addition
• When writing code - use parentheses Left to Right

• 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
What Does “Type” Mean?
• In Python variables, literals, and
>>> d = 1
constants have a “type” >>> dd = 4
>>> print(d + dd)
• Python knows the difference between 5
an integer number and a string >>> ee = 'hello '
>>> e = 'there'
>>> print(ee + e)
• For example “+” means “addition” if hello there
something is a number and
“concatenate” if something is a string
concatenate = put together
Type Matters
• Python knows what “type” >>> eee = 'hello ' + 'there'
everything is >>> eee = eee + 1
Traceback (most recent call last):
File "<stdin>", line 1, in
• Some operations are <module>TypeError: Can't convert
prohibited 'int' object to str implicitly
>>> type(eee)
• You cannot “add 1” to a string <class'str'>
>>> type('hello')
<class'str'>
• We can ask Python what type >>> type(1)
something is by using the <class'int'>
type() function >>>
Several Types of Numbers
>>> x = 1
• Numbers have two main types
>>> type (x)
<class 'int'>
- Integers are whole numbers:
>>> temp = 98.6
-14, -2, 0, 1, 100, 401233
>>> type(temp)
<class'float'>
- Floating Point Numbers have
>>> type(1)
decimal parts: -2.5 , 0.0, 98.6, 14.0
<class 'int'>
• There are other number types - they >>> type(1.0)
<class'float'>
are variations on float and integer
>>>
Type Conversions
>>> print(float(99) + 100)
199.0
• When you put an integer and >>> i = 42
floating point in an >>> type(i)
expression, the integer is <class'int'>
implicitly converted to a float >>> f = float(i)
>>> print(f)
• You can control this with the 42.0
>>> type(f)
built-in functions int() and
<class'float'>
float()
>>>
Integer Division
>>> print(10 / 2)
5.0
>>> print(9 / 2)
Integer division produces a floating 4.5
point result >>> print(99 / 100)
0.99
>>> print(10.0 / 2.0)
5.0
>>> print(99.0 / 100.0)
0.99
This was different in Python 2.x
String
>>> sval = '123'
>>> type(sval)
<class 'str'>

Conversions
>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object


to str implicitly
You can also use int() and >>> ival = int(sval)
float() to convert between >>> type(ival)
<class 'int'>
strings and integers >>> print(ival + 1)
124
• You will get an error if the string >>> nsv = 'hello bob'
>>> niv = int(nsv)
does not contain numeric Traceback (most recent call last):
characters File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
with base 10: 'x'
User Input
• We can instruct Python to
name = input('Who are you?\n')
pause and read data from
print('Welcome', name)
the user using the input()
function

• The input() function


returns a string Who are you? Chuck
Welcome Chuck
Converting User Input

• If we want to read a number


from the user, we must inp = input('Europe floor?\n')
usf = int(inp) + 1
convert it from a string to a print('US floor', usf)
number using a type
conversion function
Europe floor? 0
US floor 1
Converting User Input
>>> inp = input('Europe floor?\n')
What?
>>> int(inp)


ValueError Traceback (most recent
If the user enters something call last)
different than a string of <ipython-input-4-155078aed62b> in
<module>()
digits, you get an error ----> 1 int(inp)
ValueError: invalid literal for
int() with base 10: 'What?'
Comments in Python

• Anything after a # is ignored by Python

• Why comment?

- Describe what is going to happen in a sequence of code

- Turn off a line of code - perhaps temporarily


Summary
• Type • Integer Division

• Reserved words • Conversion between types

• Variables (mnemonic) • User input

• Operators • Comments (#)

• Operator precedence
Exercises

Write a program to prompt the user for hours


and rate per hour to compute gross pay.

Enter Hours: 6.5


Enter Rate: 9.5

Pay: 61.75
Exercises

Let width= 17 and height = 12.0


What is the output and type of each of the
following statement?

width//2
width/2.0
height/3
Exercises

Write a program which prompts the user for a Celsius


temperature, convert the temperature to Fahrenheit,
and print out the converted temperature.

Enter the temperature in Celsius


29.5

The temperature is 85.1 degrees Fahrenheit

You might also like