Loops
First,
see here, but skip sections 2 and 4, we will cover them later.
Below are the examples we covered in class.
while loops
def getPositiveInteger():
userInput = 0
while(userInput <= 0):
userInput = int(input("Enter a positive integer: "))
return userInput
# Repeating a block of code a certain number of times with a while loop:
i = 0
numRepetitions = 10
while (i < numRepetitions):
# Some block of code
# ...
counter += 1
def countToN(n):
counter = 1
while(counter <= n):
print(counter)
counter += 1
countToN(7)
def sumToN(n):
counter = 1
total = 0
while(counter <= n):
total += counter
counter += 1
return total
print(sumToN(5)) # prints 15
def sumFromMToN(m, n):
counter = m
total = 0
while(counter <= n):
total += counter
counter += 1
return total
print(sumFromMToN(3,6)) # prints 18
def leftmostDigit(n):
while (n >= 10):
n = n // 10
return n
print(leftmostDigit(1234)) # prints 1
print(leftmostDigit(-1234)) # prints -1234 (wrong answer)
def leftmostDigit(n):
n = abs(n)
while (n >= 10):
n = n // 10
return n
print(leftmostDigit(-1234)) # prints 1
def nthAwesome(n):
found = 0
guess = 0
while (found <= n):
if (isAwesome(guess)):
found += 1
guess += 1
return guess - 1
def isAwesome(m):
return ((m % 3) == 0) or ((m % 5) == 0)
for loops
for i in [1, 2, 3, 4]:
print(i)
# the following does the same thing
# think of range(m, n) as the list [m, m+1, .., n-1]
for i in range(1, 5):
print(i)
# range(n) is the same as range(0, n)
# note that it starts from 0!
for i in range(5):
print(i)
# this prints the letters of "Hello", each one on a separate line
for c in "Hello":
print(c)
# If you know how many iterations are needed,
# use a for loop rather than a while loop.
def sumToN(n):
total = 0
for i in range(n+1):
total += i
return total
def sumFromMToN(m, n):
total = 0
for i in range(m, n+1):
total += i
return total
# think of range(m, n, k) as the list [m, m+k, m+2k, m+3k, ...]
# (stops before reaching n)
def sumEveryKthFromMToN(m, n, k):
total = 0
for i in range(m, n+1, k):
total += i
return total
def sumOfOddsFromMToN(m, n):
total = 0
for x in range(m, n+1):
if (x % 2 == 1):
total += x
return total
def sumOfOddsFromMToN(m, n):
if (m % 2 == 0):
# m is even, add 1 to start on an odd
m += 1
total = 0
for i in range(m, n+1, 2):
total += i
return total
# This works, but is not clear code!
def sumOfOddsFromMToN(m, n):
if (n % 2 == 0): n -= 1
total = 0
for x in range(n, m-1, -2):
total += x
return total
isPrime and nthPrime
def isPrime(n):
if (n < 2): return False
for x in range(2, n):
if(n % x == 0): return False
return True
def fasterIsPrime(n):
if (n < 2): return False
maxFactor = round(n**0.5)
for x in range(2, maxFactor + 1):
if(n % x == 0): return False
return True
def nthPrime(n):
found = 0
guess = 0
while (found <= n):
guess += 1
if (isPrime(guess)):
found += 1
return guess