Python程序设计(第3版) - 学习笔记_第二章

本博客主要为了学习Python使用,若有错误欢迎指正。

1. 混沌模型:输入中的非常小的变化导致结果的大变化,使其随机或不可预测。   

# File: chaos.py
# A simple program show Chaotic model

print("This program show a chaos function.")
x=eval(input("Enter a number between 0 to 1: "))
for i in range(10):
    x = 3.9 * x * (1 - x)
    print(x)
  

代码具体意义将在下方统一描述。

2. 编写简单程序

    创建程序过程分为几个阶段:

    分析问题,确定规格说明,创建设计,实现设计,测试调试程序,维护程序

    通过书上例子-温度转换器程序进行讲解

    分析问题:给你的温度为摄氏度,但是你需要知道温度的华氏度表示方式。

    确定规格说明:程序以摄氏度为输入,以华氏度为输出。

    创建设计:华氏度=9/5*摄氏度+32

    实现程序,测试调试即可。

# File: convert.py
# A program to convert Celsius temps to Fahrenheit

def main():
    c = eval(input(What is the Celsius temperature? ))
    f = 9.0 / 5.0 * c + 32.0
    printf("The Fahrenheit is ",f)

main()

    3. 注意事项

    Python标识符构成:以字母和下划线开头,后跟字母、数字、下划线,区分大小写(和C语言一致)

    Python提供 “连接”操作:直接连接两段字符串,例如 “你好”+“李华”=“你好李华”

    Python输入: input-eval 组合,功能过于强大,存在代码注入等危害

                           一般采用 input-int,input-float 组合等等

    Python输出:print(<expr>,<expr>,end="\n")  end="\n"为默认形式可进行重载修改

    Python赋值:存在 同时赋值方式:a, b=x+y, x-y 同时赋值有时候能避免擦除原始值

    Python-range(num)函数:产生一系列数字,从0到num-1

    Python-range(num,end)函数:产生一系列数字,从num到end-1

    Python-range(num,end,step)函数:产生一系列数字,从num到end-1,每次加上step

4. for 循环运用

# File: futval.py
# A program to compute the value of an investment 
# carried 10 years into the future

def main():
    print("This program calculates the future value of a 10-year investment.")
    principal = eval(input("Enter the initial principal: "))
    apr = eval(input("Enter the annual interest rate: "))
    for i in range(10):
        principal = principal * (1 + apr)
    print("The value in 10 years is: ",principal)

main()
    

    

猜你喜欢

转载自blog.csdn.net/SMyName/article/details/81584541