

























Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Riassunto "How To Code in Python" per la preparazione dell'esame di Computational thinking and Programming (mod. 1) del corso DHDK. I capitoli: Intro / HT Write a P3 Program /Und. Data Types /HT Use Variables /Und. Boolean Logic /HT Write Conditional Statements /HT Define Functions /HT Write Comments /HT Import Modules/Und. Lists/HT Use Lists meth/HT Construct While Loops/HT Construct For Loops/Und tuples/Und. Dictionaries/HT Construct Class and define Object (HT = How To / Und = understanding)
Tipologia: Sintesi del corso
1 / 33
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!


























Python is a good general-purpose language that can be used in a variety of applications. Python is a very human-readable programming language, allowing for quick comprehension. It supports multiple styles including scripting and object-oriented programming and for this reason it is considered to be a multi-paradigm language that enables programmers to use the most suitable style to complete a project. The name is inspired by the British comedy group Monty Python. It was an important foundational goal of the Python development team to make the language fun to use. Easy to set up, and written relatively straightforward ( = semplice) style with immediate feedback on errors. It was developed in the late 1980s and first published in 1991 by Guido van Rossum. Some differences between Python 2 and Python 3. In P2 print is treated as a statement instead of a function. In P3 print() is explicitly a function, so to print out a string we can use the syntax of a function.
In P2 any number that you type without decimals is treated as the programming type called integer. In P3 integer division became more intuitive. If we want to do floor division, we should use the syntax of //.
print("Hello, World!") print() is a function that tells the computer to perform an action. It's a function because it uses parentheses. It tells Python to display or output whatever we put in the parentheses. By default, this will output to the current terminal window.
Some functions, like print(), are built-in functions included in Python by default. These built-in functions are always available for us to use in programs that we create. We can also define our own functions that we construct ourselves through other elements. Inside the parentheses is a sequence of characters that is enclosed in quotation marks - > any character that are inside of quotation marks are called a string. [ Once we are done writing our program, we can exit nano by typing the control and x keys, and when prompted to save the file press y. You'll return to your shell] How to run the program: python3 hello.py
how different functions and operations evaluating to either True or False can change the course of the program. STRING A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Strings exist within either single quotes ' or double quotes '' in Python, so to create a string, enclose a sequence of characters in quotes. You can choose to use either single quotes or double quotes, but whichever you decide on you should be consistent within a program. The simple program "Hello, world!" demonstrates how a string can be used in computer programming, as the characters that make up the phrase Hello, Wolrd! are a string. We can store strings in variables. Like numbers, there are many operations that we can perform on strings within our programs in order to manipulate them to achieve the results we are seeking. LIST A list is a mutable, or changeable, ordered sequence of elements. Each element or value that is inside of a list is called an item. Just as strings are defined as characters between quotes, list are defined by having values between square brackets [ ]. A list of integers looks like this: [ - 1, 0, 1, 2 ] List are very flexible data type because they are mutable in that they can have values added, removed, and changed. TUPLE A tuple is used for grouping data. It is an immutable ordered sequence of elements. Tuples are very similar to lists, but they use parentheses ( ) instead of square brackets and because they are immutable their values cannot be modified. A tuple looks like this: ('blue coral', 'pillar coral') Dictionaries The dictionary is Python's built-in mapping type. This means that dictionaries map keys to values and these key-value pairs are a useful way to store data in Python. A dictionary is constructed with curly braces on either side { }. Tipically used to hold data that are related, such as the information contained in an ID, a dictionary looks like this: {'name': 'Sammy', 'animal': 'shark', 'color':'blue'} You will notice that in addition to the curly braces, there are also colons throughout the dictionary. The words to the left of the colons are the keys. Keys can be made up of any immutable data type. The keys in the dictionary above are: 'name', 'animal'. The words to the right of the colons are the values. Values can be comprised of any data type. The values in the dictionary above are: 'Sammy', 'shark'. If we want to isolate Sammy's color, we can do so by calling sammy['color']. As dictionaries offers key-value pairs for storing data, they can be important elements in your Python program.
Variables are an important programming concept to master. They are essentially symbols that stand in for a value you're using in a program. Understanding Variables A variable is assigning a storage location to a value that is tied to a symbolic name or identifier. The variable name is used to reference that stored value within a computer program. It's like a label that as a name on it, which you tie onto a value.
The Boolean data type can be one of two values, either True or False. Booleans represent the truth values that are associated with the logic branch of mathematics, which informs algorithms in computer science. Comparison Operators Comparison operators are used to compare values and evaluate down to a single Boolean value of either True or False. Logical Operators There are three logical operators that are used to compare values. They evaluate expressions down to Boolean values, returning either True or False. Logical operator are typically used to evaluate whether two or more expressions are true or not true. Truth Tables For the comparison operator
For the logic operator AND For the logic operator OR For the logic operator NOT Truth tables are common mathematical tables used in logic, and are useful to memorize or keep in mind when constructing algorithms in computer programming. Using Boolean Operators for Flow Control To control the stream and outcomes of a program in the form of flow control statements, we can use a condition followed by a clause. A condition evaluates down to a Boolean value of True or False, presenting a point where a decision is made in the program. The clause is the block of code that follows the condition and dictates the outcome of the program.
With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time. By using conditional statements, programs can determine whether certain conditions are being met and then be told what to do next. If statement The if statement evaluates whether a statement is true or false, and run code only in the case that the statement is true. grade = 70 Print("Passing grade") if grade >= 65: With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal to 65. If we change the grade value with one that is minor than 65, the output will be different and the print will not work. Else statement It's likely that we will want the program to do something even when an if statement evaluates to false. To do is, we will add an else statement: grade = 60 print("Passing grade") if grade >= 65: print("Falling grade") else: Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will print not the first string, but the second one. Else if statement In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an else if statement, which is written in Python as elif. The elif statement looks like an if statement and will evaluate another condition. The elif statement will be placed between the if statement and the else statement: grade = 60 print("A grade") if grade >= 90: print("B grade") elif grade >= 80: print("C grade") elif grade >= 70: print("D grade") elif grade >= 65: else:
print("Falling grade") else: Since elif statements will evaluate in order, we can keep or statements pretty basic. Nested if statements We can use nested if statements for situations where we want to check for a secondary condition if the first condition executes as true. For this, we can have an if-else statement inside another one. print("True") print("yes") if nested_statement: print("no") else: if statement1: print("false") else:
print( "Username: " + username) print("Followers:" + str(followers)) def profile_info(username, followers=1): We can run the function with only the username function assigned, and the number of followers will automatically default to 1. Returning a Value You can pass a parameters value into a function, and a function can also produce a value. A function can produce a value with the return statement, which will exit a function and optionally pass an expression back to the caller. If you use a return statement with no arguments, the function will return None. In facts, without using the return statement, the program cannot return a value, so the value defaults to None. y = x ** 2 return y def square (x): result = square(3) print(result) Using main() as a function Although in Python you can call the function at the bottom of your program and it will run, many programming languages require a main function in order to execute. Including a main() function, though non required, can structure our Python programs in a logical way that puts the most important components of the program into one function. It can also make our programs easier for non-Python programmers to read. print("Hello, World!") def hello(): print("This is the main function") hello() def main(): main() Because we called the hello() function within the main() and then only called main() to run, the Hello, World! Text printed only once, after the string that told us we were in the main function. If you define a variable within a function block, you'll only be able to use that variable within that function. In Pyrhon 'main' is the name of the scope where top-level code will execute. When a program is run from standard input, a script, or from an interactive prompt, its name is set equal to 'main'. #Code to run if name == 'main':
Comments are lines that exist in computer programs that are ignored by compilers and interpreters. Comments can serve as notes to yourself or reminders, or they can be written with the intention of other programmers being able to understand what your code is doing. Comment Syntax They begin with a hash mark and whitespace character and continue to the end of the line
Comments are in the source code for humans to read, not for computers to execute. Comments should be made at the same indent as the code it is commenting. Block comments Block comments can be used to explain more complicated code or code that you don't expect the reader to be familiar with. In block comments, each line begins with the hash mark and a single space. If you need to use more paragraph, they should be separated by a line that contains a single hash mark.
…. Variable. These #arguments … Inline comments Inline comments occur on the same line of a statements, following the code itself. They begin with a hash mark and a single whitespace character. [code ] #inline comment
program's namespace, letting us avoid dot notation. Aliasing Modules It's possible to modify the names of modules and their functions within Python by using the as keyword. You may want to change a name because you have already used the same name for something else in your program, another module you have imported also uses that name. The construction looks like this: import [module] as [another_name] So: import math as m print(m.pi) print(m.e) Within the program, we now refer to the pi constant as m.pi rather than math.pi
Each element or value that is inside of a list is called an item. Lists are great to use when you want to work with many related values. They enable you to keep data together that belongs together, condense your code, etc. Let's create a list that contains items of the string data type: sea_creatures = ['shark', 'cuttlefish', 'squid','mantis shrimp', 'anemone'] As an ordered sequence of elements, each item in a list can be called individually, through indexing. Lists are a compound data type made up of smaller parts, and are very flexible because they can have values added, removed and changed. Indexing Lists Each item in a list corresponds to an index number, which is an integer value, starting with the index number 0. The first item, the string 'shark' starts at index 0, and the list ends at index 4 with the item 'anemone'. Because each item in a Python list has a corresponding index number, we're able to access and manipulate lists in the same ways we can with other sequential data types. We can call a discrete item of the list by referring to its index number: print(sea_creatures[1]) #output: cuttlefish The index numbers for this list range from 0-4. We can also access items from the list with a negative index number, by counting backwards from the end of the list, starting at - 1. 'anemone' = sea_creatures[-1] We can concatenate strings items in a list with other strings using the + operator: print('Sammy is a' + sea_creatures[0]) With index numbers that correspond to items within a list, we're able to access each item of a list discretely and work with those items. Modifying items in Lists We can using indexing to change items within the list, by setting an index number equal to a different value. This gives us greater control over lists as we are able to modify and update the items that they contain. If we want to change the string value of the item at index 1 from 'cuttlefish' to 'octopus', we can do so like this: sea_creatures[1] = 'octopus' Now: print(sea_creatures) #output will be ['shark', 'octopus', 'squid', 'mantis shrimp', 'anemone'] Slicing Lists We can also call out a few items from the list. With slices, we can call multiple values by creating a range of index numbers separated by a colon [x:y]: print(sea_creatures[1:4])#the output:['octopus', 'squid', 'mantis shrimp']
print(oceans * 3) #the output: ['shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab', 'shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab'] ['Pacific', 'Atlantic', 'Indian', 'Southern', 'Arctic', 'Pacific', 'Atlantic', 'Indian', 'Southern', 'Arctic', 'Pacific', 'Atlantic', 'Indian', 'Southern', 'Arctic'] By using the * operator we can replicate our lists by the number of times we specify. We can also use compound forms of the + and * operators with the assignment operator =. The += and *= compound operators can be used to populate lists in a quick and automated way. sea_creatures += ['fish'] print(sea_creatures) for x in range(1,4): #the output: ['shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab', 'fish'] ['shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab', 'fish', 'fish'] ['shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab', 'fish', 'fish', 'fish'] The *= operator behaves in a similar way sharks = ['shark'] sharks *= 2 print(sharks) for x in range(1,4): ['shark', 'shark'] ['shark', 'shark', 'shark', 'shark'] ['shark', 'shark', 'shark', 'shark', 'shark', 'shark', 'shark', 'shark'] Removing an Item from a List Items can be removed from lists by using the del statement. This will delete the value at the index number you specify within a list. sea_creatures =['shark', 'octopus', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab'] del sea_creatures[1] print(sea_creatures) #the output: ['shark', 'blobfish', 'mantis shrimp', 'anemone', 'yeti crab'] Now the item at index position 1, the string 'octopus', is no longer in our list. We can also specify a range with the del statement. del sea_creatures[1:4] Constructing a List with List items Lists can be defined with items that are made up of lists, with each bracketed list enclosed inside the
Lists can be defined with items that are made up of lists, with each bracketed list enclosed inside the larger brackets of the parent list: sea_names = [['shark', 'octopus', 'squid', 'mantis shrimp'],['Sammy', 'Jesse', 'Drew', 'Jamie']] These list within lists are called nested lists. To access an item within the list, we will have to use multiple indices: print(sea_names[1][0]) print(sea_names[0][0]) The first list, since it is equal to an item, will have the index number of 0, which will be the first number in the construction, and the second list, will have the index number of 1. Within each inner nested list, there will be separate index numbers, which we will call in the second index number.