Return to Course Home Page


Interactive Session: Variables & Operators

⬅️ Previous Session | 🏠 Course Home | 🚦 EDS217 Vibes | ➡️ Next Session |

variables.jpg

All programming languages contain the same fundamental tools: variables, operators, and functions. This session will covers the first two of these basic elements of the Python language.

Session Topics
  • 📌 Numbers: int, float
    • Arithmetic operators
    • Boolean operators
    • Built-in functions for numerical objects
  • 📌 Strings
    • Built-in functions for strings
    • Formatted print statements

Instructions

We will work through this notebook together. To run a cell, click on the cell and press “Shift” + “Enter” or click the “Run” button in the toolbar at the top.

🐍     This symbol designates an important note about Python structure, syntax, or another quirk.

▶️     This symbol designates a cell with code to be run.

✏️     This symbol designates a partially coded cell with an example.


Variables + Operators

Variables are used in Python to create references to an object (e.g. string, float, DataFrame, etc.). Variables are assigned in Python using =.

🐍 <b>Note.</b>
Variable names should be chosen carefully and should indicate what the variable is used for. Python etiquette generally dictates using lowercase variable names. Underscores are common. Variable names cannot start with a number. Also, there are several names that cannot be used as variables, as they are reserved for built-in Python commands, functions, etc. We will see examples of these throughout this session.

Numbers

Numbers in Python can be either integers (whole numbers) or floats (floating point decimal numbers).

The following syntax is used to define an integer:

x = 1
y = 42
▶️ Run the cell below.
Code
# Define variables x and y as integers.
x = 1
y = 42

The following syntax is used to define a float:

a = 1.0
b = 42.0
c = 23.782043
###

✏️ Try it. Define variables a, b, and c according to the values above.

Code
# Define variables a, b, and c as floats.
a = 1.0
b = 42.0
c = 23.782043

Arithmetic Operators

Just like a calculator, basic arithmetic can be done on number variables. Python uses the following symbols

Symbol Task
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
// Floor division
** Power
###

✏️ Try it. Practice these arithmetic operations by running the code in the cell below. Feel free to add more to test the operators. Use the print() command to output your answers.

Code
# Do some math.

Notice that the order of operations applies.

Boolean Operators

Boolean operators evaluate a condition between two operands, returning True if the condition is met and False otherwise. True and False are called booleans.

Symbol Task
== Equals
!= Does not equal
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
▶️ Run the cell below.
Code
print( b >= a )
print( 87 < -2 )
print( c != 0 )
print( y == x)

Built-in functions

Python has a number of built-in functions. Here we will introduce a few of the useful built-in functions for numerical variables.

The type() function is used to check the data type of a variable. For numerical arguments, either float or int is returned.

▶️ Run the cell below.
Code
1

The isinstance() function is used to determine whether an argument is in a certain class. It returns a boolean value. Multiple classes can be checked at once.

isinstance(12, int)
>>> True

isinstance(12.0,int)
>>> False

isinstance(12.0,(int,float))
>>> True

The commands int() and float() are used to convert between data types.

▶️ Run the cell below.
Code
print( float(y) )
print( int(c) )

Notice that when converting a float value to an integer, the int() command always rounds down to the nearest whole number.

To round a float to the nearest whole number, use the function round(). You can specify the number of decimal places by adding an integer as an argument to the round() function .

▶️ Run the cell below.
Code
print( round(c) )
print( round(c,3) )

The complex() function is used to define a complex number. We won’t be using complex numbers in this course, but it’s important to know that python is happy to handle them.

▶️ Run the cell below.
Code
d = complex('5+2j')

To return the absolute value of a number, use the abs() function.

▶️ Run the cell below.
Code
print( abs(d) )
print( abs(-12) )

The divmod() function returns the quotient and remainder of two input operands in a tuple. (Tuples are another data type that we will cover later.)

divmod(64, 4.2)

Output:

(15.0, 0.9999999999999973)

The pow() function is an alternative to the ** operator for raising a number to an exponent, i.e. x^y. An optional third argument is used to return the modulus (%) of the power of a number, i.e. x^y % z.

pow(8,2)

Output:

64
pow(8,2,3)

Output:

1

Strings

Pieces of text in Python are referred to as strings. Strings are defined with either single or double quotes. The only difference between the two is that it is easier to use an apostrophe with double quotes.

mytext = 'This is a string.'
mytext2 = "This is also a string."

To use an apostrope or single quotes inside a string defined by single quotes (or to use double quotes), use a single backslash ( \ ) referred to as an “escape” character.

q1a = "What is Newton's 1st law of motion?"
q1b = 'What is Newton\'s 1st law of motion?'

Built-in functions

Just like the int() and float commands, the str() command converts a number to a string.

▶️ Run the cell below.
Code
ystr = str(y)

The + operator can be used to combine two or more strings.

▶️ Run the cell below.
Code
s = 'isaac' + ' ' + 'newton'

The commands string.upper() and string.capitalize() can be used to convert all letters in the string to uppercase and capitalize the first letter in the string, respectively.

▶️ Run the cell below.
Code
print( s.upper() )
print( s.capitalize() )

Formatted print statements

Python uses C-style formatting to create new, formatted strings with the % operator. This is useful for printing variables in functions and when asking for user input, both of which we will discuss later. Formatted print statements contain a string argument with one of the following specifiers:

Symbol Task
%s Strings
%d Integers
%f Floating point numbers

The second argument can contain a variable name or a tuple, which is a list of a fixed size. The arguments are separated by the % operator.

▶️ Run the cell below.
Code
city = 'Santa Barbara'
yrs = 3
print( 'I live in %s.' % city )
print( 'I have lived in %s for %d years.' % (city,yrs))
Code
# Define the variable info.
info = (first, age)
# Complete the sentence to be printed
sentence = "My name..."
# Print
print( sentence % info)

When printing floats, the %f argument specifier can be accompanied by a number of decimal places to print only a certain number of digits.

▶️ Run the cell below.
Code
import math
pi_sqrt = math.sqrt(math.pi)
print("The square root of pi is %f." % pi_sqrt)
print("The square root of pi is %.2f." % pi_sqrt)

The input() function allows for user input within a script or program. Importantly, when Python prompts the user for input, the input is stored as a string, regardless of what it is. Thus, if you write a function (a type of object we will explore in a future session) prompting the user for a number, you must be sure to convert the variable storing the input to an integer or float.

To demonstrate this, run the following cell, entering the month in which you were born in numerical format (e.g. if you were born in April, your input would be 4) when prompted.

▶️ Run the cell below.
Code
month_in = input('Month of birth (1-12): ')
type(month_in)