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))    

Odds or Evens

Create a program that simulates two players playing odds or evens

Example Output

odds play: 1, evens play: 2
total is: 3
-------------
odds score: 1, evens score: 0

odds play: 2, evens play: 2
total is: 4
-------------
odds score: 1, evens score: 1

odds play: 1, evens play: 2
total is: 3
-------------
odds score: 2, evens score: 1

Example Implementation

import random

def main():
    evens_score = 0
    odds_score = 0
    max_score = 5

    while evens_score < max_score and odds_score < max_score:
        evens_num = random.randint(1, 2)
        odds_num = random.randint(1, 2)
        total = evens_num + odds_num
        print("odds play: %s, evens play: %s" % (odds_num, evens_num))
        print("total is: %s" % (evens_num + odds_num))
        if total % 2 == 0:
            evens_score += 1
        else:
            odds_score += 1
        print("-------------")
        print("odds score: %s, evens score: %s\n" % (odds_score, evens_score))

main()

Reverse Sentence

Write a program that asks for exactly 5 words. The program should print the words in reverse order.

Example Output

Word please!
> program
Word please!
> amazing
Word please!
> my
Word please!
> out
Word please!
> check
check out my amazing program

Example Implementation

sentence = ''
for i in range(5):
    word = input("Word please!\n> ")
    sentence = word + ' ' + sentence

print(sentence)

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?')