Data Types and Variables#

Python as a calculator#

You can use Python to make calculations like addition, subtraction, multiplication, and division.

1 + 1
2
3 * 4
12
21 / 7
3.0
10 - 9
1

Data Types#

Python interprets all data as a type of data. For example, a number is interpreted as an “integer,” and any characters contained within quotes are interpreted as a “string.”

type(1)
int
type('hello world!')
str
type("1")
str
type(1)
int
type(1.)
float
type(True)
bool
type(False)
bool
type(['sausage', 'egg', 'cheese'])
list
type([1, 4, 2])
list

Variables#

Python saves data as “variables,” which are a kind of label that we can assign to values like integers, strings, or lists.

x = 5
x
5
y = 10
y
10
x + 5
10
x
5
x = "Hello"
x
'Hello'
y = " Goodbye"
y
' Goodbye'
x + y 
'Hello Goodbye'
breakfast = ['kiwis', 'yogurt', 'peanut butter sandwish', 'water']
breakfast
['kiwis', 'yogurt', 'peanut butter sandwish', 'water']
type(breakfast)
list
number = 1000
number
1000

Rules for creating variables#

# variables can start with an underscore or an alphabetic character.  
_5 = "five"
# variables are case sensitive
my_variable = "test"
My_variable = "test again"
My_variable
'test again'
my_variable
'test'
# generally variables cannot start with punctuation
$varialbe = "dollar"
  Cell In[34], line 2
    $varialbe = "dollar"
    ^
SyntaxError: invalid syntax

Objects#

Every time you save some data to a variable, you are creating an “object” in python.

# this creates a string type object
greeting = "Hello World!"
greeting
'Hello World!'

Methods for Objects#

Objects have built-in functionality based on their data type, like strings and lists. In other words, you can do certain things to string-type objects that you cannot with list-type objects.

# certain methods, like upper(), can be used to do things to strings
greeting.upper()
'HELLO WORLD!'
# lower() is another string method
greeting.lower()
'hello world!'
greeting
'Hello World!'
breakfast
['kiwis', 'yogurt', 'peanut butter sandwish', 'water']
# there are also methods for lists, like sort()
breakfast.sort()
breakfast
['kiwis', 'peanut butter sandwish', 'water', 'yogurt']
greeting.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-1405c0c7855b> in <module>
----> 1 greeting.sort()

AttributeError: 'str' object has no attribute 'sort'
# string concatenation is when you add two strings together
"Hello" + "goodbye"
'Hellogoodbye'
# f-string formatting is when you use an "f" and curly brackets {} 
# to tell python that you are going to put code in the string

f"Today for breafast, I ate {breakfast}"
"Today for breafast, I ate ['kiwis', 'peanut butter sandwish', 'water', 'yogurt']"

Homework help#

name = "Filipa"
age = 33
f"my name is {name}, and my age is {age}"
'my name is Filipa, and my age is 33'