# Practice Exercises for Functions

# Solve each of the practice exercises below. 

# 1.Write a Python function miles_to_feet that takes a parameter miles and
# returns the number of feet in miles miles.
def miles_to_feet(miles):
feet = miles * 5280
return feet print(miles_to_feet(2.5))
print('=====') # 2.Write a Python function total_seconds that takes three parameters hours, minutes and seconds and
# returns the total number of seconds for hours hours, minutes minutes and seconds seconds.
def total_seconds(hours, minutes, seconds):
total = hours * 60 * 60 + minutes * 60 + seconds
return total print(total_seconds(1, 5, 10))
print('=====') # 3.Write a Python function rectangle_perimeter that takes two parameters width and height
# corresponding to the lengths of the sides of a rectangle and
# returns the perimeter of the rectangle in inches.
def rectangle_perimeter(width, height):
perimeter = (width + height) * 2
return perimeter print(rectangle_perimeter(2.3, 2.2))
print('=====') # 4.Write a Python function rectangle_area that takes two parameters width and height
# corresponding to the lengths of the sides of a rectangle and
# returns the area of the rectangle in square inches.
def rectangle_area(width, height):
area = width * height
return area print(rectangle_area(2, 5))
print('=====') # 5.Write a Python function circle_circumference that takes a single parameter radius
# corresponding to the radius of a circle in inches and
# returns the the circumference of a circle with radius radius in inches.
# Do not use π=3.14, instead use the math module to supply a higher-precision approximation to π.
import math
def circle_circumference(radius):
circumference = 2.0 * radius * math.pi
return circumference print(circle_circumference(4.0))
print('=====') # 6.Write a Python function circle_area that takes a single parameter radius
# corresponding to the radius of a circle in inches and
# returns the the area of a circle with radius radius in square inches.
# Do not use π=3.14, instead use the math module to supply a higher-precision approximation to π.
def circle_area(radius):
area = radius * radius * math.pi
return area print(circle_area(4.0))
print('=====') # 7.Write a Python function future_value that takes three parameters present_value, annual_rate and years and
# returns the future value of present_value dollars invested at annual_rate percent interest,
# compounded annually for years years.
def future_value(present_value, annual_rate, years):
value = present_value * pow(annual_rate + 1.0, years)
return value print(future_value(1000000.0, 0.03, 10))
print('=====') # 8.Write a Python function name_tag that takes as input the parameters first_name and last_name (strings) and
# returns a string of the form "My name is % %." where the percents are the strings first_name and last_name.
# Reference the test cases in the provided template for an exact description of
# the format of the returned string.
def name_tag(first_name, last_name):
form = "My name is %s %s." % (first_name, last_name)
return form print(name_tag('Bob', 'Smith'))
print('=====') # 9.Write a Python function name_and_age that takes as input the parameters name (a string) and age (a number) and
# returns a string of the form "% is % years old." where the percents are the string forms of name and age.
# Reference the test cases in the provided template for an exact description of
# the format of the returned string.
def name_and_age(name, age):
form = "%s is %d years old." % (name, age)
return form print(name_and_age('John', 24))
print('=====') # 10.Write a Python function point_distance that takes as the parameters x0, y0, x1 and y1, and
# returns the distance between the points (x0,y0) and (x1,y1).
def point_distance(x0, y0, x1, y1):
distance = math.sqrt((x0 - x1)**2 + (y0 - y1)**2)
return distance print(point_distance(0, 0.5, -2.2, 3.5))
print('=====') # 11.Challenge: Write a Python function triangle_area that takes the parameters x0, y0, x1,y1, x2, and y2, and
# returns the area of the triangle with vertices (x0,y0), (x1,y1) and (x2,y2).
# (Hint: use the function point_distance as a helper function and apply Heron's formula.)
def triangle_area(x0, y0, x1, y1, x2, y2):
side1 = point_distance(x0, y0, x1, y1)
side2 = point_distance(x1, y1, x2, y2)
side3 = point_distance(x2, y2, x0, y0)
area = heron_formula(side1, side2, side3)
return area # 海伦公式
def heron_formula(side1, side2, side3):
p = (side1 + side2 + side3) / 2.0
area = math.sqrt(p * (p - side1) * (p - side2) * (p - side3))
return area print(triangle_area(0, 0.5, -2.2, 3.5, -3, -2.5))
print('=====') # 12.Challenge: Write a Python function print_digits that takes an integer number in the range [0,100),
# i.e., at least 0, but less than 100. It prints the message "The tens digit is %, and the ones digit is %.",
# where the percent signs should be replaced with the appropriate values.
# (Hint: Use the arithmetic operators for integer division // and remainder % to find the two digits.
# Note that this function should print the desired message, rather than returning it as a string.
def print_digits(number):
tens, ones = number // 10, number % 10
message = "The tens digit is %d, and the ones digit is %d." % (tens, ones)
print(message) print_digits(49)
print('=====') # 13.Challenge: Powerball is lottery game in which 6 numbers are drawn at random.
# Players can purchase a lottery ticket with a specific number combination and,
# if the number on the ticket matches the numbers generated in a random drawing,
# the player wins a massive jackpot. Write a Python function powerball that takes no arguments and
# prints the message "Today's numbers are %, %, %, %, and %. The Powerball number is %.".
# The first five numbers should be random integers in the range [1,60), i.e., at least 1,
# but less than 60. In reality, these five numbers must all be distinct, but for this problem,
# we will allow duplicates. The Powerball number is a random integer in the range [1,36),
# i.e., at least 1 but less than 36. Use the random module and the function random.randrange to
# generate the appropriate random numbers.Note that this function should print the desired message,
# rather than returning it as a string.
import random
def powerball():
ball1, ball2, ball3, ball4, ball5 = random.sample(range(1,60), 5)
ball6 = random.choice(range(1, 36))
message = "Today's numbers are %d, %d, %d, %d, and %d. The Powerball number is %d." % (ball1, ball2, ball3, ball4, ball5, ball6)
print(message) powerball()
powerball()
print('=====')

