Introduction to Python

davidbpython.com




In-Class Exercises, 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
bb = 35


# if vara is equal to varb, print 'ok2' (use '==')
vara = 50
varb = 50.0


# if mya is greater than or equal to thisx, print 'ok3' (use '>=')
mya = 5
thisx = 4.9
Expected Output:
ok
ok2
ok3
ok4
ok5
ok5
 
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'
var_y = 'hello'
 
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
b = 3
 
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
mybb = 10
 
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'
vary = 'awe'
Expected Output:
is a substring
 

AND, OR, NOT

 
Ex. 2.6 Use 'or', 'and' and 'not' to perform the noted comparisons.
vara= 5
myb = -5

# single statement:  if variable 'vara' is greater than 0
# and also greater than 'myb', print 'ok1'


# single statement:  if variable 'vara' is greater than 0
# or 'myb' is greater than 0, print 'ok2'


# single statement:  if variable 'vara' is less than 0
# or 'myb' is not greater than 0, print 'ok3'
Expected Output:
ok1
ok2
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".

aa = input('"q" or "quit" to quit:  ')
 
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
that = 5.01
 
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.  '

ui = input('please enter search text:  ')
 

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.

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 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

ui = input('please enter an int value: ')

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 for greater than or less than.

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: ')

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: ')

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'

ui = input('please enter a substring: ')
Sample program run:
please enter a substring:  Utah
True

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:  ')

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:  ')

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

num = num + 1
num = num + 1
num += 1           # same as above 2 statements

print(num)         # 3
 
Ex. 2.18 While loop until threshold value. Increment <\B>num until it reaches the value of <\B>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
threshold = 3

# your while loop here




print('done')
Expected Output:
1
2
3
done
 
Ex. 2.19 While loop until arbitrary value. Add a test so that this while loop 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.)

# continue looping until input is equal to 'yes'
ui = ''

while  # your test here

    ui = input("please say yes, otherwise I'll ask again: " )





print('done')
Expected Output:
please say yes, otherwise I'll ask again: no
please say yes, otherwise I'll ask again: well
please say yes, otherwise I'll ask again: what
please say yes, otherwise I'll ask again: yes
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:

    ui = input('please enter "q" to quit:  ')

    # your code here

    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
count = 0

while count < maxval:

    count = count + 1

    # your code here:  loop back if count < 3

    print(count)


print('done')
Expected Output:
3
4
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
b = 3
c = 2
 

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
Expected Output:
1
2
3
4
 
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.

 
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.

 
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
Expected Output:
2
4
6
8
10
 

'TRANSFORMING' STRING METHODS

 
Ex. 2.27 Use string methods that transform a string with the below operations.
# lowercase and print this string (use .lower())
xx = 'HELLO'


# uppercase and print this string (use .upper())
zz = 'what?'


# replace 'this' with 'that' in the sentence,
# then print the replaced string (use .replace())
sentence = "I can't say no to this."
Expected Output:
hello
WHAT?
I can't say no to that.
 

'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'



# if string variable 'varstr2' is not all digits, print "not all digits"
# (use 'not' in front of .isdigit()))
varstr2 = '555a'



# 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'



# if the string 'filename2' ends with '.txt' (a text file), print "text file"
# (use .endswith())
filename2 = 'myfile.txt'
Expected Output:
all digits
hidden
text file
 

'f' STRINGS

 
Ex. 2.29 Use an f'' string to perform string formatting operations.
# insert numbers into a string:  using the below variables
# in one statement without concatenation,
# print '7 days a week, 365 days a year'

year = 365
week = 7



# insert a string variable into another string:
# without concatenation, print "my name is Python"

name = 'Python'



# 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'
Expected Output:
7 days a week, 365 days a year
my name is Python
The string is "aeiou" and its length is 5
 

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!

 
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: ')
 
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'
 
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
Expected Output:
Python was created in 1989.
 
[pr]