An Introduction to Interactive Programming in Python (Part 1) - Week 1

来源:互联网 发布:文明太空mac版 编辑:程序博客网 时间:2024/05/21 14:08

Quiz 1

1.

An if statement can have at most how many else parts?

  • 0
  • (CHECKED) 1
  • Unlimited, i.e., 0 or more

2.

Consider the Boolean expression not (p or not q). Give the four following values in order, separated only by spaces:

the value of the expression when p is True, and q is True,
the value of the expression when p is True, and q is False,
the value of the expression when p is False, and q is True,
the value of the expression when p is False, and q is False,

Remember, each of the four results you provide should be True or False with the proper capitalization.

False False True False

3.

A common error for beginning programmers is to confuse the behavior of print statements and return statements.

  • print statements can appear anywhere in your program and print a specified value(s) in the console. Note that execution of your Python program continues onward to the following statement. Remember that executing a print statement inside a function definition does not return a value from the function.
  • return statements appear inside functions. The value associated with the return statement is substituted for the expression that called the function. Note that executing a return statement terminates execution of the function definition immediately. Any statements in the function definition following the return statement are ignored. Execution of your Python code resumes with the execution of the statement after the function call.

As an example to illustrate these points, consider the following piece of code:

def do_stuff():    print "Hello world"    return "Is it over yet?"    print "Goodbye cruel world!"print do_stuff()

Note that this code calls the function do_stuff in the last print statement. The definition of do_stuff includes two print statements and one return statement.

Which of the following is the console output that results from executing this piece of code? While it is trivial to solve this question by cutting and pasting this code into CodeSkulptor, we suggest that you first attempt this problem by attempting to execute this code in your mind.

Hello world
Hello worldIs it over yet?Goodbye cruel world!
  • (CHECKED)
Hello worldIs it over yet?
Hello worldIs it over yet?Goodbye cruel world!Is it over yet?

4.

Given a non-negative integer n, which of the following expressions computes the ten’s digit of n? For example, if n is 123, then we want the expression to evaluate to 2.

Think about each expression mathematically, but also try each in CodeSkulptor.

  • (CHECKED) (n % 100 - n % 10) / 10
  • (CHECKED) ((n - n % 10) % 100) / 10
  • (n - n % 10) / 10

5.

The function calls random.randint(0, 10) and random.randrange(0, 10) generate random numbers in different ranges. What number can be generated by one of these functions, but not the other?

(Refer to the CodeSkulptor documentation.)

By the way, we (and most Python programmers) always prefer to use random.randrange() since it handles numerical ranges in a way that is more consistent with the rest of Python.

10

6.

Implement the mathematical function f(x)=-5x^5+69x^2-47 as a Python function. Then use Python to compute the function values f(0), f(1), f(2), and f(3). Enter the maximum of these four values calculated.

def f(x):    return (-5)*x**5 + 69*x**2 - 47print f(0),f(1),f(2),f(3)-47 17 69 -641
69

7.

When investing money, an important concept to know is compound interest.

The equation FV=PV(1+rate)^periods relates the following four quantities.

The present value (PV) of your money is how much money you have now.
The future value (FV) of your money is how much money you will have in the future.
The nominal interest rate per period (rate) is how much interest you earn during a particular length of time, before accounting for compounding. This is typically expressed as a percentage.
The number of periods (periods) is how many periods in the future this calculation is for.
Finish the following code, run it, and submit the printed number. Provide at least four digits of precision after the decimal point.

def future_value(present_value, annual_rate, periods_per_year, years):    rate_per_period = annual_rate / periods_per_year    periods = periods_per_year * years    # Put your code here.print "$1000 at 2% compounded daily for 3 years yields $", future_value(1000, .02, 365, 3)

Before submitting your answer, test your function on the following example.

future_value(500, .04, 10, 10) should return 745.317442824

def future_value(present_value, annual_rate, periods_per_year, years):    rate_per_period = annual_rate / periods_per_year    periods = periods_per_year * years    # Put your code here.    return present_value * (1.0+rate_per_period)**periodsprint "$1000 at 2% compounded daily for 3 years yields $", future_value(1000, .02, 365, 3)print future_value(500, .04, 10, 10)$1000 at 2% compounded daily for 3 years yields $ 1061.83480113745.317442824
1061.83480113

