cpsc111-Su16-Lab2_withAnswer.docx - CPSC111 Introduction to...

This preview shows page 1 - 3 out of 6 pages.

CPSC111 - Introduction to ComputingSummer 2016Lab2 – Practice with PythonLAB MARK: 20 / 25Today's lab exercise provides practice with selection (if) and repetition (for, while) in Python as well as practicing with evaluating numerical expressions and forming numeric expressions in Python. You will work with a partner on this Lab2. Two students should work at a single computer. Occasionally switch the student who is typing. Talk to each other about what you are doing and why so that both of you understand each step. The first thing to do is to create a folder with the name Lab2.Part A: Forming numeric expressionsConvert each of the following mathematical formulas into assignment statements in Python. For each formula, replace the single-letter variable names (traditional in mathematics) into more readable whole-word names in the assignment statement. For example, the formula that gives thevolume v of a cylinder of length l and cross-sectional radius r is:This formula can be represented as the following assignment statementa)The following formula gives the surface area of a cube of side-length l :can be represented as the assignment statement:b)The following formula gives the volume v of a sphere of radius r :can be represented as the assignment statement:pg. 1/ am/cpsc111-Su16-Lab2.docximport matharea = 6 * lengthimport mathvolume = float(4/3) * math.pi * radius**3import mathvolume = length * math.pi * radius ** 2
c)The following formula gives the radius r of a sphere, given that the surface area of the sphere is a :can be represented as the assignment statement:Part B: while and if statementsAs we have seen in lectures, the (if)statement is used to choose between alternatives while (for and while) statements are used to repeatedly execute blocks of statements.The for statement is most useful when you know exactly how many times you want to repeatedlydo something (for example, you know how many sides of a polygon you want to draw). Here is an example showing how to print something times:n = 3for i in range(n):  print("Hello!")Here is the corresponding output:Hello!Hello!Hello!The while statement is most useful when you don’t know in advance how many times the

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture