import math
#basic while loops (and a for loop thrown in at the end)
#print the squares of the integers 1 through 10.
def one():
n=1
while n<=10:
print (n*n)
n=n+1 #Also can write n+=1 here
#Question what happens when you forget the n=n+1 ?
#Alternatively, print the squares that are no more than 500.
def two_a():
n=1
m=n*n
while m<=500:
print(m)
n+=1
m=n*n
#Same as above, but instead of hard-wiring an upper bound of 500,
#supply this as an argument to the function.
def two_b(x):
n=1
m=n*n
while m<=x:
print(m)
n+=1
m=n*n
#Another way of doing exactly the same thing, using the break statement
def three():
n=1
while True:
m=n*n
if m>500:
break
print(m)
n+=1
#Compute the sum of a list of numbers entered by the user.
#If the user hits return at the prompt,
#the loop terminates. (Notice the 'newline character' \n.)
def four():
running=0
while True:
x=input('Enter a number. Hit return to terminate.\n')
if x=='':
break
running+=float(x)
print(running)
#for statement: Here is another version of the function one()
#written using for and the range function. Observe how concise
#this is compared to the while statement
def five():
for x in range(1,11):
print(x*x)
#Below this line is some more 'advanced' stuff, concerning formatting output
#and trapping errors.
#First, let's try to make a nicely formatted table of the square roots of the
#integers 1 through 150. We do this in stages, starting with the most
#straighforward code.
def six_a():
for n in range(1,151):
print(n,math.sqrt(n))
#It might be a little nicer if I use a tab instead of a space to separate the
#columns.
def six_b():
for n in range(1,151):
print(n,math.sqrt(n),sep='\t')
#Now for some fancy formatting: We'll right-justify the first column and allow
#a field four characters wide, then make the second column line up in a field
#six characters wide with three digits after the decimal point.
def six_c():
for n in range(1,151):
output='{:4d}\t{:6.3f}'.format(n,math.sqrt(n))
print(output)
#Now let's re-do the running sum function (the function four()) so that
#if the user enters anything but a float or a return, a message is
#printed and the input is ignored.
def seven():
running=0
while True:
x=input('Enter a number. Type return to terminate.\n')
if x=='':
break
try:
running+=float(x)
except:
print('Bad input.')
print (running)