Introduction to Python

davidbpython.com




In-Class Exercise Solutions, Session 2



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. 2.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. 2.2 Math operators.

Add 'a' to 'b', muliply 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. 2.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. 2.4 Modulus operator.

Determine whether the following numbers are odd or even. Use modulus % to see if there is a remainder from dividing by 2.

odd = 5
even = 8

print(odd % 2)   # 1 (remainder of division)

print(even % 2)  # 0 (no remainder)
 
 
Ex. 2.5 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. 2.6 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. 2.7 Square a number.
gg = 5              # int, 5

hh = gg ** 2        # int, 25
print(hh)
 
Ex. 2.8 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.

 
Ex. 2.9 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.

 
Ex. 2.10 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.

 
Ex. 2.11 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)
 
Ex. 2.12 Use the variable 'x' below to make a 40-character dotted line.
x = '-'           # str, '-'

y = x * 40        # str, '----------------------------------------'
print(y)
 

"PROCESSING" FUNCTIONS len() and round()

 
Ex. 2.13 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. 2.14 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. 2.15 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. 2.16 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...')
 

"TYPE CONVERSION" FUNCTIONS INT, FLOAT, STR

 
Ex. 2.17 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
 

REPLICATING CODE EXAMPLES

 
Ex. 2.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. 2.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. 2.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. 2.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. 2.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. 2.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. 2.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. 2.25 Get the length of 1000000.
n = 1000000          # int, 1000000

sn = str(n)          # str, '1000000'
snl = len(sn)        # int, 7

print(snl)
 
Ex. 2.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. 2.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. 2.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)
 
[pr]