Skip to content
Snippets Groups Projects
module4_looping.py 1.41 KiB
Newer Older
  • Learn to ignore specific revisions
  • vand's avatar
    vand committed
    #%% example -- can't change iterator during for loop, formatting display
    
    for i in range(10):
        print(f'i is {i}, trying to change it to {3*i}')
        i = 3*i # don't do this (trying to change an iterator in a for loop)
        
    
    #%% example -- find largest number divisible with 7 and smaller than 100    
    i = 1
    while i*7<100:
        i = i+1
    print(7*i) # this will be larger than 100 -- so condition from while does not hold
    
    #%% example -- vectorization
    
    import numpy as np
    test = np.array([3, 4, 8, 6, 5, 8, 3, 4, 7, 8, 8, 9, 4, 1, 3, 4, 6, 7, 9, 5, 3, 5, 7, 2, 5, 3])
    
    ## I want to count how many times does 8 appear in test
    
    # One way of achieving this
    count = 0
    for t in test:
        if t==8:
            count += 1
            
    # A better way of achieving this
    count = (test==8).sum()
    
    
    #%% I want to count how many times does each digit appear in test
    
    # One way of achieving this
    hist = np.zeros(10, dtype='int')
    for i in range(len(hist)):
        hist[i] = (test==i).sum()
    
    # Another way of achieving this
    hist = np.zeros(10, dtype='int')
    for t in test:
        hist[t] += hist[t]
        
     
    #%% Avoid using break for better readability, if possible
    
    # Without break: readable code, easly to see when while loop stops
    i = 0
    while i<101: 
        i = i+1
        print(i, end= ' ')
        
        
    # With break: may be difficult to see when loop stops (especially in loops spanning many lines)
    i = 0
    while True:
        i = i+1
        print(i, end= ' ')
        if i>100:
            break