A function is a piece of built-in code that performs an operation. Python comes with lots of such built-in functions that perform various operations. We'll discuss several of these functions throughout the course of this module.
The print function is perhaps one of the most fundamental such built-in function. We use it to display things on the computer screen
print('Hello World')
When Python executes this function, we say that the function is called.
In general, a function has a name, followed by a pair of parentheses that enclose the argument of the function. In this case the argument of the print function is a string literal (i.e., 'Hello World').
String literals consist of a sequence of characters (numbers, letters, tabs, etc) enclosed in quote marks or double-quote marks. These quote marks serve the purpose of indicating where the literal string starts and ends, respectively. Inside a string you can't have other quote marks.
print('Paul Dirac')
print('12 Queensgate')
print('Huddersfield HD3 2RH')
Each line in the above code represents a statement; here the statements are executed sequentially, in the order in which they appear.
Sometimes we want to add comments to our code. To this end we use the hash character:
# basic example illustrating
# the print function:
print('3 + 7')
A variable is a name that represents a value stored in the computer's memory. In particular, variables contain memory addresses of values. We say that variables refer to values.
We create a variable with an assignment statement:
temperature = 37.5 # creates a new variable (temperature)
# and stores the value 37.5 in it
# You can print variables...
print(temperature) # 1st print statement
#... or try this:
print('temperature =', temperature) #2nd print statement
As seen in this example, we don't have to limit the name of our variables to just one letter. Python is fairly easy going concerning the naming of variables, but there are some rules you must follow:
Guidelines for naming your variables:
Variables must be assigned values before they can be used in expressions. Also, variables can reference different values while a computer program is running.
# this examples demonstrates variable re-assignment
# start by assigning a value to the variable 'sides':
sides_number = 3
print('A triangle has', sides_number, 'sides')
# re-assign the variable so it references
# a different value:
sides_number = 8
print('An octogon has', sides_number,'sides')
# end of example
The assignment operations seen so far have all involved a variable on the LHS of the equality sign and some value on the RHS. All programming languages admit augmented assignments. These combine an assignment statement with an operator to make the statement more concise. Here's an example:
count = 10
print(count) # first print statement
count = count + 10 # this is an augmented assignment
print(count) # second print statement
These type of statements are so common that there is a shorthand for them. For example, the one above can be written in the equivalent form indicated below:
count = 10
count += 10 # this is the same as:
# count = count + 10
print(count)
An augmented assignment is executed as follows:

