Python-Loops

Published:2020-05-17
Share:

Python interpreter typically runs code sequentially first statement then the second .. from top to bottom, one alternative way of running code, is executing the same statements repeatedly, this term is known in programming as a loop not Lupe :)

Python loop types

Python supports two type of loop for and while loops

  • while loop which is a simple loop used mainly for infinite loops aka loops that doesn't need to stop, like listening for incoming connection on a server socket
    while condition:
    	expression
    	expression
    
  • for loop is a little less a simple than the while one, for is used mainly to iterate over a items in an object, for example lists, tuples, and dictionaries.
    for item in items:
    	print(item)
    
    In order to loop over a dictionary you can use the following for to get both keys and values
    for k, v in items:
    	print(k, v)
    

Examples

  • for loop
    #!usr/bin/python3
    
    host = 'coderme.com'
    for c in host:
    	print(c)
    
  • The following example is equivalent to the for loop one, but it uses while loop instead.
    #!usr/bin/python3
    
    host = 'coderme.com'
    c = 0
    
    while c < len(host):
    	print(host[c])
    	c += 1
    

Read also

Python Numbers

Python numeric types store allow you to play with numebers, numbers in python are immutable, which means changing the value of a number makes a new numeric object. Number objects Numbers in most programming languages are the simplest data to work with (well technically boolean is simpler, but lets just keep going :), so you can create a number by just an assignment, bingoooooo For example coder = 5 coderme = 7 com = 3 You can also delete a number variable like you delete any...