Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lesson 1: Basics of Python Programming

Instructor: Yuki Oyama, Prprnya

The Christian F. Weichman Department of Chemistry, Lastoria Royal College of Science

This material is licensed under CC BY-NC-SA 4.0

Welcome to the first lesson! In this lesson, we will cover the very basics of Python. If you have never programmed before, don’t worry! We will start from the ground up. If you have some experience, this will be a good refresher.

Variables and Data Types

In Python, data is stored in variables. A variable is a name that refers to a value. You can think of it as a label for a box that holds something inside. You can create a variable by assigning a value to it using the = operator. This is called assignment. For example:

x = 5

Copy this code into the next cell and run it by pressing Shift + Enter (on macOS pressing Shift + Return instead). You won’t see any output, but the variable x is now created and holds the value 5.

You can check the value of a variable by typing its name at the end of any cell after you defined it, then running it. For example:

y = 10
y

Name of a variable can be anything you like, as long as it starts with a letter or an underscore (_), and is followed by letters, numbers, or underscores.

  • Valid variable names: my_variable, data1, _temp

  • Invalid variable names: 1data, my-variable, my variable

Variable names are case-sensitive, so CAP, Cap and cap are different variables. Run the code below to see how variable names work:

CAP = 0
Cap = 1
cap = 2
CAP, Cap, cap

Note that in the code mode, we can output multiple variables by separating them with commas. The output will give them in a sequence wrapped by parentheses and separated by commas. Otherwise, you can use print() function to customize the output format. We will introduce functions later.

print(CAP, Cap, cap)

Spacing between the variable name and the operator is optional. However, it is good practice to put a single space after each operator.

space1=10
space2 = 10
space3    =      10
print(space1, space2, space3)

Data Types

There are several basic data types in Python. We have put a 5 for x, which is an integer. Other common data types include:

  • Float: A number with a decimal point, e.g., 3.14

  • String: A sequence of characters, e.g., 'Hello, World!'

  • Boolean: A value that is either True or False

Let’s take a look at each of these data types.

Integer

Integer is a whole number, positive or negative, without decimals. For example:

beta = 147
beta

We can check the type of variable using the type() function (again, we will introduce functions later, don’t worry!), type your variable name inside the parentheses of type():

type(beta)

Here, int stands for integer.

Float

Float is a number that has a decimal point. For example:

phi = 1.618
phi, type(phi)

Even if a float has zero decimal parts, it is still considered a float—it’s important to put a .0 to indicate that it’s a float:

type(8), type(8.0)

From the case above, you can see that integer and float are different data types. They have different preposes, and they behave differently in some operations. We will see more about this later.

Some float numbers can be represented in scientific notation, which is a way of expressing huge or tiny numbers. For example, 3.0e8 represents 3.0×1083.0 \times 10^8 (300,000,000), and 1.5e-4 represents 1.5×1041.5 \times 10^{-4} (0.00015):

speed_of_light = 3.0e8  # in meters per second
avogadro_number = 6.022e23  # in mol^-1
speed_of_light, avogadro_number

Note that the content after # is a comment, which is ignored by Python.

String

Strings are sequences of characters, enclosed in either single or double quotes.

greeting = 'Hello, Chem 18!'
greeting, type(greeting)

Here, str stands for string.

Boolean

Booleans represent one of two values: True or False. They are often used in conditional statements and comparisons.

is_chem_fun = True
is_chem_fun, type(is_chem_fun)

Here, bool stands for boolean.

Operators and Basic Arithmetic

We now shift our focus to how to manipulate these variables using operators. Operators are special symbols that perform operations on variables and values. Python supports several types of operators, including:

  • Arithmetic Operators: +, -, *, /, // (floor division), % (modulus), ** (exponentiation)

  • Comparison Operators: ==, !=, >, <, >=, <=

  • Logical Operators: and, or, not

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations. Here are some examples:

3+2, 5-2, 4*3

We can use parentheses to group operations and control the order of evaluation, just like what we study in primary school:

(3+2)*4, 3+2*4

For exponentiation, use **:

2**3, 4**0.5

For division, Python uses / for floating-point division and // for integer (floor) division:

7/2, 7//2

What about the remainder of an integer division? The remainder can be obtained using the modulo operator %:

7 % 2

The above process can be represented as:

7÷2=317 \div 2 = 3 \cdots 1

You may notice that types of the results vary depending on the operations. In general, if any operand is a float, the result will be a float. If both operands are integers, the result will be an integer (except for division /, which always returns a float).

Comparison Operators

Comparison operators are used to compare two values. They return a Boolean value (True or False) based on the comparison. There are six comparison operators in Python:

  • ==: Equal to (==)

  • !=: Not equal to (\ne)

  • >: Greater than (>>)

  • <: Less than (<<)

  • >=: Greater than or equal to (\ge)

  • <=: Less than or equal to (\le)

Be careful not to confuse = (assignment) with == (comparison)!

Here are some examples:

a = 5
b = 3
a == b, a != b, a > b, a < b, a >= b, a <= b

Logical Operators

Logical operators are used to combine multiple Boolean expressions. The three main logical operators in Python are:

  • and: Returns True if both operands are True

  • or: Returns True if at least one operand is True

  • not: Returns the opposite of the operand, which is True if the operand is False and False if the operand is True

