Coding Activities for Python Programming Language
Begin by opening the Python interactive shell from JupyterLab or Anaconda. To do this, open a command line in the relevant application and type “Python”. You should see the Python logo with a few lines of text like this:
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Python 3.9.7 (default, Sep 16 2021, 16:59:28)
[MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Now let’s write some code. Start by assigning the number 10 to a variable. Variables are used to store data. To assign the number 10 to a variable called “myNumber”, type the following code:
myNumber = 10
Now let’s do something with this number. Let’s print it out. To print it, type the following code:
print(myNumber)
You should see the number 10 printed out. Now let’s try doing something more complicated. Let’s add 2 to the number and print it out. To do this, type the following code:
myNumber = myNumber + 2
print(myNumber)
You should see the number 12 printed out. Congratulations, you have written and executed your first Python program! To exit the interactive shell, type “exit()”.
Further activities with Python
hello_world.py
# print a statement: 'Hello World!'
print('Hello World!')
# print a statement: 'Hello World from a new cell'
print('Hello World from a new cell')
variables.py
# Creates a variable with a string "Frankfurter"
title = "Frankfurter"
years = 23
hourly_wage = 65.40
expert_status = True
# Print the variables
print(title)
print(years)
print(hourly_wage)
print(expert_status)
# Prints the data type of each declared variable
print("The data type of variable title is", type(title))
print("The data type of variable years is", type(years))
print("The data type of variable hourly_wage is", type(hourly_wage))
print("The data type of variable expert_status is", type(expert_status))
# Using variable names in calculations
total_miles = 257
gallons_gas = 7.2
miles_per_gallon = total_miles / gallons_gas
# Updating variables using assignment
miles = 48
kilometers = 0.621371 * miles
# Substituting/formatting variable
message = f"The total kilometers driven was: {kilometers}"
print(message)
# Variable naming conventions
# Bad Example
mpg = 24
# Better Example
miles_per_gallon = 24