8.

There are several ways to calculate the area of a regular polygon. Given the number of sides, n, and the length of each side, s, the polygon’s area is

ns24tan(πn)

For example, a regular polygon with 5 sides, each of length 7 inches, has area 84.3033926289 square inches.

Write a function that calculates the area of a regular polygon, given the number of sides and length of each side. Submit the area of a regular polygon with 7 sides each of length 3 inches. Enter a number (and not the units) with at least four digits of precision after the decimal point.

Note that the use of inches as the unit of measurement in these examples is arbitrary. Python only keeps track of the numerical values, not the units.

import mathdef area(n, s):    return (n*s**2)/(4 * math.tan(math.pi/n))print area(5,7), area(7, 3)84.3033926289 32.705211996
32.705211996

9.

Running the following program results in the error

SyntaxError: bad input on line 8 (‘return’).

Which of the following describes the problem?

def max_of_2(a, b):    if a > b:        return a    else:        return bdef max_of_3(a, b, c):return max_of_2(a, max_of_2(b, c))
  • (CHECKED) Incorrect indentation
  • Missing colon
  • Wrong number of arguments in function call
  • Misspelled variable name
  • Misspelled keyword
  • Misspelled function name
  • Extra parenthesis
  • Missing parenthesis

10.

The following code has a number of syntactic errors in it. The intended math calculations are correct, so the only errors are syntactic. Fix the syntactic errors.

Once the code has been fully corrected, it should print out two numbers. The first should be 1.09888451159. Submit the second number printed in CodeSkulptor. Provide at least four digits of precision after the decimal point.

define project_to_distance(point_x point_y distance):    dist_to_origin = math.square_root(pointx ** 2 + pointy ** 2)     scale == distance / dist_to_origin    print point_x * scale, point_y * scaleproject-to-distance(2, 7, 4)
import mathdef project_to_distance(point_x, point_y, distance):    dist_to_origin = math.sqrt(point_x ** 2 + point_y ** 2)    scale = distance / dist_to_origin    print point_x * scale, point_y * scaleproject_to_distance(2, 7, 4)1.09888451159 3.84609579056

Mini-project #1 - Rock-paper-scissors-lizard-Spock

# Rock-paper-scissors-lizard-Spock templateimport random# The key idea of this program is to equate the strings# "rock", "paper", "scissors", "lizard", "Spock" to numbers# as follows:## 0 - rock# 1 - Spock# 2 - paper# 3 - lizard# 4 - scissors# helper functionsdef name_to_number(name):    # delete the following pass statement and fill in your code below    # convert name to number using if/elif/else    # don't forget to return the result!    if name == 'rock':        return 0    elif name == 'Spock':        return 1    elif name == 'paper':        return 2    elif name == 'lizard':        return 3    elif name == 'scissors':        return 4    else:        print 'incorrect name:', namedef number_to_name(number):    # delete the following pass statement and fill in your code below    # convert number to a name using if/elif/else    # don't forget to return the result!    if number == 0:        return 'rock'    elif number == 1:        return 'Spock'    elif number == 2:        return 'paper'    elif number == 3:        return 'lizard'    elif number == 4:        return 'scissors'    else:        print 'incorrect number:', numberdef rpsls(player_choice):     # delete the following pass statement and fill in your code below    # print a blank line to separate consecutive games    print    # print out the message for the player's choice    print 'Player chooses', player_choice    # convert the player's choice to player_number using the function name_to_number()    player_number = name_to_number(player_choice)    # compute random guess for comp_number using random.randrange()    comp_number = random.randrange(0,5)    # convert comp_number to comp_choice using the function number_to_name()    comp_choice = number_to_name(comp_number)    # print out the message for computer's choice    print 'Computer chooses', comp_choice    # compute difference of comp_number and player_number modulo five    diff = (comp_number-player_number) % 5    # use if/elif/else to determine winner, print winner message    if diff == 1 or diff == 2:        print 'Computer wins!'    elif diff == 3 or diff == 4:        print 'Player wins!'    else:        print 'Player and computer tie!'# test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODErpsls("rock")rpsls("Spock")rpsls("paper")rpsls("lizard")rpsls("scissors")# always remember to check your completed program against the grading rubric

-eof-

0 0
原创粉丝点击