Personal tools
You are here: Home → Comp 171 Scripting Practicum → Course Materials → Python Materials → Python Programs → Examples Using If and Logic
Document Actions

Examples Using If and Logic

by Dr. William L. Honig — last modified 2012-02-18 11:23 PM

Basics of control structures using if else elif. Learn about Boolean logic and decision making in scripts

Click here to get the file

Size 2.0 kB - File type text/python-source

File contents

# 
#Comp 171 Standard Python Script Header 
#Assignment name: Understand logic and decision making
#LUC id and Name whonig@luc.edu  William Honig 
#Date 19 Feb 2012
# 
#Examples of if control structure
# 
#Questions: Do you understand how to use variables to keep totals as your script works?
#           Need help? See Dr. Harrington's Python book, section 1.13.7, Accumulation Loops
# 
#           More help needed on control structures (if and else and elif)?
#           See See Dr. Harrington's Python book, section 3.1, If Statements
#
def simpleAdder():
    aList = [ 10, 20, 35, 40, 55 ]
    total = 0
    for num in aList:
        total = total + num
    print( "The total of the list is: " + str(total) )

def tensAdder():
    aList = [ 10, 20, 35, 40, 55 ]
    total = 0
    tensTotal = 0
    for num in aList:
        total = total + num
        if( num%10 == 0 ):
            tensTotal = tensTotal + num
    print( "The total of the list is: " + str(total) )
    print( "The total of the multiples of ten is: " + str(tensTotal) )

    
def pickyCounter():
    aList = [ 7, 34, 11, 14, 10, 30, 16, 70, 53, 99 ]
    tensCount = 0
    multiplesOfFirstCount = 0
    primesLessThan10Count = 0
    fiftysAndNinetysCount = 0
    allOthersCount = 0
    firstNum = ""
    for num in aList:
        if( num%10 == 0 ):
            tensCount = tensCount + 1
        elif( num in [2,3,5,7] ):
            primesLessThan10Count = primesLessThan10Count + 1
        elif( (num > 50 and num < 60) or (num > 90 and num <100) ):
            fiftysAndNinetysCount = fiftysAndNinetysCount + 1
        else:
            allOthersCount = allOthersCount + 1
        if( firstNum == ""):
            firstNum = num
        else:
            if( num%firstNum == 0 ):
                multiplesOfFirstCount = multiplesOfFirstCount + 1
    print( tensCount, primesLessThan10Count, fiftysAndNinetysCount, allOthersCount, multiplesOfFirstCount )        
                  
            
« October 2027
Su Mo Tu We Th Fr Sa
12
3456789
10111213141516
17181920212223
24252627282930
31
 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: