#!/usr/bin/env python # coding: utf-8 # In[8]: # Section 4.3 - for loops # aside about lists mylist=[1,2,3,5,7] print("mylist is",mylist) print("type(mylist) is",type(mylist)) anotherlist=['a',12345,12.2214,'more strings',1] print(anotherlist) print("type(anotherlist) is",type(anotherlist)) # can see particular entires in any list using list[#] print("anotherlist[0] is",anotherlist[0]) print("anotherlist[1] is",anotherlist[1]) print("anotherlist[2] is",anotherlist[2]) print("anotherlist[3] is",anotherlist[3]) print("anotherlist[4] is",anotherlist[4]) # In[13]: # syntax for for loops # for var in list: # do stuff # do stuff # do stuff # Example primes=[2,3,5,7,11,13,17,19,23,29] print("I will print some prime numbers for you.") for num in primes: print(num) # Do with strings beatles=['George','Ringo','John','Paul'] for member in beatles: print(member) # In[23]: # range function for num in range(5): print("Hello world! and num=",num) print(range(5)) print("type(range(5)) is",type(range(5))) print("list(range(5)) is",list(range(5))) print("type(list(range(5))) is",type(list(range(5)))) # range with two inputs # list(range(a,b)) gives a list [a,a+1,a+2,...,b-1] print("list(range(5,10)) is",list(range(5,10))) # In[35]: # List of perfect squares and perfect cubes # Tab symbol is written as \t in Python print('Number\t Square\t Cube') print('---------------------') for num in range(1,11): print(num,"\t",num**2,"\t",num**3) # In[44]: # User-defined list of squares start=int(input("Input the first integer.")) end=int(input("Input the final integer.")) print("Number\t Square") print("---------------") for num in range(start,end+1): print(num,"\t",num**2) # In[48]: # Section 4.4 -- calculating a running total # The idea is to have a variable that you continually update # Sum numbers programs #max number of numbers MAX=5 #our accumulator is set to 0 total=0.0 print("This program calculates the sum of",MAX,"numbers you will input.") for var in range(MAX): newnumber=float(input("Give me a number.")) total=total+newnumber print("The total was",total) #TABLE -- assume x=6 # Code What it does Value of x after # x=x+4 adds 4 to x 10 # x=x-3 subtracts 3 from x 3 # x=x*2 multiplies x by 2 12 # x=x/2 divides x by 2 3 # x=x%4 finds remainder of x/4 2 # Augmented assignment operators # Operators Example Equivalent to # += x+=4 x=x+4 # -= x-=3 x=x-3 # *= x*=2 x=x*2 # /= x/=2 x=x/2 # %= x%=4 x=x%4 # In[ ]: