Contents

## 1. Bibliography

### 1.1. In English

Pagina (oficială) de pornire used for documentation; the main topics are:

The Python Tutorial -- a perfect starting point for those that want to start programming in Python: it covers the basis of Python programming;

Using Python -- it describes the installation and usage of the Python interpreter in the context of main operating systems;

The Python Language Reference -- a good cover material for the Python language (syntax and basic entities);

The Python Standard Library -- the cover material for all standard Python libraries (practically all that there is to know about Python);

### 1.2. În Romanian

Tutorial Python -- the translation in Romanian of The Python Tutorial, but for the older version 2.4.1.

## 2. Introduction

What is python? ::

First of all an

**programming language**, but also an**execution environment**(**run-time environment**);

What does the term *language* mean in the context of computers? ::

- A method in which the user (not necessarily a programmer) interacts with an application.
In general we are thinking at a text with a well defined format that is

*understood*by the application.

What does *programming* imply?

- It referrers to the possibility of prescribing a sequence of actions that an application must undertake.
In general the

*programming*has two flavors:*temporary*(after the application restarts the sequence of actions is lost);or

*permanent*;

*Programming language*?

- The way in which the actions are prescribed for a certain application (or for the computer itself).
The text that results is usually called

*source code*, or simpler said*program*.

*Program execution*?

The application uses the

*source code*(described according to the rules in the*programming language*) and undertakes the actions prescribed.

What is an *shell*?

- The way in which some applications obtain the source code can differ. But the majority falls in one of the two use cases:
either the

*source code*is provided as a computer file;- either the interaction with the user takes the form of a dialogue.

The applications that fall in the last category are generically called

*shells*. (Python fits both categories.)

## 3. Dialoguing with Python

### 3.1. Starting the shell

Both under Windows and under Linux we could use IDLE (*An Integrated DeveLopment Environment for Python*). This is accessible from the menus of both operating systems.

(Furthermore under Linux we could use also the built-in Python shell `python`, or `ipython`.)

Once started, Python informs us about the current version, and displays a *prompt* (a sequence of characters that indicates to the user that the application waits for commands):

#Python 2.6 ... >>>

### 3.2. "Pocket calculator"

Although we have in our hands a very complex and powerful application, we can "downgrade" it and use it as a simple pocket calculator.

But before continuing we must be aware of a few issues:

in the case we copy/paste the examples that follow in this text, we must remember that the user does not have to input the characters

*>>>*, but only what follows after it.in general every

*shell*while dialoguing with the user behaves in the following manner:the

*shell*displays a prompt (in the case of Python this is*>>>*);the user inputs the text (conforming to the rules of the language understood by the application), followed by the

*Enter*key;the

*shell*tries to parse the code (accordingly with the language), and in the case it understands what it has to do, it undertakes the action;and as a consequence of the execution of the requested actions, the

*shell*displays the outcome of the operation; (this is not always the case;)

Simple operations:

>>> 1 + 2 3 >>> 2 * 3 + 4 10 >>> 2 ** 3 8

Prioritized operations:

>>> (1 + 2) * 3 9

Operations with complex numbers:

>>> 3j ** 2 (-9+0j) >>> (2 + 3j) ** 2 (-5+12j)

### 3.3. Numeric data types

integers:

`1`,`259`,`-874`;- reals:
in decimal format:

`0.0`,`-895.059`;in scientific format:

`1.7e+5`,`-59.7e-80`;

- complex:
with only an imaginary part:

`7j`,`-9.8884j`,`5.9e200j)`;with only a real part:

`(3+0j)`,`(-2.75+0j`;both real and imaginary parts:

`(15+20j)`;

### 3.4. Arithmetic operators

`+`,`-`-- addition, subtraction;`*`-- multiplication;`/`-- division, but:if we divide two integer numbers then the result represents only the integer part:

`3 / 2 => 1`,`1 / 2 => 0`;in any other case the division is an exact one:

`3 / 2.0 => 0.5`,`1.0 / 2 => 0.5`;

`%`-- the reminder of the division, but:we could use it even for real numbers:

`0.7 % 0.3 => 0.09999...`

`**`-- power raising;

### 3.5. Arithmetic functions

`abs`-- absolute value:>>> abs(5) 5 >>> abs(-1) 1 >>> abs(-9.72) 9.72 >>> abs(1+3j) 3.162

`min`,`max`:>>> min(5,9) 5 >>> max(5,9) 9

`round`-- rounding:>>> round(5.6) 6 >>> round(5.5) 6 >>> round(5.1) 5 >>> round(-1.5) 2

`int`-- real to integer conversion (by truncation):>>> int(5.5) 5 >>> int(-1.5) -1

### 3.6. Variables

In contrast to other programming languages, in Python there is no need of declaring variables, instead these are automatically defined in the moment of assignment.

>>> pi = 3.14 >>> radius = 7 >>> perimeter = 2 * pi * radius >>> perimeter 43.96 >>> surface = pi * radius ** 2 >>> surface 153.86

### 3.7. Other mathematical functions

There are some useful functions that are held in the mathematical module (see the documentation for a complete list).

Importing the functions:

# if we need the sqrt function from math import sqrt # or if we need the trigonometric functions from math import sin, cos, tan

Using the functions:

r = sqrt (90)

## 4. Programming in Python

### 4.1. Source code editing

For IDLE: `File` -> `New Window` (`Control-N`) or `File` -> `Open...` (`Control-O`).

For Linux in the command line: `nano <path-of-file>`.

