Strings
The keyword print()
is a function in Python. You can usually identify a function in Python by some keyword followed by open and closing parentheses, i.e. ()
, and possibly one or more arguments inside the the parentheses. In the example above, the argument to the print function is the string "Hello, World!". Strings in a programming language are a collection of characters, e.g. ASCII or Unicode. You can verify that "Hello, World!"
is a string, by passing it as an argument to the function type()
.
type("Hello, World!")
str
is just shorthand for "string". str
is called the data type. There are many other data types in Python and we will discuss them each in turn as we encounter them.
String concatenation
If you want to concatenate two or more strings together, there are several ways to achieve this in Python. The first and likely simplest method is to use the +
operation. We often associate +
with adding two numbers together, in this case, we can use it to add two strings together. For example,
"Hello, " + "World!"
The +
operation will not work if you attempt to add a number to a string, e.g.
"2 + 2 = " + 4
However, we can make this work by explicitly converting the integer 4 (the default Python data type for 4
is int
) to a string, i.e.
"2 + 2 = " + str(4)
We could also use quotes around 4, i.e. "4"
to ensure it is of data type str
instead of int
.
Another way to produce a formatted string is to use the .format()
function that operates on strings. We'll start with an example and the explanation will follow
"Hello, {}{}".format("World", "!")
In the example above, notice the two sets of braces {}
in the string. These act as placeholders, that are then replaced by the arguments of .format()
in order. So "World"
gets inserted into the location of the first brace and "!"
gets inserted into the location of the second brace. The dot notation, i.e. .format()
might look strange attached to the end of the string, this is a convention from object-oriented programming that will become clear later when that topic is discussed in detail. A nice feature of the .format()
function is that is can provide some type-casting between the number data types like float
, int
, complex
and str
. So the example we attempted above will work without error using this method
"2 + 2 = {}".format(4)
The final method we'll discuss is how to join a list of strings together given some delimiter. Again, a list
is a Python data type that we'll discuss in due course, but for now, you can think of it as a collection of items grouped by surrounding square braces []
and separated by commas. For example, if we wanted to join the list
['a', 'list', 'is', 'a', 'collection', 'of', 'items']
with a whitespace delimiter to form a sentence fragment, we could do this by passing the list as an argument to the .join()
function
" ".join(['a', 'list', 'is', 'a', 'collection', 'of', 'items'])
In this case, the leading " "
indicates the delimiter as whitespace, but we can specify any delimiter, for example
"||".join(['a', 'list', 'is', 'a', 'collection', 'of', 'items'])
Finally, if you have a really long string that you want to span multiple lines in the source code, but be treated as a single continuous string otherwise, you can use the \
notation at the end of each line to indicate that the string on the following line should be joined with the current line
"Here is a really long " \
"string."
Variables
We can assign the values stored in different data types, e.g. str
, int
, etc., to variables in Python for later use. In the example below, the string "Hello, "
is "stored" in a variable hello
and likewise "World!"
is "stored" in the variable world
. I use the word "stored" in quotes because this allows us a convienent way to think about variables, but in reality, the data is stored in the memory of the computer and the variable just points the program to that location in memory.
hello = "Hello, "
world = "World!"
We can now use the variables hello
and world
to perform further operations, like concatenation as demonstrated earlier.
hello + world
Do not let the similarity between the variable name and what's "stored" in it confuse you, as the variable name is completely arbitrary and decided upon by the programmer. Repeating the example above with completely arbitrary variable names for demonstration
dog = "Hello, "
cat = "World!"
dog + cat
Of course you shouldn't do this. You should use descriptive variable names so that your code is readable to yourself and others in the future.
Variables can store any valid data, for example an int
is stored as days_in_a_year
below.
It's convention in Python to separate words in variable names with an underscore _
.
days_in_a_year = 365
print(days_in_a_year)
We can reassign the variable to a different number to update its value.
days_in_a_year = 366
print(days_in_a_year)
We can use the variable itself in a reassignment operation, e.g.
days_in_a_year = days_in_a_year - 1
print(days_in_a_year)
In the operation above, the expression to the right of the equal (=
) sign is evaluated first, so days_in_a_year
which currently stores the value 366
has 1
subtracted from it and is then reassigned to the variable days_in_a_year
. If all you need to do is a single mathematical operation to a variable and reassign it to itself, there are a few shorthand operations for that.
days_in_a_year -= 2
days_in_a_year += 3
print(days_in_a_year)
The first line above subtracts 2
from days_in_a_year
and reassigns the result to days_in_a_year
. The second line then adds 3
so the net change over the two operations is that the value stored in days_in_a_year
has been incremented by 1
. There are similar operations for multiplication and division.
Since we've started using mathematical operations, let's discuss them in more detail.
Mathematical operations
All of the standard calculator arithmetic operations are available and there are really no surprises here, but let's quickly demonstrate several.
addition = 3 + 5
print("3 + 5 = {}".format(addition))
subtraction = 7 - 5
print("7 - 5 = {}".format(subtraction))
multiplication = 8 * 3
print("8 x 3 = {}".format(multiplication))
division = 3 / 2
print("3 / 2 = {}".format(division))
There is one subtly here to explain. Let's look at the data type for the data stored in multiplication
type(multiplication)
And compare that to what's stored in division
type(division)
All of the inputs to both multiplication
and division
were originally of type int
(we could have forced the input, and hence the output, to be of type float
by using a decimal after the number, so 8.0
instead of 8
); however, Python performed a type casting operation to turn the output into a float
because that is what is required to store a rational number that results when dividing 3 by 2.
This may not seem too important, and in most cases it's not, but integers take up less space in memory and the mathematical operations are performed faster on a computer than when doing floating-point arithmetic.
The power operation is a little different in Python than some programming languages that use the ^
to indicate taking a power. In Python, $x^2 = $ x ** 2
. For example,
power = 2 ** 8
print(power)
Another useful operation is called the modulo operator. In Python it is represented as %
. This operation gives the remainder after whole division with a number. For example,
15 % 2
so 15 / 2 yields 7 evenly plus 1 remainder. We can use this type of operation to design a test to check if a number is even or odd.
is_even = 15 % 2 == 0
print(is_even)
The double equal ==
is a boolean operation. It returns True
if the left and right sides are equal, otherwise it returns False
. In this case, the resulting False
is stored in the variable is_even
. We can verify that it is of type bool
type(False)
We'll look at more boolean operations later, but for now, you can negate
any boolean variable with the not
keyword in front of the bool
.
not is_even
Python functions: a quick primer
Functions in Python can be thought of as small programs in their own right, i.e. they take inputs, called arguments, and usually return something (this is not a strict requirement). Both the arguments and the return variable can be of any valid Python type.
Functions are defined with the def
keyword. Additionally, in Python, whitespace is syntax so anything that is to be included in the function body must be indented to the same level. Let's look at an example
def my_math_operation(a, b):
ans = a + b / 2 + 56
return ans
The function above has the name my_math_operation
and takes the arguments a
and b
. These arguments are replaced in the expression a + b / 2 + 56
, for instance if a=2
and b=4
then the expression reads 2 + 4 / 2 + 56
. This expression is then evaluated mathematically and then stored in the variable ans
which is returned when the function exits. The variable ans
is said to be local to the function, i.e. it is not available for use outside of the function.
What appears above, only defines the function. To execute it, we call it on a separate line providing values for a
and b
.
my_math_operation(2, 4)
The arguments can be variables themselves as long as they are defined somewhere, e.g.
num1 = 67
num2 = 89
my_var = my_math_operation(num1, num2)
In this case, the function executes and the result is stored in my_var
which can be used later.
print(my_var)
It is good programming practice to build large programs or applications by executing a series of functions in sequence, often delivering the results of one function as arguments to the next function and/or combining the results of several function calls until the final desired result is achieved.
We will discuss more attributes of functions in the sequel.
Further reading
Further reading on data types can be found in the Python documentation.