Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 2
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
IF/ELIF/ELSE with COMPARISON OPERATORS |
|
Ex. 2.1 | Use 'if' and 'if not' with comparison operators to perform the noted comparisons. |
# if aa is greater than bb, print 'ok1' (use '>')
aa = 50 # int, 50
bb = 35 # int, 35
if aa > bb: # bool, True
print('ok')
# if vara is equal to varb, print 'ok2' (use '==')
vara = 50 # int, 50
varb = 50.0 # float, 50.0
if vara == varb: # bool, True
print('ok2')
# if mya is greater than or equal to thisx, print 'ok3' (use '>=')
mya = 5 # int, 5
thisx = 4.9 # float, 4.9
if mya >= thisx: # bool, True
print('ok3')
|
|
Ex. 2.2 | Compare two strings for equivalence. |
If var_x is the same string value as var_y, print 'ok4' (use '==') |
|
var_x = 'hello' # str, 'hello'
var_y = 'hello' # str, 'hello'
if var_x == var_y: # bool, True
print('ok4')
|
|
Ex. 2.3 | Use 'if' with 'else'. |
If 'a' is greater than or equal to 'b', print 'greater than or equal to'. Otherwise (without an additional test) print 'lesser than'. Change the values to show both parts of the if/else are working correctly. |
|
a = 5 # int, 5
b = 3 # int, 3
if a >= b: # bool, True
print('greater than or equal to')
else:
print('lesser than')
|
|
Ex. 2.4 | Use 'if' with 'elif' and 'else'. |
If variable 'myaa' is greater than variable 'mybb', print 'greater'; otherwise if 'myaa' is less than 'mybb', print 'lesser', otherwise, print 'equal'. Again, change the values to prove that all 3 conditions are correctly handled. |
|
myaa = 20 # int, 20
mybb = 10 # int, 10
if myaa > mybb: # bool, True
print('greater')
elif myaa < mybb: # bool, False
print('lesser')
else: #
print('equal')
|
|
Ex. 2.5 | Test to see if one string can be found in another. |
Use if with in to see if the characters in varx can be found in vary; if so, print 'is a substring'. |
|
varx = 'Python is awesome' # str, 'Python is awesome'
vary = 'awe' # str, 'awe'
if vary in varx: # bool, True
print('is a substring')
|
|
AND, OR, NOT |
|
Ex. 2.6 | Use 'or' and 'and' to perform the noted comparisons. |
vara= 5 # int, 5
myb = -5 # int, -5
# single statement: if variable 'vara' is greater than 0
# and also greater than 'myb', print 'ok1'
if vara > 0 and vara > myb: # bool, True
print('ok1')
# single statement: if variable 'vara' is greater than 0
# or 'myb' is greater than 0, print 'ok2'
if vara > 0 or myb > 0: # bool, True
print('ok2')
# single statement: if variable 'vara' is less than 0
# or 'myb' is not greater than 0, print 'ok3'
if vara < 0 or not myb > 0: # bool, True
print('ok3')
|
|
Ex. 2.7 | Use 'or' to test a variable for multiple values. |
In a single statement, if user's input is equal to "q" or "quit", print "quitting..."; otherwise, print "NOT quitting". MAKE SURE TO TEST WITH 'q', 'quit' AND 'hello' (i.e., neither 'q' nor 'quit' -- this last test is extremely important). |
|
aa = input('"q" or "quit" to quit: ') # 'q' (sample value)
if aa == 'q' or aa == 'quit': # bool, True
print("quitting...")
else:
print('NOT quitting')
|
|
Ex. 2.8 | Use a negative test. |
If the value of variable 'this' is NOT equal to variable 'that', print 'ok5'. Do this two ways, without using 'else' (use '!=' and '==' with not') |
|
this = 5.0 # float, 5.0
that = 5.01 # float, 5.01
if this != that: # bool, True
print('ok5')
if not this == that: # bool, True
print('ok5')
|
|
Ex. 2.9 | Use 'not' with 'in'. |
Use not in front of the in operator to see if user's input is not in the sentence. If cannot be found there, print not found. |
|
text = 'Calculation is the name of the game.' # str, 'Calculation...'
num = input('please enter search text: ') # str, 'name' (sample value)
if not num in text: # bool, False
print('not found')
|
|
LAB 1 |
|
Ex. 2.10 | Compare user input to string. |
Take keyboard input from the user, then see if it is equal to 'quit'. If it is, print quitting.... Make sure to test with 'quit' and with another input value. |
|
ui = input('please enter quit: ') # str, 'quit' (sample value)
if ui == 'quit': # bool, True
print("quitting")
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.11 | Compare user input for a number to an integer; test for equivalence. |
Take keyboard input for a number from the user, then see if the number is equal to integer 5. If so, print 'is equal to 5'. Again, test both with 5 and another value. |
|
test_int = 5 # int, 5
ui = input('please enter an int value: ') # str, '5'
iui = int(ui) # int, 5
if iui == test_int: # bool, True
print('is equal to 5')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.12 | Compare user input for a number to an integer; test for greater or lesser. |
Take keyboard input for a number from the user, then see if the number is greater than 0; if so, print 'positive'. Otherwise, see if it is less than 0; if so, print 'negative'. Otherwise, print 'zero'. Again, test with positive and negative values, and 0. (Don't forget that if your logic says 'otherwise', it should use elif or else.) |
|
ui = input('please enter an int value: ') # str, '4' (sample value)
iui = int(ui) # int, 4
if iui > 0: # bool, True
print('positive')
elif iui < 0: # bool, False
print('negative')
else:
print('zero')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.13 | Take user input for a number, then say whether the number is even or odd. |
Remember to test for both! |
|
ui = input('please enter an int value: ') # str, '3' (sample value)
iui = int(ui) # int, 3
if iui % 2 == 0: # bool, False
print('even')
else:
print('odd')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.14 | Take user input, say if it is a substring of another string. |
If the user types a string of characters that can be found in test_string, print True otherwise print False. Remember to test! |
|
test_string = 'Alaska,California,Nevada,Utah' # str, 'Alaska,...'
ui = input('please enter a substring: ') # str, 'Utah'
if ui in test_string: # bool, True
print('True')
else:
print('False')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.15 | Take user input for a number, say if it is equal to one value or equal to another value. |
If the user's number is equal to 5 or equal to 15, print 'true'; otherwise, print 'false'. |
|
ui = input('please enter an int value: ') # str, '5' (sample value)
iui = int(ui) # int, 5
if iui == 5 or iui == 15: # bool True
print('true')
else:
print('false')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
Ex. 2.16 | Take user input for a number, say if it is less than one value and greater than another value. |
If the user's number is less than 101 and greater than 0, print 'within range'; otherwise, print 'out of range'. |
|
ui = input('please enter an int value: ') # str, '35' (sample value)
iui = int(ui) # int, 35
if iui > 0 and iui < 101: # bool, True
print('within range')
else:
print('out of range')
|
|
Please note import runreport refers to my own custom module for working with the class during lab periods. For now it is disabled, we will discussed when we get an opportunity. |
|
WHILE |
|
Ex. 2.17 | Increment a value 3 times. |
In 3 statements, use incrementation (num = num + 1, or num += 1) to bring the value num to 3. |
|
num = 0 # int, 0
num = num + 1 # int, 1
num = num + 1 # int, 2
num += 1 # int, 3 (same as previous 2 lines)
|
|
Ex. 2.18 | While loop until threshold value. |
Increment num until it reaches the value of threshold. (Note if you can't get out of a loop, in PyCharm use the red square to the left of the Run window; in Jupyter notebook, restart the kernel.) |
|
num = 0 # int, 0
threshold = 3 # int, 3
while num < threshold: # bool, True (initial value)
num = num + 1 # int, 1
print(num)
print('done')
|
|
Ex. 2.19 | While loop until arbitrary value. |
Add a test so that this while loop that continues looping until the user's input is equal to 'yes'. (Note if you can't get out of a loop, in PyCharm use the red square to the left of the Run window; in Jupyter notebook, restart the kernel.) |
|
ui = '' # str, '' (empty string)
while ui != 'yes': # bool, False (initial value)
ui = input("please say yes, otherwise I'll ask again: " ) # str, 'yes' (sample value)
print('done')
|
|
BREAK AND CONTINUE |
|
Ex. 2.20 | Use 'break' to break out of a loop if a condition is True. |
The below loop will loop indefinitely, asking the user for input (try it, then use the red square to the left of the Run window or in Jupyter restart the kernel to get out of the loop). Add a statement to test if equal to 'q', break out of the loop (otherwise, loop should take us back to input again). |
|
while True: # bool, True
ui = input('please enter "q" to quit: ') # str, 'X' (sample value)
if ui == 'q': # bool, False
break
print('continuing...')
print('done')
|
|
Ex. 2.21 | Use 'continue' to keep iterating. |
Run this code first. Then if value of 'count' is < 3, use 'continue' to keep iterating without printing. You should see only '3' and '4' printed. |
|
maxval = 4 # int, 4
count = 0 # int, 0
while count < maxval: # bool, True (initial value)
count = count + 1 # int, 1
if count < 3: # bool, False (initial value)
continue
print(count)
print('done')
|
|
Ex. 2.22 | Modulus operator. |
What is a % b? What is a % c? Can you tell why this operator is returning these values? |
|
a = 8 # int, 8
b = 3 # int, 3
c = 2 # int, 2
x = a % b # int, 2
print(x)
y = a % c # int, 0
print(y)
|
|
LAB 2 |
|
Ex. 2.23 | Create a while loop with a counter and terminal value. |
Inside a while block, increment the counter and print the counter value. If the counter is greater than 3, the while loop should exit. In other words, it should keep looping while it is less than or equal to 3 (do not use break here). |
|
counter = 0 # int, 0
while counter <= 3: # bool, False (initial value)
counter = counter + 1 # int, 1
print(counter)
|
|
Ex. 2.24 | Create a while loop that breaks if user input equals a certain value. |
Inside a while True block, take user input. If the user typed 'quit', break out of the loop. Otherwise, allow the loop to loop back and ask again. |
|
while True: # bool, True
ui = input('please type "quit": ') # str, 'quit' (sample value)
if ui == 'quit': # bool, True
break
|
|
Ex. 2.25 | Create a while loop that continues if user input does not equal a certain value, otherwise breaks. |
Inside a while True block, take user input. If the user did not type 'quit', use continue to go back to the top of the while block; otherwise, break out of the loop. |
|
while True: # bool, True
ui = input('please enter "quit"') # str, 'hey' (sample)
if ui != 'quit': # bool, False
continue #
break #
|
|
Ex. 2.26 | Create a while loop that uses modulus to determine whether to continue. |
Create a while loop that increments the counter and stops looping if counter becomes greater than 10. Now add an if statement that checks to see if counter is even. If it is, it prints the counter. You should see only even numbers printed. |
|
counter = 0 # int, 0
while counter <= 10: # bool, True (initial value)
counter += 1 # int, 1
if counter % 2 == 0: # bool, False
print(counter)
|
|
'TRANSFORMING' STRING METHODS |
|
Ex. 2.27 | Use string methods that transform a string with the following operations. |
# lowercase and print this string (use .lower())
xx = 'HELLO' # str, 'HELLO'
xxl = xx.lower() # str, 'hello'
print(xxl)
# uppercase and print this string (use .upper())
zz = 'what?' # str, 'what?'
zzl = zz.upper() # str, 'WHAT?'
print(zzl)
# replace 'this' with 'that' in the sentence,
# then print the replaced string (use .replace())
sentence = "I am not going to try this." # str, 'I am not going to try this.'
sr = sentence.replace('this', 'that') # str, 'I am not going to try that.'
print(sr)
|
|
'INSPECTNG' STRING METHODS |
|
Ex. 2.28 | Use string methods that evaluate a string. |
Perform the following operations: |
|
# if string variable 'varstr' is all digits, print "all digits" (use .isdigit())
varstr = '555' # str, '555'
if varstr.isdigit(): # bool, True
print('all digits')
# if string variable 'varstr2' is not all digits, print "not all digits"
# (use 'not' in front of .isdigit()))
varstr2 = '555a' # str, '555a'
if not varstr.isdigit(): # bool, True
print('not all digits')
# if the string 'filename' starts with a "." (period), print "hidden"
# (incidentally, this signifies a "hidden" file on your computer's filesystem)
# (use .startswith())
filename = '.hidden' # str, '.hidden'
if filename.startswith('.'): # bool, True
print('hidden')
# if the string 'filename2' ends with '.txt' (a text file), print "text file"
# (use .endswith())
filename2 = 'myfile.txt' # str, 'myfile.txt'
if filename2.endswith('.txt'): # bool, True
print('text file')
|
|
'f' STRINGS |
|
Ex. 2.29 | Use an f'' string to perform the following operations. |
# insert numbers into a string: in one statement without concatenation,
# print '7 days a week, 365 days a year'
year = 365 # int, 365
week = 7 # int, 7
print(f'{week} days a week, {year} days a year')
# insert a string variable into another string:
# without concatenation, print "my name is Python"
name = 'Python' # str, 'Python'
print(f'my name is {name}')
# call a function inside a string: in one statement,
# without using the literal '5', and without concatenation,
# print the string and also its length.
# the output should be "The string is "aeiou" and its length is 5"
x = 'aeiou' # str, 'aeiou'
print(f'The string is "{x}" and its length is {len(x)}')
|
|
LAB 3 |
|
Ex. 2.30 | Validate a user's input string, case-insensitively. |
Take user input, then check to see if it is equal to quit but in any string case (Quit, qUIt, QUIT, etc.) Do not try to account for every combination -- instead, lowercase the user's string before testing. Print 'quitting...'. Make sure to test multiple combinations of case! |
|
ui = input('please enter quit: ') # str, 'QuIt' (sample value)
if ui.lower() == 'quit': # bool, True
print('quitting...')
|
|
Ex. 2.31 | Check to see if a user's input string is all digits. |
Take user input and see if it is all digit characters. If it is, print all digits, otherwise print not all digits. Make sure to test with all digits and with a string that is not all digits. |
|
ui = input('please enter a number: ') # str, '.txt'
if ui.isdigit(): # bool, True
print('all digits')
|
|
Ex. 2.32 | Check to see if a user's input string ends with a substring. |
Take user input and if the input ends with '.txt', print this is a text file/B> otherwise print not a text file. |
|
ui = input('please enter a filename: ') # str, 'test.txt'
if ui.endswith('.txt'): # bool, True
print('this is a text file')
else: #
print('not a text file')
|
|
Ex. 2.33 | Insert a number into a string. |
Print Python was created in 1989. exactly as shown, without using str(), concatenation or a comma inside print() (or the literal value 1989 of course -- use anno) |
|
anno = 1989 # int, 1989
print(f'Python was created in {anno}.')
|
|