An Introduction to Interactive Programming in Python (Part 1) -- Week 2_1 练习的更多相关文章

  1. An Introduction to Interactive Programming in Python (Part 1) -- Week 2_3 练习

    Mini-project description - Rock-paper-scissors-lizard-Spock Rock-paper-scissors is a hand game that ...

  2. An Introduction to Interactive Programming in Python

    这是在coursera上面的一门学习pyhton的基础课程,由RICE的四位老师主讲.生动有趣,一共是9周的课程,每一周都会有一个小游戏,经历一遍,对编程会产生很大的兴趣. 所有的程序全部在老师开发的 ...

  3. Mini-project # 1 - Rock-paper-scissors-___An Introduction to Interactive Programming in Python"RICE"

    Mini-project description - Rock-paper-scissors-lizard-Spock Rock-paper-scissors is a hand game that ...

  4. An Introduction to Interactive Programming in Python (Part 1) -- Week 2_2 练习

    #Practice Exercises for Logic and Conditionals # Solve each of the practice exercises below. # 1.Wri ...

  5. 【python】An Introduction to Interactive Programming in Python(week two)

    This is a note for https://class.coursera.org/interactivepython-005 In week two, I have learned: 1.e ...

  6. Quiz 6b Question 8————An Introduction to Interactive Programming in Python

     Question 8 We can use loops to simulate natural processes over time. Write a program that calcula ...

  7. Quiz 6b Question 7————An Introduction to Interactive Programming in Python

     Question 7 Convert the following English description into code. Initialize n to be 1000. Initiali ...

  8. Quiz 6a Question 7————An Introduction to Interactive Programming in Python

     First, complete the following class definition: class BankAccount: def __init__(self, initial_bal ...

  9. Mini-project # 4 - "Pong"___An Introduction to Interactive Programming in Python"RICE"

    Mini-project #4 - "Pong" In this project, we will build a version of Pong, one of the firs ...

随机推荐

  1. 关于C语言中单双引号的问题

    代码 #include<stdio.h> int main() { if ( "{" =='{' ) printf("True\n"); else ...

  2. MongoDB学习笔记——MongoDB 连接配置

    MongoDB连接标准格式: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[dat ...

  3. 问题解决——基于MSCOMM32.OCX控件的类在客户机不能创建控件

    大家不要笑我了,我不喜欢用那个人家写的串口类. 所以导出了MSCOMM32.OCX的类,然后在此基础上写了一个串口打印机的小工具类. -------------声明--------------- 本文 ...

  4. ubuntu创建、删除文件及文件夹方法

    mkdir 目录名         => 创建一个目录 rmdir 空目录名      => 删除一个空目录 rm 文件名 文件名   => 删除一个文件或多个文件 rm –rf 非 ...

  5. 烂泥:ubuntu安装KVM虚拟机管理virt-manager

    本文由秀依林枫提供友情赞助,首发于烂泥行天下. 打算学习KVM的图形界面管理器virt-manager,但是virt-manager只有linux系统的,没有windows下的.所以只能使用linux ...

  6. 有关Azure存储帐号监视器中的度量值

    在一次故障排错中,发现存储帐号监视器里'成功百分比'(该度量值的源选择的是blob)这个度量值始终是低于100%.引出几个问题: 1. 这个度量值所代表的意义? A: 存储基于REST协议,对服务的访 ...

  7. matlab中subplot函数的功能

    转载自http://wenku.baidu.com/link?url=UkbSbQd3cxpT7sFrDw7_BO8zJDCUvPKrmsrbITk-7n7fP8g0Vhvq3QTC0DrwwrXfa ...

  8. 计算机中的颜色XIV——快速变换颜色的V分量

    基本知识回顾: 计算机中的颜色Color,用RGB模式存储(用R.G.B三个分量表示颜色,每个分量的范围是0—255). 而计算机中的颜色除了用RGB模式表示以外,常见的还有HSV模式(或者是HSB. ...

  9. selenium操作滚动条的几种方式

    1.操作滚动条到当前可见视图的元素位置 WebElement element = dr.findElement(By.id("4")); ((JavascriptExecutor) ...

  10. javascript判断回文数

    "回文"是指正读反读都能读通的句子,它是古今中外都有的一种修辞方式和文字游戏,如"我为人人,人人为我"等.在数学中也有这样一类数字有这样的特征,成为回文数(pa ...