Hello, Python

1.1 Overview

In this session we are going to start learning a few basics about working with Python.

The agenda for this session is split into two main topics that are listed below:

  • How to handle input

  • How to handle output

1.2 Displaying output

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

In [1]:
print('Hello World')
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.

In [2]:
print('Paul Dirac')
print('12 Queensgate')
print('Huddersfield HD3 2RH')
Paul Dirac
12 Queensgate
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:

In [3]:
# basic example illustrating 
# the print function:
print('3 + 7')
3 + 7

1.3 Variables

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:

In [4]:
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
37.5
temperature= 37.5

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:

  • Names can't start with a number
  • Names can't be too long
  • Names can't contain special characters (although we are allowed 'underscores')

Guidelines for naming your variables:

  • Names should make sense; they should describe what they contain (e.g., 'total', 'username', etc)
  • Often you must use more than one word in a variable; in such cases you are encouraged to use underscores; e.g., 'number_of_toppings' rather than 'numberoftoppings'
  • For the most part you should always use lowercases (more about this when we discuss OOP)
  • Use all caps for the name of a variable when you know that the value of that variable is not going to change; this is called a CONSTANT in programming languages

Variables must be assigned values before they can be used in expressions. Also, variables can reference different values while a computer program is running.

In [99]:
# 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
A triangle has 3 sides
An octogon has 8 sides

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:

In [100]:
count = 10
print(count)           # first print statement

count = count + 10     # this is an augmented assignment
print(count)           # second print statement
10
20

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:

In [101]:
count = 10
count += 10      # this is the same as: 
                 #      count = count + 10
print(count)
20

An augmented assignment is executed as follows:

  1. Evaluate the expression on the RHS of $=$ to produce a value

  2. Then use the value produced to store it in the variable on the LHS of $=$

These augmented assignments can be applied to other operators, like $-$ and $*$. See the table included below:





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:

In [102]:
x, y = 1, 2          # multiple assignment

print('x = ', x)
print('y = ', y)
x =  1
y =  2
In [104]:
name, age = 'Keiko', 26       # multiple assignment 

print('First Name:', name)
print('Age:', age)
First Name: Keiko
Age: 26

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.

1.4 Data Types

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.

In [6]:
x = 4
type(x)  # press 'Run'
Out[6]:
int
In [7]:
y = 4.0
type(y)  # press'Run'
Out[7]:
float
In [8]:
z = 'duet'
type(z)   # press 'Run'
Out[8]:
str
In [9]:
# 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)
Florence Nightingale

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:

In [10]:
y = 34.5
print(y)               # number is displayed
y = 'Bonne_Bouffe'
print(y)               # now the string is displayed
34.5
Bonne_Bouffe

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).

1.5 Reading input from the keyboard

Python comes with a built-in function that allows us to read input typed by the user on the keyboard.

In [34]:
# 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)
Enter your first name: Xiang
Hello Xiang

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:

In [32]:
import math

number_1 = input('Provide a number: ')
number_2 = input('Provide another number: ')
total = number_1 + math.sqrt(number_2)
print(total)
Provide a number: 4
Provide another number: 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-32-40a482b62e04> in <module>()
      3 number_1 = input('Provide a number: ')
      4 number_2 = input('Provide another number: ')
----> 5 total = number_1 + math.sqrt(number_2)
      6 print(total)

TypeError: a float is required

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:

In [33]:
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
Provide a number: 10
Provide another number: 100
20.0

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:

In [35]:
# 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))
Provide a number: 10
Provide another number: 100
20.0

1.6 Doing Math in Python

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:

In [42]:
x = 7 + 12
x                # press 'run'
Out[42]:
19
In [95]:
7 + 12 = x      # press 'run'
  File "<ipython-input-95-4be3f77de04a>", line 1
    7 + 12 = x      # press 'run'
                                 ^
SyntaxError: can't assign to operator

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.





Operators in Python

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.





math Module Functions

To use a function from this module you must prefix its name with math.. For example:

In [39]:
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
2.0
3
4

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:

In [41]:
# 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
Give circle radius: 4
Area of circle is:  50.26548245743669
In [45]:
# 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))
This is e:  2.718281828459045
This is the same thing:  2.718281828459045

1.7 Odds and Ends

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).

In [54]:
var1 = 10; var2 = 20; var3 = 40; var4 = 230; var5 = 450    
    
    
total = var1 + var2 + var3 + \
         var4 + var5
    
print('Total is: ', total)    
Total is:  750

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:

In [96]:
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
Total is:  750
All work and no play makes Jack a dull boy

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:

In [61]:
print('One')        # output displayed on line 1
print('Two')        # output displayed on line 2
print('Three')      # output displayed on line 3
One
Two
Three

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:

In [98]:
# 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 = '?')     
One Two Three
One>>Two>>Three?
One	Two	Three?

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:

In [68]:
print('One\nTwo\nThree')
One
Two
Three
In [ ]:
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:

In [71]:
# ex. 1 -- string concatenation
print('This is ' + 'one string')    # note the extra space at the end of the first string
This is one string
In [97]:
# ex.2 -- string concatenation
print('\"Coming back to where you started ' +
      'is not the same as never leaving\" ')
"Coming back to where you started is not the same as never leaving" 

1.8 Formatting numbers

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.

In [86]:
print(format(12.34567,'.2f'))
12.35

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.

In [88]:
# 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 gravitational acceleration is:  9.8
The gravitational acceleration is:  9.807

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:

In [90]:
print('The number is:', format(123456.3435363,'12.2f'))
print('The number is:', format(123456.3435363,'9.2f'))
The number is:    123456.34
The number is: 123456.34

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:

In [92]:
# 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'))
 127.90
3465.15
   3.78
 264.82
  88.08
 800.00

(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:

In [94]:
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
The number is:  1.234566e+04
The number is:  1.235e+04
The number is:  1.235E+04



REFERENCE:

T. Gaddis, Starting out with Python (Fourth Edition), Pearson Education Ltd., 2018