Loop Exercises

Fours and Roots

Print out the square root of every multiple of 4 that's less than 65, but greater than 3

import math
for n in range(4, 65, 4):
    print(math.sqrt(n))    

An ATM Program

Create a program that simulates an ATM

Example Output

Your current balance is 5
(D/d)eposit, (W/w)ithdraw or (Q/q)uit?
> D
how much would you like to deposit?
> 10
Your current balance is 15
(D/d)eposit, (W/w)ithdraw or (Q/q)uit?
> d
how much would you like to deposit?
> 2
Your current balance is 17
(D/d)eposit, (W/w)ithdraw or (Q/q)uit?
> w
how much would you like to withdraw?
> 8
Your current balance is 9
(D/d)eposit, (W/w)ithdraw or (Q/q)uit?
> blah
huh?
Your current balance is 9
(D/d)eposit, (W/w)ithdraw or (Q/q)uit?
> q
k, thx bye

Example Implementation

balance = 5
command = ''
while command != 'q' and command != 'Q':
    print("Your current balance is %s" % (balance))
    command = input("(D/d)eposit, (W/w)ithdraw or (Q/q)uit?\n> ")
    if command == 'd' or command == 'D':
        amt = int(input('how much would you like to deposit?\n> '))
        balance += amt
    elif command == 'w' or command == 'W':
        amt = int(input('how much would you like to withdraw?\n> '))
        balance -= amt
    elif command == 'q' or command == 'Q':
        print('k, thx bye')
    else:
        print('huh?')

Generate Random Bits

Write the following program

how many bits (between 4 and 8)?
>4
0011 in binary is 3 in decimal

Random Bits Solution!

import random

bit_length = 0
while bit_length < 4 or bit_length > 8: 
    bit_length = int(input('how many bits (between 4 and 8)?\n>'))
bits = ''
num = 0
for exponent in range(bit_length):
    b = random.randint(0, 1)
    bits = str(b) + bits
    num += b * (2 ** exponent)

print('%s in binary is %s in decimal' % (bits, num))