zoukankan      html  css  js  c++  java
  • 《Python核心编程》第二版第36页第二章练习 续一 Python核心编程答案自己做的

    2-6.
    条件判断。判断一个数是正数还是负数,或者是0。开始先用固定的数值,然后修改你的代码支持用户输入数值再进行判断。
    【答案】
    代码如下:
    a = float(raw_input("Please input a number ... "))
    if a == 0:
        print "The number you input is Zero"
    elif a > 0:
        print "The number you input is Positive"
    else:
        print "This is a negative number"

    2-7.
    循环和字串。从用户那里接受一个字符串输入,然后逐字符显示该字符串。先用while循环实现,然后再用for循环实现。
    【答案】
    代码如下:
    a = raw_input("Please input a string ... ")
    print 'Display in for loop:'
    for i in a:
        print i,
    print '\nDisplay in while loop:'
    j = 0
    while (j < len(a)):
        print a[j]
        j = j + 1

    2-8.
    循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的和。然后修改你的代码为接受用户输入数值。分别使用while和for循环实现。
    【答案】
    代码如下:
    # Using while loop
    i = 0
    total = 0
    a = [1, 2, 3, 4, 5]
    while (i < 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
        i = i + 1
    print 'The total is', total

    # Using for loop
    total = 0
    a = [1, 2, 3, 4, 5]
    for i in range(0, 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
    print 'The total is', total

    2-9.
    循环和操作符。创建一个包含五个固定数值的列表或元组,输出他们的平均值。本练习的难点之一是通过除法得到平均值。你会发现整型除会截去小数,因此你必须使用浮点除以得到更精确的结果。float()内建函数可以帮助你实现这一功能。
    【答案】
    代码如下:
    i = 0
    total = 0
    a = [1, 2, 3, 4, 5]
    while (i < 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
        i = i + 1
    print 'The average is', total / 5.

    # Using for loop
    total = 0
    a = [1, 2, 3, 4, 5]
    for i in range(0, 5):
        print 'Please input number', i+1
        a[i] = float(raw_input())
        total = total + a[i]
    print 'The average is', total / 5.

    2-10.
    带循环和条件判断的用户输入。使用raw_input()函数来提示用户输入一个1和100之间的数,如果用户输入的数值满足这个条件,显示成功并退出。否则显示一个错误信息然后再次提示用户输入数值,直到满足条件为止。
    【答案】
    代码如下:
    t = 1
    while (t):
        a = float(raw_input('Please input a number between 1 and 100: ... '))
        if a < 100 and a > 1:
            print 'Your have input a number between 1 and 100.'
            t = 0
        else:
            print 'Please try again ...'
    【未完】这里并没有检查输入不是数字的情况。

    这里列出的答案不是来自官方资源,是我自己做的练习,可能有误。

  • 相关阅读:
    相机标定 和 单应性矩阵H
    全景视频拼接关键技术
    OpenCV图像变换(仿射变换与透视变换)
    用非数学语言讲解贝叶斯定理
    (二)SMO算法
    (一)SVM原理
    什么是赋范线性空间、内积空间,度量空间,希尔伯特空间
    决策树算法(五)——处理一些特殊的分类
    V8学习资源
    perforce 学习资源
  • 原文地址:https://www.cnblogs.com/balian/p/1933418.html
Copyright © 2011-2022 走看看