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

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 world
Is it over yet?
Goodbye cruel world!
  • (CHECKED)
Hello world
Is it over yet?
Hello world
Is 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 - 47
print 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)**periods

print "$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.83480113
745.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 math
def 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 b

def 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 * scale

project-to-distance(2, 7, 4)
import math

def 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 * scale

project_to_distance(2, 7, 4)

1.09888451159 3.84609579056

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

# Rock-paper-scissors-lizard-Spock template
import 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 functions

def 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:', name


def 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:', number


def 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 CODE
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")

# always remember to check your completed program against the grading rubric

-eof-

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python交互式编程入门》是一门介绍如何使用Python进行交互式编程的课程。在这门课程中,学习者将学习如何使用Python编写简单的程序并与之进行交互。 首先,课程将介绍Python的基本语法和编程概念。学习者将学习如何定义变量、使用条件语句和循环、编写函数以及处理列表和字典等数据结构。 接下来,课程将介绍Python交互式编程的概念。学习者将学习如何使用Python的交互式命令行界面进行编程,并了解如何与Python解释器进行交互。他们将学习如何编写单行和多行的Python代码,并立即查看结果。 在这门课程中,学习者还将学习如何使用Python编写简单的图形用户界面(GUI)应用程序。他们将学习如何使用Python的GUI库来创建窗口、按钮、文本框等界面元素,并学习如何为这些元素添加交互功能。 此外,课程还将涵盖一些常见的Python编程任务,如文件操作、网络编程和数据可视化。通过这些任务的实践,学习者将能够更好地理解Python交互式编程的应用。 该课程注重实践,学习者将通过编写小型项目和解决编程问题来应用所学知识。他们将有机会与其他学习者一起合作,分享代码和解决方案,并从其他人的经验中学习。 总之,《Python交互式编程入门》是一门适合初学者的课程,它将帮助学习者掌握Python编程的基本概念和技能,并提供实践经验和项目练习。通过这门课程的学习,学习者将能够熟练地运用Python进行交互式编程,并在日后的编程任务中受益。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值