Lab: Practice Problems

Getting reps with the fundamentals

Part I: Vars, expressions, arithmetic

Copy this into a Python file and add the specified code under each comment. For testing purposes, you can comment out working parts as you go (surround the lines with """).

# write Python code to...

# create a variable x, assign it the value 7, and print the variable's value

# create variables x and y, assign them the value 13 and -6, add them and print the sum

# create two variables and assign them a first and last name
# concatenate the names in the "Last, First" format and store that in another variable
# print the concatentated name

# get three numbers from the user and print the sum of them

# get four numbers from the user and print the average of them

# get two strings from the user, concatenate them around a colon (:), and print that
# e.g. the user types "cat" and "dog", the program prints "cat:dog"

# get a number of people from the user and print how many groups of 3 you could have
#  and how many people would be left over

      

Part II: Sequences

Copy this into a Python file and add the specified code under each comment. For testing purposes, you can comment out working parts as you go (surround the lines with """).

# write Python code to...

# get a string from the user and print its length

# create a list containing 4 real numbers (floats)
# print the whole list (on one line)

# create a list containing 4 whole numbers (integers)
# print the whole list, one line per number

# get a string from the user and print the number of 'x' characters in it

      

Lists have append() and extend() methods that strings do not, because strings are immutable. Since they are methods, you call them as shown below. Play around at the command prompt and confirm out what they do (relevant to the next part).


# assume you have a list variable called numbers

numbers.append(6)
numbers.extend([7,8])
      

Copy this into a Python file and add the specified code under each comment. For testing purposes, you can comment out working parts as you go (surround the lines with """).

# write Python code to...

# get 3 numbers from the user and store them in a list
# print the largest number in the list
# print the smallest number in the list

# create a list containing 4 real numbers (floats)
# get two more numbers from the user and append them to the end of the list

# create a list containing 4 real numbers (floats)
# copy it to another list, but omit any numbers less than 10