Multiple assignments are also allowed in Python. We can assign several values to an equal number of variables by using a single equality sign. The next examples should clarify how this works:
x, y = 1, 2 # multiple assignment
print('x = ', x)
print('y = ', y)
name, age = 'Keiko', 26 # multiple assignment
print('First Name:', name)
print('Age:', age)
In case you haven't noticed: the first variable on the LHS is assigned the first value on the RHS, the second variable on the LHS is assigned the second value on the RHS, and so on. The assignments are done by respecting the order on both the left and the right of the equality sign.
Variables can hold many different kinds of information. We call these data types. Data is stored in the computer's memory based on its data type (for our immediate purposes it does not matter how). A number that is written into a computer code is called a numeric literal.
Some common data types are: int, float, and str. Python determines on the fly the type of a numeric literal; see the examples included below.
x = 4
type(x) # press 'Run'
y = 4.0
type(y) # press'Run'
z = 'duet'
type(z) # press 'Run'
# example: use of str variables:
# create 2 variables that reference strings:
first_name = 'Florence'
last_name = 'Nightingale'
# display the values referenced by the above variables:
print(first_name, last_name)
A variable in Python can refer to items of any type. Below we assign a float to the variable y, and then re-assign a string literal:
y = 34.5
print(y) # number is displayed
y = 'Bonne_Bouffe'
print(y) # now the string is displayed
Key Points: Every value in Python has a specific type, which determines what operations can be applied to it. The two types used to represent numbers are int and float. Floating-point numbers are approximations to real numbers (this will be discussed at length later -- for now think of floats as decimal numbers).
Python comes with a built-in function that allows us to read input typed by the user on the keyboard.
# after the next line is executed, the computer prompt
# will wait for your input:
name = input('Enter your first name: ')
# check to see that the variable name
# does contain your own input:
print('Hello', name)
As you probably figure out (from the above example), the built-in function mentioned above is called input. The last character in the string that appears as the argument of this function is an empty space. That was added deliberately because the function does not automatically display a space after the prompt.
The input function always returns the user's input as a string, even if the user enters numeric data. Try this:
import math
number_1 = input('Provide a number: ')
number_2 = input('Provide another number: ')
total = number_1 + math.sqrt(number_2)
print(total)
The error message that we got on the screen was to be expected. The input function always returns a string -- obviously, we can't take the square root of a string.
Python has built-in functions that allow us to convert a string to a numeric type. Two of these functions are 'int' and 'float'. Note what happens to the previous code when we use them:
import math
val_1 = input('Provide a number: ') # type 10 when prompted
number_1 = float(val_1) # val_1 is converted to a floating point number
val_2 = input('Provide another number: ') # type 100 when prompted
number_2 = float(val_2) # val_2 is converted to a float
total = number_1 + math.sqrt(number_2) # this should be 10 + 10 = 20
print(total) # convince yourself that this is the case
The first line in this code imports a module that contains the math functions; note that later in this code we used 'math.sqrt', which represents (one of) the built-in square-root function(s) from that module. More on this, shortly.
We can reduce the number of lines of code used in this example by combining the statements that are grouped together. This is possible because both 'input' and 'float' are functions, and we can take advantage of the composition of two functions:
# this code is another implementation of the one immediately above
import math
val_1 = float(input('Provide a number: '))
val_2 = float(input('Provide another number: '))
print(val_1 + math.sqrt(val_2))
All the usual maths operations are available in Python.
Doing maths in Python follows the same rules you probably learned in school, with a few exceptions. The most important difference is that, in Python, the variable you're setting must always come before whatever calculations you are doing. Study the example included below:
x = 7 + 12
x # press 'run'
7 + 12 = x # press 'run'
Python supports all basic algebraic operations out of the box: adding, subtracting, multiplying, dividing, absolute value, and exponents. Some of the symbols that Python uses for these operations might be different from what you are used to using. For your convenience, some of the most commonly used operators in Python are included in the table below.

The Python standard library's math module contains numerous functions that can be used in mathematical calculations. There is another module that contains different implementations of the same functions (and much more) -- we postpone its discussion until we have covered a bit more ground.
A list of some of the more important functions found in this module is included below. These functions typically accept one or more values as arguments, perform a mathematical operation using the arguments, and return the result. All of the functions listed return a float value, except the ceil and floor functions, which return int values.

To use a function from this module you must prefix its name with math.. For example:
import math # this statement makes available to our code
# all the math functions in the above table
x = math.log10(10**2) # assign x the value of log to base 10 of 10**2 (i.e., 2)
print(x) # display x on the screen
# here is another example:
low = math.floor(3.64) # run the code to see what this function does
high = math.ceil(3.64) # run the code to see what this function does
print(low)
print(high)
# change 3.64 to 2.85 or 7.15 and run the code again
The math module also defines two constants, pi and e, which are assigned the values of the usual mathematical constants $\pi\simeq 3.14\dots$ and $e\simeq 2.718\dots$. An example for the former constant is included below:
# an interactive program that calculates
# the area of a circle
import math
R = float(input('Give circle radius: ')) # user input
A = math.pi*(R**2) # formula for area of a circle
print('Area of circle is: ', A) # output of the program
# math.exp(1) is the same as math.e
# run the code below to convince yourself
import math
print('This is e: ', math.e)
print('This is the same thing: ', math.exp(1))
Most programming statements are written on one line. Sometimes you'll find it useful to break a statement into multiple lines; this can improve the readability of your code.
Python allows you to break a statement into multiple lines by using the line continuation character, which is a backslah (\). You simply type the backslash character at the point where you want to break the statement, then press the ENTER key (to continue on the next line).
var1 = 10; var2 = 20; var3 = 40; var4 = 230; var5 = 450
total = var1 + var2 + var3 + \
var4 + var5
print('Total is: ', total)
Note that in the above example we also have several assignments on one line. Python is okay with that -- as long as you remember to terminate your statements with a semi-colon.
The line continuation character can be omitted when the statement you want to break into separate parts is enclosed between parentheses. Note how we can modify the example above:
var1 = 10; var2 = 20; var3 = 40; var4 = 230; var5 = 450
total = (var1 + var2 + var3 +
var4 + var5) # note the parentheses
print('Total is: ', total)
# or check this out:
print("All work and no play",
"makes Jack a dull boy")
# OBS. you can't split a string over several lines
# by using this latter approach
The next thing we'll be looking at is the fine-tuning of the output. Python offers a number of ways to exercise more control over the way the data appear on the screen.
By default, the print function prints a newline character at the end of each of your print statements. Check out the example included below:
print('One') # output displayed on line 1
print('Two') # output displayed on line 2
print('Three') # output displayed on line 3
What if you want all three outputs on the same line, separated by some space? You can do that by using an optional argument that specifies what the print function should use at the end of each line. Study the examples included below:
# we use the optional argument end ='....'
# to modify the default behaviour of the print function
# the user has to replace the dots with his/her own option
print('One', end=' ')
print('Two', end=' ')
print('Three', end = '\n') #'\n' represents the newline character
# another example:
print('One', end='>>')
print('Two', end='>>')
print('Three', end = '?\n')
# yet another one...
print('One', end='\t') # '\t' represents the tab character (4 horizontal spaces)
print('Two', end='\t')
print('Three', end = '?')
An escape character is a special character that is preceded by a backslah (\) appearing inside a string literal. We have already seen examples of escape characters above (e.g., \n is the newline escape character). Such characters are not printed on the screen, but they cause some action to be taken. See the example below:
print('One\nTwo\nThree')
Python recognises several escape characters, some of which are listed below:

