





























































Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!






























































Notice that in the "text" cells I will use a language call Markdown, that is only needed to write text and it should not be confused with Python. You may not care about how the "text" cells are formatted, but what you should learn is the theory explained in the "text" cells and how to write code of the "code" cells.
Python was initially designed in 1991. It is a widely-used, high-level programming language. It has become more and more popular because of its easy code readability and because it allows programmers to express concepts (even di cult ones) in only a few lines of code.
The goal of this course is to teach you to think like a computer scientist. One of the most important skill for a computer scientist is problem solving. It means the ability to create a solution to a problem and formulate it clearly and accurately In order to do this, we will study the basic notions of programming by using the language Python.
A program is a sequence of instructions that speci es how to perform a computation. This is similar to the steps we have to follow when we want to cook a speci c recipe. The computation might be something mathematical, such as solving an equation; but it can also be a symbolic computation, such as searching and replacing text in a document, or something graphical, such as plotting a speci c graph, etc. The details of the program look different in different languages (depending on the syntax), but every language has some features in common: inputs : data you may get from a le, online, or you may insert yourself; outputs : the results that the program returns; maths : performing mathematical computations;
conditions : checking that certain conditions hold (by using conditional statements such as the if statement) repetitions : performing some actions repeatedly (by using loops, such as for and while loops) Whichever language you may use (Python in our case), programming can be described as the process of breaking a large, complex task into smaller and smaller sub-tasks until each sub-task is simple enough to be performed with a combination of the basic instructions above.
Traditionally, the rst program is made by a simple statement which displays "Hello, world!" on the screen. print('Hello, world!') Hello, world! This is an example of a program made by a simple print statement (we will talk about statements in a bit), which uses the built-in function print (we will talk about functions later on).
Python provides operators which are special symbols that represent computations, such as addition and multiplication. The operators + , - , * and / perform, respectively, addition, subtraction, multiplication and division. For example: 1 + 1 2 2 - 1 1 2 * 2 4
What about values like ' 2 ' or ' 3. 0 '? They look like numbers, but they are in quotation marks like strings. type('2') str type('3.0') str When we type a large number, we might be tempted to use commas between groups of digits, as in 1,000,000. This is not a "legal" integer in Python, but it represents another structure (called tuple) which we will study later on 1 , 000 , 000 (1, 0, 0) If you want to type in the number one million, you should just type it without commas: 1000000 1000000
Natural languages are the languages people speak, such as English, Italian, French, etc. They evolve naturally. Formal languages are languages that are designed by people for speci c applications. For example, the language used in mathematics for relations, such as "a > b". Programming languages, such as Python, are formal languages that have been designed to express computations. Formal languages tend to have a strict syntax rules that govern the structure of the statements. Syntax is the arrengement of words and phrases to create well-formed sentences/code in a speci c language.
For example, the syntax of Python to ask the type of the number 2 is type( 2 ). On the other hand, semantics is the meaning of a sentence/line of code. For example, the semantics of type( 2 ) is asking the interpreter what is the type of number 2. Some main differences between natural languages and formal languages are as follows. Natural languages are full of ambiguity, which people may create with metaphors and deal with by using contextual clues. Formal languages, instead, are designed to be nearly or completely unambiguous. In order to make up for ambiguity and reduce misunderstanding, natural languages employ lots of redundancy. Formal languages, instead, are less redundant and more concise. Formal languages mean exactly what they state. ψ
Even though the previous syntax is correct, always try to use meaningful names for your variables. Variable names can be as long as you like (but try to keep it short!). They can contain both letters and numbers, but they cannot begin with a number. File "", line 1 2names = 'Alice and Bob' ^ SyntaxError: invalid decimal literal 2 names = 'Alice and Bob' names2 = 'Alice and Bob' two_names = 'Alice and Bob' print(two_names) Alice and Bob For variable names, you can use uppercase letters, but it is conventional to use only lowercase letters. Moreover, Python is a case-sensitive language, which means that two variable names that differ only for one upper/lower- case character represent two different variables. For example: Message = 'Uppercase' print(Message) Uppercase print(message) We are creating an assignment statement As we have already seen, the underscore character _ can appear in a variable name and it is often used in names with multiple words. Let's try some "illegal" names in Python and notice that error messages are displayed. File "", line 1 n@me = 'John' ^ SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? n@me = 'John' class = 'Computer Science for Economics'
File "", line 1 class = 'Computer Science for Economics' ^ SyntaxError: invalid syntax n@me is not permitted as variable name because it contains the "illegal" character @. What is wrong with class? It turns out that class is one of the Python's keywords. The interpreter uses keywords to recognise the structure of the program and so those cannot be used as variable names. Python's keywords are: 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 You do not have to memorise this list. Try not to use any of those as variable names, but if it happens then an error message will be displayed and will simply have to change the variable name.
An expression is a combination of values, variables and operators. A value by itself is considered an expression and so is a variable. For example, the following three are expressions: n 18 48 48 n + 25 43 When you type in an expression and run the code, the interpreter evaluates it, which means that it nds the value of that expression. In the last example, n had the value 18 and thus the expression n + 25 has the value 43. A statement is a piece of code that has an effect, such as creating a variable or displaying a value. For example:
There are two operations that are allowed on strings. The + operator performs string concatenation , which means it merges strings together. For example: ' basketball' first = 'basket' second = 'ball' first + second ' John Smith' name = 'John' surname = ' Smith' name + surname The * operator also works on strings and it performs string repetition. For example: ' Ciao! Ciao! Ciao!' 'Ciao! '* 3 Some properties of the operators + and * for strings are the same as addition and multiplication for numbers. For example: ' Ciao! Ciao! Ciao!' 'Ciao! ' + 'Ciao! ' + 'Ciao! ' On the other hand, they have some differences. For example, the commutative property does not hold for string concatenation. 1 + 2 + 3 6 1 + 3 + 2 6 ' abc' 'a'+'b'+'c' ' acb' 'a'+'c'+'b' However, string concatenation does satisfy the associative property. Try it!
As programs become longer and more complicated, they are more di cult to read. For this reason, it is a good idea to add notesto your code to explain in natural language what the program is doing These notes are called comments and they start (in the code) with the symbol #. Comments are very important for code readability.
hours = 24 minutes = hours* 60 # number of minutes in one day print(minutes) 1440 Comments are most useful when they describe non-obvious features of the code. a = 5 # assign 5 to a The previous comment is redundant, as we understand we are assigning 5 to the variable a already from the code. gamma = 0.577 # approximate Euler's constant The last comment is instead more useful, as many people would not know about Euler's constant. Good variable names can reduce the need for comments, but long names can make complex expressions hard to read. So there is always a trade-off: try to use meaningful names that are not too long. If needed, you can add comments.
ValueError Traceback (most recent call last) in () ----> 1 int('Hello!') ValueError: invalid literal for int() with base 10: 'Hello!' This means that the function int cannot convert the string 'Hello!' into an integer. The function int can convert oating-point values to integers, but it does not round off; it only chops off the fraction part: int(2.99) 2 In order to round off, we should use the built-in function round. round(2.99) 3 Similarly, the function float converts integers and strings to oating-point numbers, if it can. Finally, the function str converts its argument to a string: ' 7 ' str( 7 )
A module is a le that contains a collection of built-in functions. The math module in Python provides most of the familiar mathematical functions. Before we can use the functions within a module, we have to import the module with an import statement. import math
This statement imports a module named math. If you type in the module name, you can obtain some information about it: math
The module contains functions and variables de ned therein. To access one of those functions, you have to specify the name of the module and the name of the function, separated by a dot (also known as period). This format is called dot notation. x = 10 ** 2 math.log10(x) # we compute the logarithm base 10 of x
This example uses the function log 10 , which is part of the module math , to compute the logarithm base 10 of a number. The math module also provides the functions exp and log which compute the exponential e and the natural logarithm, respectively. x = math.exp( 3 ) # assign e^3 to x exponent = math.log(x) # assign the natural logarithm of x to exponent print(exponent)
Another known function is math.sqrt() , which computes the square root of a number. y = 5 ** 2 math.sqrt(y)
So far we have mostly looked at elements of a program - variables, expressions and statements - separated from each other, without discussing how to combine them. One of the most useful features of programming languages is their ability to take small building blocks and compose them. For example, the argument of a function can be any kind of
The empty parentheses after the name indicate that this function does not take any argument. We will talk about arguments of a function in a bit. The rst line of function de nition is called header , the rest is called body. The header has to end with a colon and the body has to be indented. After the colon of the function header, you will have noticed theat the body is automatically indented. You should erase indentation when you want to end a function. The body can contain any number of statements. The syntax for calling a new function is the same as for built-in functions. print_hello() # we are calling the new function Hello world! We are creating a new function! The de nition of a new function creates a function object , which has type function : type(print_hello) function Once you have de ned a function, you can use it inside another new function. For example: def repeat_hello(): # here we define the function repeat_hello print_hello() print_hello() repeat_hello() # here we call the function repeat_hello Hello world! We are creating a new function! Hello world! We are creating a new function!
Function de nitions are executed just like other statements, but the effect is to create function objects. The statements inside a function do not run (that is, are not executed) until the function is called. Moreover, the function de nition generates no output.
Merging the code fragments from the previous section, the whole program would look like: def print_hello(): # first function print('Hello, world!') print('We are creating a new function!') def repeat_hello(): # second function print_hello() print_hello() repeat_hello() # main program, only one statement in this case Hello, world! We are creating a new function! Hello, world! We are creating a new function! This short program contains two function de nitions, whose names are print_hello and repeat_hello. The last statement calls the function repeat_hello , which itself (in its body) calls twice the function print_hello. Therefore, the outcome of the program is the execution of the body of the function print_hello twice. The ow of the program goes as follows: (1) the statement repeat_hello() calls the function repeat_hello ; (2) we are inside the body of the function repeat_hello and we see that its rst statement calls the function print_hello ; (3) we then jump inside the body of the function print_hello and we execute its statements, which print the two sentences; this is the rst part of the output! (4) We are back to the body of the function repeat_hello and, after having executed the rst statement, we execute the second statement, which does the same; (5) therefore, we are back to the body of the function print_hello and again we execute its statements by printing the two sentences; this is the second part of the output! (6) we are back to the body of the function repeat_hello and we realise that it is completed, since we have executed its two statements; (7) nally, we are back to the main program which ends because it was only made of the statement repeat_hello().
up where it left off at the point the function was called. When it reaches the end of the program, it terminates. In summary, when you read a program, you do not always want to read from the top to the bottom. In general it makes more sense to follow the ow of execution. That is what we described in the previous section with indented paragraphs. Also, when you write a program, try to avoid long cycles of function calls because they might generate errors and the program will become more di cult to read.
Some of the functions we have seen require arguments. For instance, when we call math.exp we pass a number as an argument. Some functions take more than one argument: math.pow takes two arguments, the base and the exponent: import math math.pow( 2 , 3 )
Inside the function, the arguments are assigned to variables called parameters. For example: def print_twice(par): print(par) print(par) This function assigns the argument to a parameter called par. When the function is called, it prints the value of the parameter (whatever it is) twice. print_twice('Hello!') Hello! Hello! When executing the last statement, rst the argument 'Hello!' (a string) was assigned to the parameter par. Then, the interpreter executed the statements in the body of the function print_twice , which displayed the value of par (that is, 'Hello!' in this case) twice. print_twice( 14 )
14 14 The same rules of composition that apply to built-in functions also apply to programmer-de ned functions. So, we can use any kind of expression as an argument for print_twice. For example: print_twice('Hello! '* 3 ) Hello! Hello! Hello! Hello! Hello! Hello! The argument 'Hello! '* 3 is evaluated rst, to obtain the string 'Hello! Hello! Hello! ' , and passed as an argument to the parameter par. As a consequence, this function call prints 'Hello! Hello! Hello! ' twice. print_twice(math.log(math.exp( 2 )))
The argument math.log(math.exp( 2 )) is evaluated rst, to obtain 2, and passed as an argument to the parameter par. As a consequence, this function call prints 2 twice. You can also use a variable as an argument: sentence = 'The sky is blue' print_twice(sentence) The sky is blue The sky is blue The string 'The sky is blue' is assigned to the variable sentence. Then, when the function print_twice is called, the variable sentence is passed as an argument and assigned to the parameter par. As a consequence, the string 'The sky is blue' is printed twice. The functions we have presented up to now perform an action but do not return a value. They are called void functions. Functions can also produce return values , which can be very useful, and we will see how to do this in a few chapters.