(The extension for Python files is `.py`.)

### 4.2. Source code execution

For IDLE: `Run` -> `Run Module` (`F5`.

For Linux in the command line: `python <path-of-file>`.

### 4.3. Comments

Generic syntax:

z = x + y # afther the # character follows a comment until the end of the line # w = x * y -- this entire line is a comment, and the w variable is not initialized

## 5. Outputting to the console

Generic syntax:

print print value_1, value_2, ..., value_n

Examples:

>>> x = 1 >>> print "a =", x a = 1 >>> print "a =", "x" a = x >>> print >>> print 5 5

## 6. Control structures

### 6.1. Conditional structure

Also in contrast to other programming languages, in Python correct (consistent) indentation (the spaces at the beginning of lines) is obligatory. It is recommended to use 4 spaces for each indentation level, or a single *tab* character. However it is not recommended to mix the two styles.

Generic syntax:

if condition : operation ... else : operation ...

The syntax without the *else* clause:

if condition : operation ...

The syntax for multiple conditions:

if condition_1 : operation ... elif condition_2 : operation ... ... else : operation ...

#### 6.1.1. Examples

Testing if a number is even:

x = 5 if x % 2 == 0 : print "even" else : print "odd"

Simulating the absolute function `abs`:

x = -5 if x < 0 : x = 0 - x print x

### 6.2. Iterative structure

Iteration over an interval:

for i in range(min, max + 1) : operation ...

Iteration over an interval with a step:

for i in range(min, max + 1, step) : operation ...

Iteration over a list:

for i in [element_1, element_2, ..., element_n] : operation ...

#### 6.2.1. Examples

The sum of numbers from 1 to 100 :

sum = 0 for i in range(1, 101) : sum = sum + 1 print sum

Displaying the members of a list:

lst = ["a", "b", "c"] for e in lst : print e

### 6.3. Repetitive structure

Generic syntax:

while condition : operation ...

#### 6.3.1. Examples

The sum of the numbers from 1 to 100 :

sum = 0 i = 1 while i <= 100 : sum = sum + i i = i + 1 print sum

## 7. Lists

Creating lists:

# creating a list with some elements l = [1, 2, 3] print l # creating a list of a certain size initialized with a certain value l = [0] * 10 print l # we should see: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print len(l) # we should see: 10, the length of the list

Inputing lists:

l=input("l=") # and enter [1,2,3] print l

Accessing and updating elements:

l = [1, 2, 3] print l[0] print l[1] print l[2] l[1] = 3 l[2] = 2 print l # we should see [1, 3, 2]

Adding an element at the end of a list:

l = [] l.append (1) l.append (2) print l # we should see [1, 2]

Reversing the content of a list:

l = [1, 2, 3] l.reverse () print l # we should see [3, 2, 1]

## 8. Functions

Generic syntax:

def name (argument_1, argument_2, ...) : operation ... return value

Example (returning a list of digits of a number):

def digits (n) : dl = [] while n > 0 : d = n % 10 n = n / 10 dl.append (d) dl.reverse () return dl print digits (1234) # we should see [1, 2, 3, 4]

## 9. Problems

### 9.1. Coversions

- Write a program that converts an angle from radians to degrees.
- Write a program that converts an angle expressed in degrees in decimal form, into the following components: degrees (integer value), minutes, seconds, tens and hundreds of seconds.

### 9.2. Conditional structures

- A point in 2D space is given by its coordinate x and y. Write a program that determines if the point is in the axis origin, or in the quadrants numbered from 1 to 4 (in reverse clock order), or if the point is on the border of the quadrants.
- Considering a sphere expressed as its center coordinate and its radius, and given an arbitrary point in space, it should be determined its relative position to the sphere (i.e. inside, outside or on the surface).
- Write a program that determines the ideal body weight of a person, given the waist, age an gender. The formula are:
- Given the current date expressed as three integer numbers (year, month, and day), compute how many hours have elapsed since the beginning of the year, and how many hours are left until the end of the year. (We can consider that February has only 28 days.)
- Given the current date expressed as three integer numbers (year, month, and day), and a persons birth-date expressed the same way, write a program that computes the age of the person, expressed as a number real number. (We consider that February has 28.25 days.)

### 9.3. Iterative structures

- Write a program that determines the greatest common divisor of two natural non-negative numbers, using only subtraction.
- Write a program that determines the greatest common divisor of two natural non-negative numbers, using Euclid's algorithm.
- Write a program that determines the value of x raised to power n.
- Write a program that determines if a number is prime.
- Write a program that determines the sum of the digits for a number.
- Write a program that determines the first n terms of the Fibonacci sequence.
- Write a program that determines all the numbers smaller than n and are co-prime.
Considering the following natural number sequence: , determine the percentage of the values for n in a given interval (from a to b), so that the value is prime.

- Write a program that determines all the perfect natural numbers that don't exceed a given value n.
Write a program that determines all the sequences of successive odd numbers, whose sum is n raised to the power 3. Ex. .

- Write a program that decomposes a given number n into its prime factors.
- Write a program that determines the decomposition of a natural even number, greater than 2, as a sum of two prime numbers.

### 9.4. Economic problems

- Considering the evolution of a bank deposit that is reconstituted each month, write a program that takes as inputs the initial deposited sum, the annual interest, and the number of months, and computes the final value of the deposit.
- In the context of the previous problem, and by taking into consideration also the annual inflation (that we consider a constant given as an input), and applying this inflation at the end of each 12 months, compute the net value at the end of the period.