Operations and Variables

Operations on Strings and Numeric Types

int operations

As you'd expect: addition, subtraction and multiplication →

Division is Special

>>> 5/2
2.5
>>> type(5/2)
<class 'float'>
>>> 
>>> 12/4
3.0
>>> type(12/4)
<class 'float'>
>>> 

We Don't Need No Decimal Points

>>> 5//2
2
>>> -5//2
-3

Modulo Operator (Remainder)

>>> 5%2
1

Exponentiation

>>> 2**2
4

Order of Operations

>>> 12 + 10 / 5
14.0

BTW, what type did we get back?

float! (division, even with integers, gives back floats)

(Parentheses)

>>> (6 + 4) * 5
50

You Could Always Use It As a Calculator

Translate this formula into Python code

(9 / 5) * 37 + 32

str Operations

Multiplication!?

>>> "hey" * 3
'heyheyhey'

String Concatenation

Let's repeat: string concatenation requires both operands to be strings

Let's Fix It!

You can change from one type to another using functions of the same name as the type you are trying to convert to. Let's look at what autocomplete says about the following functions and demo them. →

And This Helps… How?

Let's fix our previous string concatenation

3 + " blind mice"

(of course, this is contrived, since we know that 3 is an int, and we could have just wrapped it in quotes: '3'… but imagine if we didn't know the type beforehand!)

>>> str(3) + " blind mice"
'3 blind mice'

Review

A Quick Summary of Operators for Numeric Types

Name as many operators that work on numeric types as you can:

A Quick Summary of String Operators

Name as many operators that work on strings as you can:

Variables

What's a Variable?

So How Do Variables Actually Work?

some_variable_name = "a value"

Another Aside - Interactive Shell

Whenever you type something in the interactive shell, it will always return a value. →

Some More Miscellaneous Comments

Variables That Aren't Defined Yet

>>> foo
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    foo
NameError: name 'foo' is not defined
>>> 

More About Reassignment

>>> a = 23
>>> a
23
>>> a = "foo"

Naming Variables

Am I a Valid Name?

Which of the following are valid variable names in Python?

  1. _foo
  2. 1_foo
  3. foo
  4. 1foo
  5. $foo

1 and 3 are valid variable names.

Let's Actually Use Some Variables

Try the following on your own:

User Input