























































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
In questo pdf sono raccorte le basi per programare in python. Imparare una lingua di programmazione può essere complicato se non si sa da dove partire e dove si deve arrivare. In questo pdf (in inglese) ci sono tutte le nozioni fondamentali di Python, il linguaggio di programmazione del presente e del futuro.
Tipologia: Schemi e mappe concettuali
1 / 63
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!
























































Decision making is required when we want to execute a code only if a certain condition is satisfied.
The if…elif…else statement is used in Python for decision making.
if test expression: statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the test expression is True.
If the test expression is False , the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. The body starts with an indentation and the first unindented line marks the end.
Python interprets non-zero values as True. None and 0 are interpreted as False.
num = 3 if num > 0: print(num, "is a positive number.") print("This is always printed.")
num = - if num > 0: print(num, "is a positive number.") print("This is also always printed.")
When you run the program, the output will be:
3 is a positive number This is always printed This is also always printed.
In the above example, num > 0 is the test expression.
The body of if is executed only if this evaluates to True.
When the variable num is equal to 3, test expression is true and statements inside the body of if are executed.
If the variable num is equal to -1, test expression is false and statements inside the body of if are skipped.
The print() statement falls outside of the if block (unindented). Hence, it is executed regardless of the test expression.
Python if...else Statement
Syntax of if...else
if test expression: Body of if else: Body of else
The if..else statement evaluates test expression and will execute the body of if only when the test condition is True.
Python if...elif...else Statement
Syntax of if...elif...else
if test expression: Body of if elif test expression: Body of elif else: Body of else
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for if is False , it checks the condition of the next elif block and so on.
If all the conditions are False , the body of else is executed.
Only one block among the several if...elif...else blocks is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart of if...elif...else
Example of if...elif...else
'''In this program, we check if the number is positive or negative or zero and display an appropriate message'''
num = 3.
if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number")
When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.
Python Nested if statements
We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.
Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.
Python Nested if Example
'''In this program, we input a number check if the number is positive or negative or zero and display an appropriate message This time we use nested if statement'''
num = float(input("Enter a number: ")) if num >= 0: if num == 0: print("Zero") else: print("Positive number")
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.
for val in sequence: loop body
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers: sum = sum+val
print("The sum is", sum)
When you run the program, the output will be:
The sum is 48
The range() function
We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers).
We can also define the start, stop and step size as range(start, stop,step_size). step_size defaults to 1 if not provided.
The range object is "lazy" in a sense because it doesn't generate every number that it "contains" when we create it. However, it is not an iterator since it supports in , len and getitem operations.
This function does not store all the values in memory; it would be inefficient. So it remembers the start, stop, step size and generates the next number on the go.
To force this function to output all the items, we can use the function list().
The following example will clarify this.
print(range(10))
print(list(range(10)))
print(list(range(2, 8)))
print(list(range(2, 20, 3)))
Output
range(0, 10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [2, 3, 4, 5, 6, 7] [2, 5, 8, 11, 14, 17]
No items left.
Here, the for loop prints items of the list until the loop exhausts. When the for loop exhausts, it executes the block of code in the else and prints No items left.
This for...else statement can be used with the break keyword to run the else block only when the break keyword was not executed. Let's take an example:
student_name = 'Soyuj'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks: if student == student_name: print(marks[student]) break else: print('No entry with that name found.')
Output
No entry with that name found.
The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate beforehand.
while test_expression: Body of while
In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression
is checked again. This process continues until the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
'''Example to illustrate the use of else statement with the while loop'''
counter = 0
while counter < 3: print("Inside loop") counter = counter + 1 else: print("Inside else")
Output
Inside loop Inside loop Inside loop Inside else
Here, we use a counter variable to print the string Inside loop three times.
On the fourth iteration, the condition in while becomes False. Hence, the else part is executed.
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until the test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.
The break and continue statements are used in these cases.
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
break
print(val)
print("The end")
Output
s t r The end
In this program, we iterate through the "string" sequence. We check if the letter is i, upon which we break from the loop. Hence, we see in our output that all the letters up till i gets printed. After that, the loop terminates.
Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
continue
Flowchart of continue
The working of the continue statement in for and while loop is shown below.
Example: Python continue
for val in "string": if val == "i": continue print(val)
In Python programming, the pass statement is a null statement. The difference between a comment and a pass statement in Python is that while the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when the pass is executed. It results in no operation (NOP).
pass
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing.
'''pass is just a placeholder for functionality to be added later.''' sequence = {'p', 'a', 's', 's'} for val in sequence: pass
We can do the same thing in an empty function or class as well.
def function(args): pass
class Example: pass
In Python, a function is a group of related statements that performs a specific task.
Functions help break our program into smaller and modular chunks. As our program growsarger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes the code reusable.
def function_name(parameters): """docstring""" statement(s)
Above shown is a function definition that consists of the following components.
def greet(name): """ This function greets to the person passed in as