Tutorial A4 Bolean and repeated statements

6 important questions on Tutorial A4 Bolean and repeated statements

Defineer sign en if or else (2x)

def sign(num):
    if num > 0:
        result = +1
    elif num < 0:
        result = -1
    else:
        result = 0
    return result

Definite loops (ivm range)

where the number of repetitions is known at the moment the structure starts.
  The definite loop, or “for”-loop, does all necessary bookkeeping in situations where the number of repetitions is known in advance, at the latest when the loop starts executing. -> FOR LOOP

The indefinite loop (voorbeeld a while-loop that computes the first power of 2 that is larger than 1000:)

“while”-loop, is very similar to the if-structure.

power = 1 
exponent = 0    
while power <= 1000:  
    power = power * 2 
    exponent = exponent + 1 
print '2 ** ', exponent, '=', power
  • Higher grades + faster learning
  • Never study anything twice
  • 100% sure, 100% understanding
Discover Study Smart

Functie van range bij definit loop

To specify that the loop has to repeat n times, for some given value of n, we write:

for i in range(n):    
    # here goes the loop body

The function “range” gives a list ofn numbers from 0 to (but without) n

For i in range(10):
    print i


0
1
2
3
4
5
6
7
8
9

What happens if n is negative? (for range)

When the only argument of functionrangeis negative, the series is empty. In that case, the for-loop does not execute its body at all.

The question on the page originate from the summary of the following study material:

  • A unique study and practice tool
  • Never study anything twice again
  • Get the grades you hope for
  • 100% sure, 100% understanding
Remember faster, study better. Scientifically proven.
Trustpilot Logo