Introduction to Python
davidbpython.com
In-Class Exercise Solutions, Session 1
PLEASE REFER to pythonreference.com for syntax to follow in coding these Exercises |
|
ALSO PLEASE NOTE THAT THESE ARE NOT HOMEWORK PROBLEMS TO BE TURNED IN! The homework projects are linked as 'Homework Projects' at the bottom of the Session's links. |
|
VARIABLES AND ASSIGNMENT; IDENTIFYING OBJECT TYPE |
|
Ex. 1.1 | Numeric and string assignment, and type() function. |
Assign an integer to new variable 'vari', a float to 'varf' and a string to 'varstr'. Print, and use the type() function to print the value and type of one or more of them. |
|
vari = 5 # int, 5
varf = 5.0 # float, 5.0
varstr = 'hey' # str, 'hey'
print(vari)
print(varf)
print(varstr)
print(type(vari)) # <class 'int'>
print(type(varf)) # <class 'float'>
print(type(varstr)) # <class 'str'>
|
|
MATH AND STRING OPERATORS |
|
Ex. 1.2 | Math operators. |
Add 'a' to 'b', multiply by 'c' and divide by 'd' (result should be 10.0). |
|
a = 5 # int, 5
b = 10 # int, 10
c = 2 # int, 2
d = 3 # int, 3
x = a + b # int, 15
y = x * c # int, 30
z = y / d # float, 10.0
print(z)
|
|
note you could also do the work in one statement, but must use parentheses to get the correct result:
a = 5 # int, 5
b = 10 # int, 10
c = 2 # int, 2
d = 3 # int, 3
z = (a + b) * c / d # float, 10.0
print(z)
|
|
Note that the result is a float because any division operation results in a float, even if there is no remainder. |
|
Ex. 1.3 | Exponentiation operator. |
Use '**' to raise a to the power of b (result should be 125). |
|
a = 5 # int, 5
b = 3 # int, 3
c = a ** b # int, 125
print(c)
|
|
Ex. 1.4 | Concatenation operator. |
Use '+' to concatenate xvar, yvar and zvar together. |
|
xvar = 'supercali' # str, 'supercali'
yvar = 'fragilistic' # str, 'fragilistic'
zvar = 'expialidocious' # str, 'expialidocious'
s = xvar + yvar + zvar # str, 'supercalifragilisticexpialidocious'
print(s)
|
|
Ex. 1.5 | String repetition operator. |
Use '*' to repeat the string in greet 3 times to return a new str value yoyoyo. |
|
greet = 'yo' # str, 'yo'
y = greet * 3 # str, 'yoyoyo'
print(y)
|
|
LAB 1 |
|
Ex. 1.6 | Square a number. |
gg = 5 # int, 5
hh = gg ** 2 # int, 25
print(hh)
|
|
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. 1.7 | Multiply 2 numbers, then square the result. |
xx = 5 # int, 5
yy = 3 # int, 3
ww = xx * yy
zz = ww ** 2 # int, 225
print(zz)
|
|
Alternative solution, in one line:
xx = 5 # int, 5
yy = 3 # int, 3
zz = (xx * yy) ** 2 # int, 225
print(zz)
|
|
For the latter solution, we want to ensure that the multiplication operator is evaluated before the exponientation operator. If you are calculating both in the same statement, use parentheses to cause Python to evaluate the multiplication operation first. 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. 1.8 | Add two numbers together and then divide by 2. |
aa = 3 # int, 3
myb = 5 # int, 5
x = aa + myb
c = x / 2
print(c)
|
|
Alternatively, in one statement:
aa = 3 # int, 3
myb = 5 # int, 5
c = (aa + myb) / 2 # float, 4.0
print(c)
|
|
For the latter solution, consider that the division operator gets evaluated before the plus operator. If you are calculating both in the same statement, use parentheses to cause Python to evaluate the plus first. 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. 1.9 | Calculate a tip. With a bill of $100, 5 people in your party and a 20% tip, how much does each person owe? |
bill = 100 # int, 100
people = 5 # int, 5
tip_pct = 20 # int, 20
tip = bill * tip_pct * .01
total = bill + tip
share = total / people
print(share)
|
|
Alternative solution -- in one statement:
bill = 100 # int, 100
people = 5 # int, 5
tip_pct = 20 # int, 20
share = (bill + (bill * tip_pct * .01)) / people # float, 24.0
print(share)
|
|
For the latter solution, consider that the division operator gets evaluated before the plus operator. If you are calculating both in the same statement, use parentheses to cause Python to evaluate the plus first. 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. 1.10 | Concatenate strings together into a sentence. See if you can make the output look as expected. |
adjective = 'happy' # str, 'happy'
event = 'birthday' # str, 'birthday'
sen = adjective + ' ' + event # str, 'happy birthday'
print(sen)
|
|
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. 1.11 | Use the variable 'x' below to make a 40-character dotted line. |
x = '-' # str, '-'
y = x * 40 # str, '----------------------------------------'
print(y)
|
|
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. |
|
"PROCESSING" FUNCTIONS len() and round() |
|
Ex. 1.12 | Get the length of strings with len(). |
Print the length of each of the below strings. Both strings should be length of 11. |
|
x = 'hello there' # str, 'hello there'
y = 'hi ok ' # str, 'hi ok '
xlen = len(x) # int, 11
ylen = len(y) # int, 11
print(xlen)
print(ylen)
|
|
Ex. 1.13 | Round numbers with round(). |
Round the number to two places (43.99), and to an int (44). |
|
x = 43.986 # float, 43.986
x2 = round(x, 2) # float, 43.99
xi = round(x) # int, 44
print(x2)
print(xi)
|
|
"ACTION" FUNCTIONS input(), print(), exit() |
|
Ex. 1.14 | Take user input from the keyboard with input(). |
Take keyboard input with input(). Print the result and its type. |
|
ui = input('please enter: ') # str, 'hello' (sample input)
print(ui)
print(type(ui)) # <class 'str'>
|
|
Ex. 1.15 | Use exit() to terminate program execution. |
Imagine we want to test the value of mysum without seeing 'program continues...' (which represents the rest of the code executing). Insert a print() statement and exit() so that the program prints mysum and nothing further. |
|
mysum = (5 + 15) * 3
print(mysum)
exit()
print('program continues...')
|
|
Note that in Jupyter Notebook, the notebook will not exit, but will show that exit() has been called. exit() is more appropriate for standalone programs. |
|
"TYPE CONVERSION" FUNCTIONS INT, FLOAT, STR |
|
Ex. 1.16 | int(), float() and str() functions. |
Convert the below string to an integer, then double the value (to 106). Convert this value to a float (106.0) and convert that value to a string. Retrieve and print the length of this string (should be 5). |
|
zzy = '53' # str, '53'
zi = int(zzy) # int, 53
zd = zi * 2 # int, 106
zdf = float(zd) # float, 106.0
zdfs = str(zdf) # str, '106.0'
print(len(zdfs)) # int, 5
|
|
Ex. 1.17 | Erroneously using built-in names as variables. |
Demo: run this program. Note that the length of the name name is 5 (the length of 'Guido'). Next, add a new int variable: len = 5. Following this, attempt to determine the length of name a second time. What happens? |
|
name = 'Guido'
print(len(name)) # 5
len = 100
print(len(name)) # TypeError: 'int' object is not callable
|
|
Following the assignment of the int variable len the call to the built-in function len() fails, because the name len has been reassigned. (The error "'int' object is not callable" results because python attempts to call (i.e., with parentheses) the len variable, which is now an int). It may seem curious that Python even allows this assignment to a built-in name, but it does! (The reason has to do with the Python designers' desire to provide a uniform set of rules for all names -- any name can be reassigned at any point in a program.) Therefore assignment to any built-in name should be avoided. Other built-in names that should be avoided are int, float and str: these names should not be used for new variables. |
|
REPLICATING CODE EXAMPLES |
|
Ex. 1.18 | Replicating code examples (1/2). |
Review pythonreference.com for the function len(). Use len() to check the length of the variable sentence (length should be 3). Next, use len() to check the length of the literal string value 'sentence' (length should be 8). |
|
sentence = 'hi!' # str, 'hi!'
x = len(sentence) # int, 3
print(x)
y = len('sentence') # int, 8
print(y)
|
|
Please note that variable sentence (no quotes) is entirely different from string 'sentence' (with quotes). A word without quotes is a variable (a value assigned to a name). A word with quotes around it is a string literal (a literal string value). |
|
Ex. 1.19 | Replicating code examples (2/2). |
Review pythonreference.com for the function round(). Perform operations listed below: |
|
myfloat = 3.927 # float, 3.927
# round myfloat to 2 decimal places (should be 3.93).
x = round(myfloat, 2) # float, 3.93
print(x)
# round myfloat to 0 places (i.e., to produce an integer - should be 4)
y = round(myfloat) # int, 4
print(y)
|
|
LAB 2 |
|
Ex. 1.20 | Get the character length of the preamble to the constitution. |
preamble = """We the People of the United States, in Order to form a more
perfect Union, establish Justice, insure domestic Tranquility, provide for
the common defense, promote the general Welfare, and secure the Blessings
of Liberty to ourselves and our Posterity, do ordain and establish
this Constitution for the United States of America."""
pl = len(preamble) # int, 327
print(pl)
|
|
Ex. 1.21 | Divide integers 5 by 3 and round the result to 2 places. |
xx = 5 # int, 5
goofy = 3 # int, 3
gg = xx / goofy # float, 1.6666666666666667
print(round(gg, 2)) # float, 1.67
|
|
Ex. 1.22 | Take input for name and print 'hello, [name]!'. |
name = input('please enter your name: ') # str, 'David' (sample input)
print('hello, ' + name + '!') # hello, David!
|
|
Ex. 1.23 | Take input and print the user's value 3 times as a single string. |
val = input('please type anything: ') # str, 'spam' (sample input)
print(val * 3) # spamspamspam
|
|
Ex. 1.24 | Take input for a number and double it. |
x = input('please enter a number: ') # str, '10' (sample value)
xi = int(x) # int, 10
print(xi * 2) # int, 20
|
|
Ex. 1.25 | Get the length of 1000000. |
n = 1000000 # int, 1000000
sn = str(n) # str, '1000000'
snl = len(sn) # int, 7
print(snl)
|
|
Ex. 1.26 | Take two integers and concatenate them as string values. |
xx = 65 # int, 65
yy = 43 # int, 43
xxs = str(xx) # str, '65'
xxy = str(yy) # str, '43'
print(xxs + xxy)
|
|
Ex. 1.27 | Take an integer and repeat it three times as a string value. |
yxy = 500 # int, 500
syxy = str(yxy) # str, '500'
print(syxy * 3) # str, '500500500'
|
|
Ex. 1.28 | Take string input for a float value and round it as a float. |
ui = input('please enter a floating-point number: ') # str, '3.926' (sample value)
fui = float(ui) # float, 3.926
rfui = round(fui, 2) # float, 3.23
print(rfui)
|
|