Docsity
Docsity

Prepara i tuoi esami
Prepara i tuoi esami

Studia grazie alle numerose risorse presenti su Docsity


Ottieni i punti per scaricare
Ottieni i punti per scaricare

Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium


Guide e consigli
Guide e consigli


PYTHON Starter Pack (impara le basi di python con teroria e esempi), Schemi e mappe concettuali di Informatica

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

2021/2022

In vendita dal 27/02/2022

edoardo-balducci
edoardo-balducci 🇮🇹

4.6

(8)

12 documenti

1 / 63

Toggle sidebar

Questa pagina non è visibile nell’anteprima

Non perderti parti importanti!

bg1
Python: if...else Statement 1
Python: if...else Statement
What is if...else statement in Python?
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.
Python if Statement Syntax
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 .
Python if Flowchart
Example: Python if Statement
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f

Anteprima parziale del testo

Scarica PYTHON Starter Pack (impara le basi di python con teroria e esempi) e più Schemi e mappe concettuali in PDF di Informatica solo su Docsity!

Python: if...else Statement 1

Python: if...else Statement

What is if...else statement in Python?

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.

Python if Statement Syntax

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.

Python if Flowchart

Example: Python if Statement

Python: if...else Statement 2

If the number is positive, we print an appropriate message

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...else Statement 4

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

Python: if...else Statement 5

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.

Try these two variations as well:

num = 0

num = -4.

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")

Python: for Loop 1

Python: for Loop

What is for loop in Python?

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.

Syntax of for Loop

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.

Flowchart of for Loop

Example: Python for Loop

Program to find the sum of all numbers stored in a list

List of numbers

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

variable to store the sum

Python: for Loop 2

sum = 0

iterate over the list

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]

Python: for Loop 4

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:

program to display student's marks from record

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.

Python: while Loop 1

Python: while Loop

What is while loop in Python?

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.

Syntax of while Loop in Python

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.

Flowchart of while Loop

Example: Python while Loop

Python: while Loop 3

'''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.

Python: break and continue 1

Python: break and continue

What is the use of break and continue in Python?

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.

Python break statement

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.

Syntax of break

break

Flowchart of break

Python: break and continue 3

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

Python: break and continue 4

The working of the continue statement in for and while loop is shown below.

Example: Python continue

Program to show the use of continue statement inside loops

for val in "string": if val == "i": continue print(val)

Python: pass statement 1

Python: pass statement

What is pass statement in Python?

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).

Syntax of pass

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.

Example: pass Statement

'''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

Python: Function 1

Python: Function

What is a function in Python?

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.

Syntax of Function

def function_name(parameters): """docstring""" statement(s)

Above shown is a function definition that consists of the following components.

  1. Keyword def that marks the start of the function header.
  2. A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of the function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example of a function

def greet(name): """ This function greets to the person passed in as