CSC111 Sentinel Example 1

From dftwiki3
Revision as of 16:04, 20 February 2014 by Thiebaut (talk | contribs) (Example 2)
Jump to: navigation, search

--D. Thiebaut (talk) 15:36, 20 February 2014 (EST)


Example 1


# sumNum.py
# D. Thiebaut
#
# Computes the sum of positive numbers entered at the keyboard 
# until a negative number is entered is entered

sum = 0
x     = 0

while x >= 0:
    x = int( input( "> " ) )
    if x > 0:
        sum = sum + x

print( "sum = ", sum )
Question
What if the user wants to enter the sum of positive and negative numbers?


Example 2


# countKeywords.py
# D. Thiebaut
# counts number of lines where two different keywords may occur

KEY1 = "MOTHER"
KEY2 = "FATHER"
SENTINEL = "ZZZENDZZZ"

# counters
key1Count = 0
key2Count = 0
timeToStop= False

while timeToStop == False:
    line = input().upper()
 
    if line.find( SENTINEL ) != -1:
       timeToStop = True
    else:
       if line.find( KEY1 ) != -1:
          key1Count = key1Count + 1
       if line.find( KEY2 ) != -1:
          key2Count = key2Count + 1

print( key1Count, "line(s) with keyword", KEY1 )
print( key2Count, "line(s) with keyword", KEY2 )