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 = 5Copy 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
yName 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,_tempInvalid 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, capNote 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.14String: A sequence of characters, e.g.,
'Hello, World!'Boolean: A value that is either
TrueorFalse
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
betaWe 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.
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 (300,000,000), and 1.5e-4 represents (0.00015):
speed_of_light = 3.0e8 # in meters per second
avogadro_number = 6.022e23 # in mol^-1
speed_of_light, avogadro_numberNote 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*3We 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*4For exponentiation, use **:
2**3, 4**0.5For division, Python uses / for floating-point division and // for integer (floor) division:
7/2, 7//2What about the remainder of an integer division? The remainder can be obtained using the modulo operator %:
7 % 2The above process can be represented as:
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 ()>: Greater than ()<: Less than ()>=: Greater than or equal to ()<=: Less than or equal to ()
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 <= bLogical Operators¶
Logical operators are used to combine multiple Boolean expressions. The three main logical operators in Python are:
and: ReturnsTrueif both operands areTrueor: ReturnsTrueif at least one operand isTruenot: Returns the opposite of the operand, which isTrueif the operand isFalseandFalseif the operand isTrue
x = True
y = False
x and y, x or y, not xIf 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: whetherageis less than 18is_senior: whetherageis at least 65eligible_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 = TrueProblem 2: Functions¶
Define functions below:
Polynomial function:
Square root function:
Exponential function:
Use your functions to calculate .
Problem 3: Iodometry¶
Yue 20 Van Nya “ 5min ” wants to measure the concentration of a solution by the following procedure:
Add of and of solution of concentration into a conical flask.
Add of solution to measure into the flask, wait until the reaction is complete. The equation of reaction is:
Titrate the generated using 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 of solution. The equation of titration is
Calculate the concentration of 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:
Charles J. Weiss’s Scientific Computing for Chemists with Python
GenAI for making paragraphs and codes(・ω< )★
And so many resources on Reddit, StackExchange, etc.!
Acknowledgments¶
This lesson draws on ideas from the following sources: