Python Unit 1
How to run Python
You will use Python in two different modes:
- Interactive mode
- When on the shell, start Python by entering
python
This will display a message similar to
Python 3.10.2 (main, Jan 15 2022, 19:56:27)
[GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license"
for more information.
>>>
and allow you to enter Python code next to the signs >>>
line by line. Each line of code will be executed as soon as you press Enter. For example:
print("Hello from the interactive shell")
- Script mode
-
Write Python commands into a text file (e.g., by using nano to create a file
my_program.py
). If you are still in the interactive mode: exit the python console by typingexit()
or the key combinationCtrl-D
(Ctrl
isStrg
on a German keyboard), then open and edit the file in a text editor such as nano.nano my_program.py
Then enter python code into the file.
print("Hello from the python script")
Then, exit nano to get back to the bash shell and pass the name of this file to the
python
command as argument:This makes Python execute the code stored in the file.python my_program.py
Data types and operators
To use Python, please connect to Corso via ssh
; on this virtual machine, all required programs have been installed.
Execute the following statements in Python’s interactive mode. Try to understand the result of each statement. If you encounter any difficulties, please do not hesitate to contact your course instructor.
Numeric types
Numeric types represent numbers.
42 # the integer number forty-two
3.1415 # a decimal number (float) that approximates pi
The hash sign #
starts a comment, so Python will ignore all remaining characters on the line. (Thus, you may omit all comments when you enter the following code snippets into the Python interpreter!).
Numbers may be manipulated via arithmetic operators:
1 + 2 # addition
7 - 4 # subtraction
5 * 6 # multiplication
5 ** 2 # exponentiation ("5 to the power of 2")
54 / 7 # division
10 % 4 # modulo – returns remainder
The assignment operator assigns a name to a value:
= 343
a = 14 b
Now, the name (also called variable) may be used instead of the value in any statement:
a+ b a
Variable names may comprise an arbitrary number of letters, digits, and underscores. However, a name must not start with a digit, and certain keywords (e.g., if
and for
) are disallowed as names.
= 1 # ok
x = 1 # ok
first_value = 1 # ok
number5 2much = 1 # syntax error – name starts with a digit
for = 1 # syntax error – for is a keyword
Let’s calculate the circumference and area of a circle with radius 5:
# do the math
= 3.1415792
pi = 5
radius = 2 * radius * pi
circumference = (radius ** 2) * pi
area
# print results
circumference area
We added explicit parentheses around radius ** 2
to indicate that Python should first calculate the power and then the product. (Actually, we could have omitted these parentheses, since the precedence of exponentiation is higher than the one of multiplication.) However, parentheses are required if the default operator precedence should be changed.
3 * 5 + 8 # equivalent to (3 * 5) + 8
3 * (5 + 8)
When in doubt, always use parentheses to structure your calculations!
Moreover, never distract from the actual order of calculations by using spaces like
3 * 5+8 # might imply that 5 and 8 are added first
Boolean type
There are only two Boolean values: True
and False
. Boolean types typically arise when using comparison operators:
3 > 2 # greater than
7 < 4 # less than
10 >= 8 # greater than or equal
2 <= 2 # less than or equal
5 == 5 # equality
10 != 9 # inequality
Logical operators connect Boolean values to obtain new Booleans.
2 < 3) and (15 / 4 > 1) # conjunction, true if both operands are true
(5 != 5) or (12 >= 13) # disjunction, true if at least one operand is true
(not (5 < 7) # negation changes true to false and vice versa
Text type
A string is a sequence of Unicode characters enclosed in single or double quotes.
= "a string"
str_a = 'also a string'
str_b = "a string with 'single' quotes" str_c
You may also use multiline strings, which must be enclosed in triple quotes.
'''a
multi-
line
string'''
String concatenation is done via the +
operator:
+ str_b str_a
Since strings are sequences of characters, you can access a single character within a string by indexing.
= "adenylyl cyclase"
enzyme 0] # first character
enzyme[3] # fourth character
enzyme[-2] # second character counting from the end of the string enzyme[
Python uses zero-based indexing, i.e., the first element has index 0
.
Slicing extracts a substring, i.e., several characters from a string:
2:8] # substring from the character at index 2
enzyme[# (i.e., the 3rd character from the left)
# to the character before (!) index 8
# (i.e., the 8th character from the left)
When using the slicing syntax [start index : end index]
, the character at the start index is included, while the character at the end index is excluded (!).
Both start index and end index are optional:
4] # substring up to index 3 (remember: the character
enzyme[:# at the end index is NOT included!)
9:] # substring starting at index 9
enzyme[# a copy of the whole string
enzyme[:] -3:] # substring starting at index 3 counting from the right enzyme[
None
type
Python also knows a None
type, which explicitly denotes the “nothing”:
= None
nothing nothing
The is
operator checks whether a variable is None
(do not use a comparison operator in this case):
is None # preferred
nothing == None # avoid nothing
Input and output
Use the print()
function to display output on the screen.
print("Hello world!")
print(3 + 5)
By contrast, the input()
function reads values supplied by the user:
= input("Please enter any value: ")
value value
After calling input()
, Python reads an arbitrary number of characters until the user presses Enter.
Note that input()
always reads a string. Thus, the following program will not work as expected:
= input("Please enter a number: ")
number print(number + 10) # a string cannot be added to an integer!
If we plan to use the entered value for calculations, we must convert it to a numeric type via int()
or float()
:
= "10" # x contains the string "10"
x = int(x) # convert the string "10" to an integer 10
y * 2 # this works as expected
y
= float("2.3") # a is now the float 2.3
a / 5.6 # this works as expected a
Note, however, that you can apparently “multiply” a string with an integer. In this case, Python returns a new string that contains the original string n times (where n is the value of the integer).
* 2 # what happens here?!
x "abc" * 3 # another example
The following program asks the user to enter two numbers and then calculates their product. Store these statements in the file product.py
and execute this file with Python (python product.py
)!
print("Calculate the product of two numbers")
= input("First number: ")
a = float(a)
a
= input("Second number: ")
b = float(b)
b
print("The result is", a * b)
Command line arguments
A Python program may also process values supplied on the command line (similar to a shell command). To enable this functionality, we have to import the sys
module (unit 2 explains modules in more detail). We create a Python script arguments.py
containing the following lines:
from sys import argv
print(argv)
print(argv[0])
print(argv[1:])
We then execute the script as follows:
python arguments.py a 12 third_argument
The program prints three lines that tell us:
argv
is a list with four elements. (The list type will be treated in unit 2. For now, you only need to know that you may access the elements of a list like characters in a string: Variable name followed by the index in brackets.)- The first element
argv[0]
contains the name of the script that was called ('arguments.py'
). - The remaining elements
argv[1:]
contain the command line arguments in the given order.
By using command line arguments, we may calculate the product of two numbers as shown below:
from sys import argv
= float(argv[1])
a = float(argv[2])
b print("The result is", a * b)
Store these statements in product2.py
and execute the program:
python product2.py 35 10
Exercises
Each unit concludes with several exercises which you should solve on your own. Your solutions will be graded, and the scores will be used to obtain your final grade for the course. The maximum number of points for the correct solution of each exercise is indicated.
Store all files that you generate for unit 1 in the folder python1
in your home directory.
Exercise 1.1 (3 P)
You have successfully solved this exercise as soon as you have worked through this unit. In particular, the folder python1
must contain the following files, which you have created in the course of this unit:
product.py
arguments.py
product2.py
Exercise 1.2 (2 P)
Write a Python program that executes the following statements consecutively. Store the program in exercise_1_2.py
.
- Store the integer 32 in the variable
z
and the float 2.5 in the variablea
. - Store the product of
z
anda
in the variableb
. - Divide
a
by 8 and store the result ina
. - Print whether
a
is greater thanb
(here, the program should print a single Boolean value.) - Print whether the sum of
z
and 11 is unequal to 44 (again, only print a single Boolean value).
See section Data types and operators.
Exercise 1.3 (2 P)
Write a program exercise_1_3.py
that prompts the user to enter three numbers and then displays whether the division of the first number by the second number yields a remainder that is equal to the third number.
An exemplary run of the program may yield the following output:
$ python exercise_1_3.py
dividend: 10
divisor: 4
remainder: 2 True
The user entered the three values 10, 4, and 2; subsequently, the program printed True
.
A different run of the program may look like
$ python exercise_1_3.py
dividend: 835
divisor: 111
remainder: 20 False
It does not matter whether your program prints anything in the input lines (such as “dividend:” above). However, it is important that the last printed line contains a single Boolean value that has been calculated correctly.
See this example.
Exercise 1.4 (3 P)
Write a program exercise_1_4.py
that reads four command line arguments. (Below, these arguments are called dna
, x
, a
, e
.). The first argument is a string of arbitrary length which represents a DNA sequence. Arguments 2 to 4 are integers. The program should print two lines:
- The first line contains the
x
-th base from the left indna
. - The second line contains the subsequence of
dna
that starts two bases before the position given bya
and ends at the position given bye
.
Bases are numbered starting from one (thus, the first base in the sequence is actually numbered “1”).
You may check that your program works correctly by using the following exemplary calls:
x a e
↓ ↓ ↓
$ python exercise_1_4.py AGCTATAGTAATCCAAT 2 5 9
G
CTATAGT
a x e
↓ ↓ ↓
$ python exercise_1_4.py ATCTACGCGATATCGCGATAGCCGATGCTGACGACTGACTTGACG 13 7 20
T ACGCGATATCGCGATA
See this example and the section on string indexing and slicing.