Digital Scholarship Resources - Vanderbilt Libraries Digital Scholarship and Communications Office

Previous lesson:

If you weren’t sure how you were going to be running your code: Installing a programming environment

If you wanted to start coding Python as quickly as possible: Quickstart guide for running Python in a Colab notebook

Python programming basics

This lesson is focused on developing familiarity with core statements and functions that are frequently used in Python scripts.

Learning objectives At the end of this lesson, the learner will:

Total video time: 53m 8s (66m 40s with optional practice script videos)

Lesson Jupyter notebook at GitHub

Lesson Colab notebook

Lesson slides

The = assignment operator

Introduction to variable assignment (3m25s)

String, number, and boolean object types

A string is a sequence of characters, such as a word or sentence.

There are a variety of number types in Python. Two types are integers (numbers with no decimal point) and floating point numbers (numbers with a decimal point).

A boolean is a True or False value.

Literals

In a literal, you state explicitly what the object is. String literals are written within single or double quotes:

"cat"
'dog'
"My name is Steve."
'!@#$%^&*'

To create a literal containing a quote, enclose it in the other kind of quote:

"That's OK!"
`Why is he called "Paco"?'

A back slash is used to generate special characters, such as a newline (“hard return” character). The character after the backslash has a special meaning and is not included in the string. Example:

'This is the first line of text.\nThis is the second line of text.'

Number literals are written without quotes:

3.14159
157
57.25
0.0098

Bolean literals are written like this, without quotes:

True
False

Assignment to variables

Values are assigned to variables using an equals sign. In variable assignment, an equals sign does not mean that the two things are equal! The value on the right is assigned to the variable on the left. It’s helpful to think of the equals sign as an arrow pointing to the left. Examples:

user_name = "smithjr"
is_door_open = False
number_of_array_elements = 47
eulers_number = 2.7182818

In these examples, literals are being assigned to variables. The contents of a variable can also be assigned to a variable, or an expression can be evalutated and the result placed in a variable.

user_name = last_login_name
sum = number_widgets + 3
too_many = sum > 10

In the third example above, the variable too_many will contain a boolean (True or False) depending on a condition (whether the number in sum is greater than 10 or not).


Assignment to variables: coding conventions (7m28s)

The following conventions are suggestions for naming that are commonly used and “safe”. That doesn’t mean that you can construct names in other ways and get away with it, but if you follow these conventions, your code will be easy to read and won’t have unexpected behavior.

Your code is less likely to have bugs if it is easy for a human to read it and easily tell what’s going on. For that reason, it is better to have object names that are descriptive of what the object is or does. For example, a name like load_participant_data is better than x.

The following characters can be considered “safe” for names in Python: upper and lower case Roman letters, numerals, and the underscore (_) character. Periods (dots) have special use in Python. Spaces are bad. Hypens can cause problems in some circumstances, so it’s better to avoid them. As a general practice, it’s probably safest to begin object names with letters, since other symbols sometimes have special uses, and in some contexts, object names beginning with numerals might have problems.

For names of variables and functions, the PEP 8 style guide recommends separating words with underscores. Examples: company_report_file_name and convert_xml_to_json. This style is sometimes called snake_case.

camelCase is also frequently used. In camelCase, descriptive words are concatenated, with the first word beginning with a lower case letter and subsequent words beginning with capital letters. Examples: companyReportFileName and convertXmlToJson.


Built-in functions

Review of functions (2m14s)

A function is a way to break Python into reusable chunks.

A function is like a processing machine. You put stuff into it and different stuff comes out of it. Think of a latte-making machine. It might have three inputs: one for coffee beans, one for milk product, and one for water. You put those three things in and a latte comes out. The exact result will depend on what you put in. Put in decaf beans, fat-free milk, and water and you get a skinny decaf latte. Put in regular beans, soy milk, and water and you get a vegan regular latte. Put in regular beans, full cream milk, and no water and you get an error.

The things you put into the function are called arguments. The general format for a Python function is:

function_name(argument1, argument2, ...)

There can be zero to many arguments in a function. The latte function might look like this:

make_latte(beans, milk, water)

The output of the function, called the return value can be assigned to a variable:

my_latte = make_latte(beans, milk, water)

Some built-in functions

Python comes with build-in functions that are always available. Here are some:

print()
input()
max()
len()
type()
int()

Built-in functions: print and input (5m17s)

print() function example:

# The argument passed into the print() function is printed to the display.
# There is no return value
print(character_name) # pass in a variable
print() # pass in nothing
print('Fred') # pass in a literal

input() function example:

# The argument passed into the input() function is the prompt to the user.
# The return value is the string entered by the user from the keyboard.
my_character = input('What is the name of the character? ')
print(my_character)

Review of function behavior (1m46s)


Comments in programs (1m57s)

Examples:

# Comment on a separate line (ignored by the Python interpreter)
print('some words') # comment on the same line as a statement (everything after # is ignored)

Type of objects

The type function (3m14s)

type() function example:

# The argument passed into the type function is the object whose type you want to know.
# The return value is the type of the object.
# The output can be assigned to a variable.
the_type = type("a word")
print(the_type)

Function nesting example:

print(type(True))

Cross-cell persistence of values (3m15s)


String return value of input function (1m31s)

Example:

# What is the type of the output of the input() function?
answer = input("Input a string or number: ")
print(answer)
print(type(answer))

What determines the type of a variable? (2m19s)


Requirements of function arguments (4m57s)

max() function examples:

print(max(1, 5, 2))
print(max(3, 6, 14, 1, 256, 34))
print(max()) # produces an error

len() function examples:

print(len('dog'))
print(len('aardvark'))
print(len('')) # '' is called the empty string
print(len(42)) # produces an error

Inputting a number (4m38s)

Type conversion using the int() function:

# We may be able to turn one kind of object into another.
a_string = '42'
print(a_string)
print(type(a_string))
a_number = int(a_string)
print(a_number)
print(type(a_number))

Numeric input example:

response = input('What is your number? ')
number = int(response)
# You can print several arguments by separating them by commas
print('Here is your number, plus 2:', number + 2)

Operators

Math operations and concatenation (3m18s)

Some simple math operators are + (addition), - (subtraction), * (multiplication), and / (division).

Examples:

number_widgets = 1
answer = number_widgets + 3
print(answer)
first_number = 325
second_number = 145
together = first_number + second_number
print(together)
print(type(together))
first_number = '325'
second_number = '145'
together = first_number + second_number
print(together)
print(type(together))

The + operator is used for concatenation of strings.


Working with boolean operations (7m49s)

Boolean operators are: == (equivalence), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to).

Examples:

print('dog' == 'cat')
print('cat' == 'cat')
print('dog' != 'cat')
print(3 > 2)
print(2 > 2)
print(2 >= 2)
# Notice that one `=` is the assignment operator and two `==` is the equivalence operator.
same_animal = 'cat' == 'monkey'
print(same_animal)
first_animal = input('What is your first animal? ')
second_animal = input('What is your second animal? ')
same_animal = first_animal == second_animal
print('First animal the same as second animal?', same_animal)

Optional Practice scripts

Look at the scripts in the lesson Colab notebook and try to explain what they do before you run them. Then try running the to see if what you predicted was correct. If you don’t understand what happened, you can watch the following videos.

Practice instructions (0m47s)


Practice script 1 (2m14s)

name = input("What's your name? ")
print('Hello ' + name + '! How are you?')

Practice script 2 (3m02s)

first_number = float(input('What is your number? '))
second_number = 67
biggest = max(first_number, second_number, 100)
print(biggest)

Practice script 3 (2m29s)

name = input('What is your name? ')
how_long = len(name)
print('Your name is '+ name + '. It is: ')
print(how_long)
print('characters long.')

Practice script 4 (2m19s)

a_number = 16
a_number = a_number + 1
print(a_number)

Practice script 5 (2m41s)

number_widgets = int(input('How many widgets? '))
sum = number_widgets + 3
too_many = sum > 10
print(too_many)

Practice assignment:

In each of the scripts that you write, for each variable in the script use a meaningful name that follows the PEP 8 style (“snake case”).

  1. Create a code cell that assigns a string to a variable, then prints the length of the string.
  2. Create a code cell that allows the user to input two numbers, then prints the difference between them. Don’t forget that the input() function produces a string that must be turned into a number before subtrating. Write this script two ways: one where the input strings are assigned to variables, then converted into numbers using separate statements, and another where the number conversion is done directly on the output of the input() function by nesting the two functions.
  3. Create a code cell where the user enters a string. The script concatenates ‘Simon says: ‘ to the front of their string and prints the result for the user.
  4. Create a variation of the previous script where the entered string is not concatenated to ‘Simon says: ‘, but rather is printed as a second argument of the print() function along with the ‘Simon says:’ string. How can you make the output be exactly the same as before (having a single space between the : and the string they entered)? What have you learned about the spacing of the output when print() has several arguments?
  5. Create a number guessing game. Set the value of the secret number using an assignment statement. Then let the user enter a number. Print two feedback statements. The first one should tell the user whether the guess was correct (True or False). The second print statement should tell the user whether the guess was too high (True or False). The user will need to re-run the cell with each guess.

Next lesson: Using code libraries


Revised 2022-03-18

Questions? Contact us

License: CC BY 4.0.
Credit: "Vanderbilt Libraries Digital Scholarship and Communications - www.library.vanderbilt.edu"