Code
# Define variables x and y as integers.
= 1
x = 42 y
⬅️ Previous Session | 🏠 Course Home | 🚦 EDS217 Vibes | ➡️ Next Session |
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
int
, float
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 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 in Python can be either integers (whole numbers) or floats (floating point decimal numbers).
The following syntax is used to define an integer:
= 1
x = 42 y
▶️ Run the cell below.
# Define variables x and y as integers.
= 1
x = 42 y
The following syntax is used to define a float:
= 1.0
a = 42.0
b = 23.782043 c
✏️ Try it. Define variables a, b, and c according to the values above.
# Define variables a, b, and c as floats.
= 1.0
a = 42.0
b = 23.782043 c
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.
# Do some math.
Notice that the order of operations applies.
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.
print( b >= a )
print( 87 < -2 )
print( c != 0 )
print( y == x)
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.
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.
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.
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.
= complex('5+2j') d
To return the absolute value of a number, use the abs()
function.
▶️ Run the cell below.
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
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.
= 'This is a string.'
mytext = "This is also a string." mytext2
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.
= "What is Newton's 1st law of motion?"
q1a = 'What is Newton\'s 1st law of motion?' q1b
Just like the int()
and float
commands, the str()
command converts a number to a string.
▶️ Run the cell below.
= str(y) ystr
The +
operator can be used to combine two or more strings.
▶️ Run the cell below.
= 'isaac' + ' ' + 'newton' s
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.
print( s.upper() )
print( s.capitalize() )
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.
= 'Santa Barbara'
city = 3
yrs print( 'I live in %s.' % city )
print( 'I have lived in %s for %d years.' % (city,yrs))
# Define the variable info.
= (first, age)
info # Complete the sentence to be printed
= "My name..."
sentence # 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.
import math
= math.sqrt(math.pi)
pi_sqrt 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.
= input('Month of birth (1-12): ')
month_in type(month_in)