CODE STRUCTURES
LINES OF CODE

Before we talk about “loop and range conditional structures in Python”, let’s look at code structures.

The physical line is the line of code we write. The logical line is the one that Python assembles from a certain number of physical lines and then generates a single instruction. Let’s see an example.

Lines of code

The simple program shown here makes use of two lines of code and a comment that is not part of them. When Python runs the program it transforms the two lines of code into two logical lines, so in this case the ratio is 1: 1.

Code lines example

In this case there are four physical lines as the source is written on four distinct physical lines that Python assembles on two logical lines, recomposes the string on a single line, first logical instruction, and finally the print statement, second logical instruction .

Multi-line code

When Python runs the program, it assembles the two physical lines that define the tuple into a logical line, plus a logical line for print, in all three physical lines and two logical lines.

Unescaped code on multiple logical lines

CODE BLOCKS

They represent a code structure. Code blocks can be nested to create a hierarchical structure. Python, unlike other languages such as Java, C# which uses curly brackets to determine the beginning and end of a block, uses indentation, usually four spaces to the right of the upper instructions to delimit a block of code.

Indentation

THE STATEMENT

A physical line of code usually consists of a single statement also called a Statement.

statement

In this example, the first Statement is an assignment, the second a function call. It is also possible to insert several Statements on a line, they must be separated with the character;

two statements on one line

SIMPLE AND COMPOUND STATEMENTS

s=”Python”      Simple statement 

Simple statement

COMPOSED STATEMENT

compound statement

EXAMPLE OF COMPOSED STATEMENT CODE

compound statement

THE STATEMENT IF

The Statement if is used to take a number of different actions based on Boolean tests of the type True or False. When an expression is evaluated True, the suite of instructions for that block is executed. The expressions could also all give False, furthermore it is optional, and if present, the else statement must be unique while the elif statements can be zero, one or more than one, this according to need.

Statement if
def Statement():
    #PRIMO ESEMPIO
    x=8
    if x<10: #Si legge "se x minore di 10 
             #allora stampa a video Minore di 10"
        print("Minore di 10")
    #SECONDO ESEMPIO
    x=10
    if x<10:#Si legge:Se x<10 (test booleano) allora stampa Minore di 10
            #else (altrimenti stampa >=10)
        print("Minore di 10")
    else:
        print("Maggiore o uguale a 10")
    #TERZO ESEMPIO
    x=6
    if x<5:               #se x<5
        print("< di 5")
    elif (x>=5 and x<=10):# altrimenti se x compreso tra 5 e 10
        print(">=5 e <= a 10")
    else:                 #altrimenti in tutti gli altri casi > di 10
        print("> di 10")
Statement()

THE STATEMENT WHILE

If the expression is evaluated immediately False it does not enter the Loop, vice versa if True it enters the suite of the Loop many times until the condition turns out to be true. In all cases, if it has the else clause, this is always executed even if the expression has False as its initial test value.

While
def While():
    #PRIMO ESEMPIO
    x=0
    while(x<3):#sino a che x<3 esegui la suite di while
        print(x)
        x+=1 #Incremento x per chiudere il Loop
             #e non ciclare all'infinito
             #stamperà 0,1,2
    else:
        print("Codice ramo else sempre eseguito.")
    #SECONDO ESEMPIO
    #Ci sono molti casi in cui non sappiamo a priori quante
    #volte deve essere eseguito un loop. Ad esempio:
    while True:#LOOP INFINITO
        x=input("Inserire una stringa: ")
        if x=='stop':
            break #LO STATEMENT BREAK INTERROMPE IMMEDIATAMENTE IL LOOP
        print(x)
    #TERZO ESEMPIO
    while True:#LOOP INFINITO
        x=input("Inserire una stringa: ")
        if x=='stop':
            break     #LO STATEMENT BREAK INTERROMPE IMMEDIATAMENTE IL LOOP
        if x <'b':
            continue  #CONTINUE NON INTERROMPE IL LOOP MA SI
                      #RITORNA IN TESTA AL LOOP STESSO
        print(x)
While() 

THE STATEMENT FOR

Statement for
def For():
    #PRIMO ESEMPIO
    myList = [3,4,5,6,7,8]
    for x in myList:
        print(x)
    else:
        print("Ramo else sempre esguito.")
    #SECONDO ESEMPIO
    myString = "Hello"
    for x in myString:
        print(x)
    #TERZO ESEMPIO
    myDict = {"a":1,"b":2,"c":3}
    for x in myDict:
        print(x)#STAMPA LE CHIAVI
    for x in myDict.values():
        print(x)#STAMPA I VALORI
    for x in myDict.items():
        print(x)#STAMPA CHIAVI E VALORI
    #LE PAROLE CHIAVE BREAK E CONTINUE FUNZIONANO ALLO STESSO
    #MODO VISTO NEL CICLO WHILE
For()

THE RANGE FUNCTION

In the conditional loops and range structures in Python, the range function takes on an important aspect. When called, it returns an iterable object that contains a sequence of consecutive numbers. The three parameters are similar to the slice parameters we have already seen. Stop is mandatory start and step are optional. Start if not indicated is zero, and default step is one if not indicated. Stop is excluded as a limit for this reason 16 is not printed.

Range
def Range():
    #Scrivere un algoritmo utilizzando un ciclo for
    #e la funzione range compresa tra 10 e 50 che 
    #aggiunge ad una lista
    #i numeri dispari compresi tra 10 e 40.
    lista=[]
    for x in range(10,50):
        if (x % 2 > 0) and (x < 40):
            lista.append(x)
    print(lista)        
Range()

LINK TO GITHUB CODE

GITHUB

LINKS TO PREVIOUS POST

PREVIOUS POST LINKS