x = True
y = False
x and y, x or y, not x

If you are confused about how logical operators work, click this link or refer to any textbooks about logic.

Assignment Operators

Before introducing assignment operators, let’s see how to update the value of a variable. You can simply reassign a new value to the variable:

count = 10
print(count)
count = 15
print(count)
count = 30
print(count)

Moreover, you can use the current value of the variable in the new assignment:

count = 10
print(count)
count = count + 5
print(count)

Let’s try it again by another operation:

count = 15
print(count)
count = count * 2
print(count)

Assignment operators are used to assign values to variables. The most common assignment operator is =, which we have already seen. However, Python also provides several compound assignment operators that combine an arithmetic operation with the assignment:

  • +=: Add and assign

  • -=: Subtract and assign

  • *=: Multiply and assign

  • **=: Exponentiate and assign

  • /=: Divide and assign

  • //=: Floor divide and assign

  • %=: Modulus and assign

For example:

count = 10
print(count)
count += 5  # Equivalent to count = count + 5
print(count)
count *= 2  # Equivalent to count = count * 2
print(count)

Defining Functions

Functions are blocks of code that perform a specific task. They are useful for reusing code and avoiding repetition. We have already seen some functions in the previous lessons. For example, print() is a function that prints the value of a variable or expression. We can define our own functions using the def keyword.

def plus_one(n):
    return n+1

plus_one(146)

Defining a function is as simple as defining a variable. The function name is followed by parentheses, which contain the arguments of the function. At the end of the function, we use the return keyword to return the value of the function. In some cases, we may not want to return anything, in which case we can drop the return keyword—which, is a rare case, and you don’t need to care so much about it (´▽`)

You can take multiple arguments by separating them with commas:

def plus(x, y):
    return x+y

plus(114, 514)

Sometimes we want to make some arguments optional. We can do this by assigning default values to the arguments:

def plus_default(x, y=0):
    return x+y

print(plus_default(1919))
print(plus_default(1919, 810))

Notice that all the optional arguments must come after the required arguments.

We can even define functions with no arguments:

def hello():
    print('Hello, world!')

hello()

End-of-Lesson Problems

Now it’s your turn! We will leave you with some interesting questions at the end of each lesson. Feel free to reach us out or discuss with your friends if you have any questions(´▽`)

Problem 1: 8-Twelve Discount

Consider an 8-Twelve discount policy: a person is eligible for a discount if they are a minor (under 18 years old), a senior (65 years or older), or have a student ID.

Define the variables below and write out the Boolean expressions to determine:

  • is_minor: whether age is less than 18

  • is_senior: whether age is at least 65

  • eligible_discount: true if a person is a minor, a senior, or has a student ID

Return eligible_discount at the end of the cell. The initial values are given for you.

age = 20
has_student_id = True

Problem 2: Functions

Define functions below:

  • Polynomial function: f(x)=3x22x+1f(x) = 3x^2 - 2x + 1

  • Square root function: g(x)=x=x12g(x) = \sqrt{x} = x^{\frac{1}{2}}

  • Exponential function: h(x,y)=2x+yh(x, y) = 2^{x+y}

Use your functions to calculate f(h(1,3))+f(6)g(9)f(h(1, 3)) + f(6) \cdot g(9).

Problem 3: Iodometry

Yue 20 Van Nya5min wants to measure the concentration of a KMnOX4\ce{KMnO4} solution by the following procedure:

  • Add 2.0 g2.0\ \mathrm{g} of KI\ce{KI} and 10 mL10\ \mathrm{mL} of HX2SOX4\ce{H2SO4} solution of concentration 1.0 molL11.0\ \mathrm{mol\,L^{-1}} into a conical flask.

  • Add 5.00 mL5.00\ \mathrm{mL} of KMnOX4\ce{KMnO4} solution to measure into the flask, wait until the reaction is complete. The equation of reaction is:

    2MnOX4X(aq)+10IX(aq)+16HX+(aq)2MnX2+(aq)+5IX2(aq)+8HX2O(aq)\ce{2MnO4-(aq) + 10I-(aq) + 16H+(aq) -> 2Mn^2+(aq) + 5I2(aq) + 8H2O(aq)}
  • Titrate the generated IX2\ce{I2} using 0.1020 molL10.1020\ \mathrm{mol\,L^{-1}} NaX2SX2OX3\ce{Na2S2O3} solution. Add five drops of a starch solution while the titration is about to end. Continue titration until the blue color of the solution vanished. The titration consumed 26.43 mL26.43\ \mathrm{mL} of NaX2SX2OX3\ce{Na2S2O3} solution. The equation of titration is

    IX2(aq)+2SX2OX3X2(aq)2IX(aq)+SX4OX6X2(aq)\ce{I2(aq) + 2S2O3^2-(aq) -> 2I-(aq) + S4O6^2-(aq)}

Calculate the concentration of KMnOX4\ce{KMnO4} solution. Define some variables, perform calculations, make outputs of your answer—and be fun! Just make sure that you should show all the steps in the code cell below.

Hint: The following is the quantitative relationship between related ions:

MnX2+ 5IX 5SX2OX3X2\ce{Mn^2+ \sim 5I^- \sim 5S2O3^2-}

Acknowledgments

This lesson draws on ideas from the following sources: