Adapted by the original online tutorial.
The material will give you an idea of the Python programming language.
Python is an interpreted language.
It is available in all major platforms and runs anywhere from High Performance Computers (HPCs) to embedded devices.
It is a very popular choice for scientific computing and big data processing.
It is completely open source.
The standard Python distribution is available at http://www.python.org.
Be sure to select the latest Python 3 version.
To get a first taste of Python, we will be using it interactively.
Start the IDLE program on your machine.
In the program's main console you can see a prompt:
>>>
This is where you enter Python commands.
When you press Enter, the Python interpreter takes your input and executes it, then waits for new input.
The interpreter acts as a simple calculator.
You can type an expression at it and it will write the value.
Expression syntax is straightforward: the operators +
, -
, *
and /
work just like in most other languages (for example, Pascal or C); parentheses (()
) can be used for grouping.
2 + 2
50 - 5*6
8 / 5
The integer numbers (e.g. 2, 4, 20) have type int
.
Τhe ones with a fractional part (e.g. 5.0, 1.6) have type float
.
As we saw, division (/
) always returns a float.
To do floor division and get an integer result (discarding any fractional result) you can use the //
operator.
To calculate the remainder you can use %
.
17 / 3
17 // 3
17 % 3
5 * 3 + 2
The arithmetic operators have the following precedence:
*
, /
, %
: highest+
, -
: lowestTo alter the default calculation order we can use parentheses.
2 * 3 + 4
2 * (3 + 4)
((1 + 2) * 3) * ((3 + 4) * 5)
**
operator.5 ** 2
2 ** 7
**
has higher precedence than unary minus (-
), so:-3 ** 2
(-3)**2
A variable in programming is a name that refers to a value.
The =
operator is used to assign a value to a variable.
In Python you do not need to declare the type of the variable.
You cannot use a variable before you assign a value to it.
The name of a variable can be as long as we like, cannot begin with a number, and cannot container spaces (we use _
instead).
width = 20
height = 5 * 9
width * height
n # try to access an undefined variable
----> 1 n # try to access an undefined variable
NameError: name 'n' is not defined
The following names cannot be used for variables, as they are reserved by Python.
They are called keywords.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
radius = 10
area = 3.14 * radius**2
print("The area of circle with radius", radius, "is", area)
radius = 20
area = 3.14 * radius**2
print("The area of circle with radius", radius, "is", area)
a = 10
b = 20
print("a = ", a, "b = ", b)
b = a
a = b
print("a = ", b, "b = ", b)
a = 10
b = 20
print("a = ", a, "b = ", b)
t = a
a = b
b = t
print("a = ", a, "b = ", b)
This is the standard procedure in most programming languages.
It also works, as you have just seen, in Python.
However, in Python we can also do more simply the following.
a = 10
b = 20
print("a = ", a, "b = ", b)
b, a = a, b
print("a = ", a, "b = ", b)
In Python, as in most programming languages, different kinds of numbers are represented by different types.
In general, different kinds of things are represented by different types, as will will see.
The two basic numeric types are integers and floating point.
There is full support for floating point.
Operators with mixed type operands convert the integer operand to floating point.
3 * 3.75 / 1.5
7.0 / 2
In contrast to other languages, there is no limit on the size of an integer.
An integer will be calculated, as long as it fits in the memory available to Python.
2 ** 8192
Python has numeric types for fractions (Fraction
) and for decimal numbers (Decimal
).
The Decimal
type is used for money, or any case where we need to calculate with exact decimal precision.
Python also supports complex numbers. The suffix j
or J
is used for the imaginary part: 3 + 4j
.
Of course, we can use Python for more complicated tasks than adding two and two together.
For instance, we can write an initial sub-sequence of the Fibonacci series as shown below.
If you have not seen it before, the Fibonacci series is a series of numbers starting with 0 and 1, where every number is the sum of the previous two numbers.
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
The first line contains a multiple assignment.
The variables a and b simultaneously get the new values 0 and 1.
On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place.
The right-hand side expressions are evaluated from the left to the right.
The while
loop executes as long as the condition (here: b < 10
) remains true.
In Python, like in many programming languages, any non-zero integer value is true; zero is false.
The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false.
The test used in the example is a simple comparison.
The standard comparison operators are written the same as in most other programming languages: <
(less than), >
(greater than), ==
(equal to), <=
(less than or equal to), >=
(greater than or equal to) and !=
(not equal to).
Note the expression a, b = b, a+b
.
The two assignments are executed at the same time.
We have seen that before: to swap two variables in python you only need x, y = y, x
and not a temporary variable like in many other languages.
Unlike most other languages, whitespace and indentation is important in Python.
The body of the loop is indented: indentation is Python’s way of grouping statements.
At the interactive prompt, you have to type a tab or space(s) for each indented line.
In practice you will prepare more complicated input for Python with a text editor.
All decent text editors have an auto-indent facility.
When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line).
Note that each line within a basic block must be indented by the same amount, otherwise you will get an error, or you will indicate an inner block.
The print()
function writes the value of the argument(s) it is given.
It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings.
Strings are printed without quotes, and a space is inserted between items, so you can format things nicely.
i = 256*256
print('The value of i is', i)
a, b = 0, 1
while b < 1000:
print(b, end=',')
a, b = b, a+b
However, most uses of Python involve writing Python programs, scripts, saved in files.
A Python file has by convention the extension .py
, for example, foo.py
.
To run such a program we enter python foo.py
or python3 foo.py
(depending on the details of our installation).
We must ensure that python
or python3
is in the system's path.
When foo.py
is run we'll see that a file foo.pyc
is generated. That is a compiled file that does not contain executable machine code but some intermediate level code.
A perfect number is a number that is the sum of all its divisors, except for itself.
We do not currently know whether there are infinitely many perfect numbers.
Perfect numbers appear as early as as early Euclid's Elements (VII.22).
for test_number in range(1, 10000):
sum = 0
for i in range(1, test_number):
if test_number % i == 0:
sum += i
if sum == test_number:
print(test_number, "is a perfect number")
The range(1, 10000)
function produces the values 1, 2, ..., 9999.
In general, range(a, b)
produces the values a, a + 1, ..., b - 1.
The simplified range(a)
produces the values 0, 1, 2, ...., a - 1.
The if
statement is a conditional statement.
If the condition that follows is true, the indented code below it will be executed.
Note also the sum += i
expression.
This is a shortcut for sum = sum + 1
.
In general, for an operator op
, the expression x op= y
means x = x op y
.
i = 1
while i <= 10:
if i % 2 == 0:
print(i, "check")
elif i % 3 == 0:
print(i, "check")
else:
print(i, "is not a multiple of 2 nor 3")
i += 1
This time we use the if .. elif ... else
construct.
The elif
branch is executed if the condition of the if
is not true, but the condition following it is true.
The else
branch is executed when all other conditions are false.
Note that both elif
and else
are optional:
if
without else
and elif
if
with elif
but without else
if
with else
but without elif
We mentioned before that Python offers the Decimal
type when we want exact arithmetic calculations.
That is because computer arithmetic is not the same as school arithmetic.
Consider the following.
step = 0.1
total = 0
for i in range(1000):
total += step
print(total)
The range(a)
function produces the function 0, 1, 2, ..., a - 1.
So the above program adds 1000 times 0.1, which would produce $1000 \times 0.1 = 100$.
But in computers, this does not happen.
When we do need to be as accurate as normal arithmetic requires, we use mechanisms such as the Decimal
type to which we referred.
We won't be needing it that now, but just be aware that computer arithmetic is not everyday arithmetic.
To ask for input from the user on the command line, we use the input()
function.
The function then reads a line from input and returns it to the program.
input_name = input("What's your name? ")
print("Hello,", input_name)
What's your name? Panos
Hello, Panos
Note that input()
returns an object that is called a string.
We will have much more to say about strings in a bit.
For now, be aware that a string is not a number, even if it looks like a number.
input_radius = input("Give the circle radius: ")
area = input_radius**2 * 3.13
print(area)
Give the circle radius: 10
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-89-232c7e4563eb> in <module>()
1 input_radius = input("Give the circle radius: ")
----> 2 area = input_radius**2 * 3.13
3 print(area)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
We need to convert the input to a number.
To convert to an integer, we use the int()
function.
To convert to a floating point number, we use the float()
function.
input_radius = input("Give the circle radius (must be integer): ")
area = int(input_radius)**2 * 3.14
print(area)
Give the circle radius (must be integer):10
314.0
input_radius = input("Give the circle radius:")
area = float(input_radius)**2 * 3.14
print(area)
Give the circle radius:12.3
475.0506000000001
In Python everything following the character # is a comment.
A comment is not executed by the computer.
It exists so that humans can understand a program.
They are an essential part of well-written programs: always include them in your programs!
# This is a comment
spam = 1 # and this is the second comment
# ... and now a third!
text = "# This is not a comment because it's inside quotes."
# Calculates the Fibonacci numbers up to 1000
a, b = 0, 1 # First two Fibonacci numbers are 0 and 1, by definition
while b < 1000:
print(b, end=',')
a, b = b, a+b
Write a program that asks the user to provide different numbers of banknotes and coins, from €50 to €1. Then output the total sum in euros. For example:
Enter number of 50 euro banknotes: 10
Enter number of 20 euro banknotes: 20
Enter number of 10 euro banknotes: 30
Enter number of 5 euro banknotes: 40
Enter number of 2 euro coins: 50
Enter number 1 euro coints: 60
You have 1560 euros.
If we want to calculate the area of a triange given its sides, we can use Heron's formula, which is: $$ A= \frac{1}{4}\sqrt{(a+b+c)(-a+b+c)(a-b+c)(a+b-c)} $$ where $a$, $b$, and $c$, are the three sides of the triangle. Write a program that asks the user for the three sides and calculates its area. Note that to calculate the square root in Python you have to include the line
import math
at the beginning of your program. Then, the square root of, say, r
, is math.sqrt(r)
.
A quadratic equation is an equation of the form:
$$ax^2 + bx + c$$
The roots of a quadratic equation are given by the formula:
$$x=\frac{-b\pm {\sqrt {b^{2}-4ac\ }}}{2a}$$
Note that if $b^2 - 4ac < 0$, then no real-valued solutions exist. Write a program that asks the user to enter values for $a$, $b$, $c$, then prints the solutions of the quadratic equation they define, if they exist. If they do not exist, it should output an appropriate message.
Write a program that calculates the first five terms of the harmonic sequence, that is, the numbers: $$1$$ $$1 + \frac{1}{2}$$ $$1 + \frac{1}{2} + \frac{1}{3}$$ $$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4}$$ $$1 + \frac{1}{2} + \frac{1}{3} + \frac{1}{4} + \frac{1}{5}$$
These are the numbers:
1
1.5
1.8333333333333333
2.083333333333333
2.283333333333333
The triangle or triangular numbers are given by the following formula: $$T_{n}=\sum _{k=1}^{n}k=1+2+3+\dotsb +n={\frac {n(n+1)}{2}}$$ So, the first six triangular numbers are: 0, 1, 3, 6, 10, 15, 21. Their name comes from the fact that it is the number of objects that we must use to form an equilateral triangle. Write a program that asks the user the number of triangular numbers to produce, then prints them out:
Enter number of triangle numbers: 9
1 3 6 10 15 21 28 36 45
Enter number of triangle numbers: 15
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120
Enter number of triangle numbers: 30
1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 210 231 253 276 300 325 351 378 406 435 465
The pronic numbers are those that are the product of two consecutive integers, so that they have the form $n(n + 1)$. For example, the first six pronic numbers are: $$ 1 \times 2 = 2$$ $$ 2 \times 3 = 6$$ $$ 3 \times 4 = 12$$ $$ 4 \times 5 = 20$$ $$ 5 \times 6 = 30$$ $$ 6 \times 7 = 42$$
Write a program that asks the user the number of pronic numbers to output, then goes on and prints them:
Enter number of pronic numbers: 10
2 6 12 20 30 42 56 72 90 110
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.