The + operator was used earlier in these notes to add two or more numbers. When the + operator is used with two strings, it performs string concatenation; that is, one string is appended to another (the order of the two strings is important).
Check out the following examples:
# ex. 1 -- string concatenation
print('This is ' + 'one string') # note the extra space at the end of the first string
# ex.2 -- string concatenation
print('\"Coming back to where you started ' +
'is not the same as never leaving\" ')
Sometimes we want to display numbers that are rounded to just a few decimal places. By default, Python will write floating-point numbers in long form (including lots of decimal places). To control this behaviour we have several options, but for now we are going to look at the format function.
The built-in format function takes two arguments: a numeric value and a format specifier. The latter is a string that contains special characters specifying how the numeric value should be formatted.
print(format(12.34567,'.2f'))
In this example the format specifier is the string '.2f'
The part .2 specifies the precision, i.e. it indicates that we want to round the number to two decimal places.
The f in the format specifier informs Python of the data type of the number we are formatting; in this case the number 12.34567 is a floating-point number, hence the character 'f'.
The format function returns a string containing the formatted number.
# another example regarding the format function
print('The gravitational acceleration is: ', format(9.80665,'.1f')) # 1 decimal place
print('The gravitational acceleration is: ', format(9.80665,'.3f')) # 3 decimal places
The format specifier can include a minimum field width, which is the minimum number of spaces that should be used to display the value. If your number is shorter than the number of spaces specified, Python will still use the number of space you provided. Study the example included below:
print('The number is:', format(123456.3435363,'12.2f'))
print('The number is:', format(123456.3435363,'9.2f'))
In the first case 8 spaces would have been enough to represent the number, but Python used 12 (because that's what we asked for). In the second case it used 9 space (you can see the extra space between the colon and the first digit of the number printed out).
Field widths are helpful when you need to print numbers aligned in columns. The next example illustrates the idea:
# This program displays the following
# floating-point numbers in a column
# with their decimal points aligned.
num1 = 127.899
num2 = 3465.148
num3 = 3.776
num4 = 264.821
num5 = 88.081
num6 = 799.999
# Display each number in a field of 7 spaces
# with 2 decimal places.
print(format(num1, '7.2f'))
print(format(num2, '7.2f'))
print(format(num3, '7.2f'))
print(format(num4, '7.2f'))
print(format(num5, '7.2f'))
print(format(num6, '7.2f'))
(There are better ways to achieve the same result, as we shall see later in this module).
The format statement can be used to display numbers in scientific notation as well. This involves using the letter 'e' or 'E' instead of 'f'. See example below:
print('The number is: ', format(12345.657575757,'e'))
print('The number is: ', format(12345.657575757,'.3e'))
print('The number is: ', format(12345.657575757,'.3E')) # this is the same as the one
# immediately above
REFERENCE:
T. Gaddis, Starting out with Python (Fourth Edition), Pearson Education Ltd., 2018