Variables in Python¶

  • Go back to Introduction
  • Jump to Data Types

Objectives¶

  • assign scalar values to variables and perform calculations
  • Trace value changes in programs that use scalar assignment

Variables¶

  • Variables are names for values.

    • Can only contain letters, digits, and underscore _
    • cannot start with digit
    • are case sensitive
  • names should be meaningful so you or another programmer knows what it is.

  • variables that start with _ have special meaning

  • = symbol assings value on the right to the name on the left

In [1]:
age = 15
first_name = 'Tom'

print function¶

  • displays the value of variables
In [1]:
age = 15
first_name = 'Tom'
In [2]:
print(age)
print(first_name, age)
print(first_name, 'is', age, 'years old')
15
Tom 15
Tom is 15 years old

Variables persist between cells!

Reading Errors¶

In [3]:
print(second_name)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 print(second_name)

NameError: name 'second_name' is not defined

Variables can be used in calculations¶

In [4]:
later_age = age + 4
print('Age in four years', later_age)
Age in four years 19

Excercise 2: Swapping Values¶

Fill the table showing the values of the variables in this program after each statement is executed.

# Command  # Value of x   # Value of y   # Value of swap #
x = 1.0    #              #              #               #
y = 3.0    #              #              #               #
swap = x   #              #              #               #
x = y      #              #              #               #
y = swap   #              #              #               #

If you doubt, test it by yourself on a jupyter notebook!

Data Types and Type Conversion¶

  • Go back to Variables in Python

Data Types¶

  • Every value has a specific type.
In [18]:
print(type(2))
<class 'int'>
In [9]:
print(type(age))
Out[9]:
int

Some more examples

In [19]:
print(type(print))
<class 'builtin_function_or_method'>
In [20]:
print(type(3.14))
<class 'float'>
In [21]:
print(type("Every value has a type!"))
<class 'str'>
In [22]:
print(type(type))
<class 'type'>

Data types control what operations can be performed on a given value¶

In [13]:
print(5-3)
2
In [14]:
print('hello' - 'h')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[14], line 1
----> 1 print('hello' - 'h')

TypeError: unsupported operand type(s) for -: 'str' and 'str'
In [15]:
print(5+3)
8
In [16]:
print('hello' + 'h')
helloh

Functions may be type specific¶

In [33]:
print(first_name)
print('Number of characters: ', len(first_name))
Tom
Number of characters:  3
In [34]:
print(len(52))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[34], line 1
----> 1 print(len(52))

TypeError: object of type 'int' has no len()

Can mix integers and floats¶

In [35]:
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
half is 0.5
three squared is 9.0

Operands¶

Best way of learning this is by trial and error! Create a new cell, state what you want to do, and see if the result is what you expect :) . You can also read the documentation

In [40]:
print('Multiplication', '5 * 3: ', 5 * 3)
print('Power', '5**3: ', 5**3)
print('Division', '5/3: ', 5/3)
print('Sum', '5+3: ', 5+3)
print('Subtract', '5-3: ', 5-3)
Multiplication 5 * 3:  15
Power 5**3:  125
Division 5/3:  1.6666666666666667
Sum 5+3:  8
Subtract 5-3:  2

On division

In [41]:
print('Integer division', '5 // 3:', 5 // 3)
print('Floating point division', '5 / 3:', 5 / 3)
print('Remainder from integer division (modulo)', '5 % 3:', 5 % 3)
Integer division 5 // 3: 1
Floating point division 5 / 3: 1.6666666666666667
Remainder from integer division (modulo) 5 % 3: 2

Treating complex numbers, python understands special character j for imaginary part.

In [43]:
a_complex_number = 6 + 2j
print(type(a_complex_number))
print(a_complex_number.real)
print(a_complex_number.imag)
<class 'complex'>
6.0
2.0

Takeaway¶

  • Use variables to store values.
  • Use print to display values.
  • Variables persist between cells.
  • Variables must be created before they are used.
  • Variables can be used in calculations.
  • Use the built-in function len to find the length of a string.
  • Python is case-sensitive.
  • Use meaningful variable names.