News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

2024-11(6)

挑战14天学完Python----初识计算思维

posted on 2023-06-03 20:40     read(762)     comment(0)     like(21)     collect(3)


previous articles

Challenge to finish learning Python in 14 days - first knowledge of Python syntax

Challenge to finish learning Python in 14 days----beginner python basic graphics drawing

Please add a picture description

foreword

This chapter will start with two examples: "Power Up Every Day" and "Text Progress Bar", to learn the operation of numeric types, string types and operations, and the use of the very important time library in Python.

1. An example of "Power Up Every Day"

In 1951, Chairman Mao Zedong wrote an inscription "study hard and make progress every day", which became a classic phrase that inspired generations of Chinese people to work hard. So how powerful is the power of "upward every day"? Below we will use a Python program to calculate the power of upward every day.

Question 1: The strength of daily progress is
1% 365 days a year, based on the ability value of the first day, recorded as 1.0, when studying hard, the ability value increases by 0.1% compared to the previous day, and when there is no learning, the ability value is compared to It had fallen 0.1 percent the previous day. . What is the difference in ability value between working hard every day and letting go every day for a year?

demand analysis

  • Mathematical formulas can be solved, it seems that there is no need to use programs?
  • What if it is "three days of fishing and two days of drying the net"?
  • What if it is "weekends without going backwards"?

According to the topic, the code is as follows:

0.1%. The power is nearly doubled, so don't underestimate it

Question two: 5%. And 1% power
365 days a year, 0.5% progress every day. Or 1%, how much is the cumulative progress?
365 days a year, 0.5% regress every day. Or 1%, how much is left?
In question 2, we add a variable dayFactor, the advantage of using variables: one modification, available everywhere

0.5% power:
1% power:

0.5%. The power, amazing!
1% power, amazing!
Question 3: The power of working days
365 days a year, 5 working days a week, 1% progress every day
365 days a year, 2 rest days a week, 1% back every day
this How about the power of a working day?
We use a cycle to simulate 365 days of process abstraction + automation.


In this code, we *abandoned mathematical thinking and introduced computational thinking,Computational thinking is the result of a combination of abstraction and automation
Abstraction: formalized logic of abstract problems
Automation: automatic realization of abstract results through programs

Question 4: Efforts on working days
How hard should the workday model be to be the same as 1% every day?
Mr. A: 365 days a year, 1% improvement every day, non-stop
Mr. B: 365 days a year, work every week 5 days off, 2 days off, 1% drop on rest days, how hard should I work?

# DayDayUp4.py
def dayUp(df):
    dayup = 1
    for i in range(365):
        if i % 7 in [6, 0]:
            dayup = dayup * (1 - 0.01)
        else:
            dayup = dayup * (1 + df)
        return dayup
dayFactor = 0.01
while dayUp(dayFactor) < 37.78:
    dayFactor += 0.001
print("工作日的努力参数是:{:.3f}".format(dayFactor))

Although the example only contains 8-12 lines of code, it contains many grammatical elements Conditional loops, counting loops, branches, functions, computational thinking Clear understanding of these codes can quickly get started with the Python language

2. Numerical operations

2.1 Numeric Operators

An operator is a symbolic system for performing operations.


Binary operators have corresponding enhanced assignment operators.

The relationship between digital types: mixed operations can be performed between types, and the result is the "widest" type
There is a gradually "expand" or "broaden" relationship among the three types
Integer -> Float -> Complex
For example: 123 + 4.0 = 127.0 (Integer + Float = Float)

2.2 Numerical operation functions

Some numerical arithmetic functions provided as functions


Note: z in pow(x,y[,z]) can ensure that the result range is always kept within the range calculated by the computer

Before knocking on the "text progress bar", let's learn some knowledge about strings and time libraries in order to better understand the code.

3. String type operations

3.1 Special characters in strings

Escapes\

  • The escape character expresses the original meaning of a specific character
    "here is a double quote (")" and the result is a double quote (") here
  • Escape characters form some combinations to express some non-printable meanings
    "\b" back n "new line (move the cursor to the beginning of the next line) r" car (move the cursor to the beginning of the line)

3.2 String operators

An ordered character sequence consisting of 0 or more characters

An example: get a week string
Input: an integer from 1 to 7, indicating the day of the week
Output: input a corresponding week string Example: input 3, output Wednesday

3.3 String processing functions

String processing capabilities provided as functions

3.4 Unicode encoding

Unicode编码Python字符串的编码方式
Unicode编码是Python的统一字符编码,即覆盖几乎所有字符的编码方式从0到1114111(0x10FFFF)空间,每个编码对应一个字符
Python字符串中每个字符都是Unicode编码字符
在Python中,数字、标点符号、汉字、字母都是一个字符

Unicode编码的一些有趣的例子

3.5 字符串处理方法

一些以方法形式提供的字符串处理功能

insert image description here

3.5 字符串类型的格式化

格式化是对字符串进行格式表达的方式

字符串格式化使用.format0方法,用法如下:

<模板字符串>.format(<逗号分隔的参数>)

图示:
insert image description here

format()方法的格式控制----槽内部对格式化的配置方式

{<参数序号> : <格式控制标记>}

举一些例子说明他们的使用:


槽格式控制 填充 对其 宽度

:b 二进制形式输出
:c 以字符形式(Unicode的编码形式)输出
:d 以十进制形式输出
: o 以八进制形式输出
:x 以十六进制形式输出
:X 以大写十六进制形式输出

编写模板字符串判断浮点类型的输出方式
:e 采用科学计数法e形式表现浮点数
:E 采用科学计数法E形式表现浮点数
:f 指的是以通常的非科学计数法形式表示浮点数
:% 百分号形式表示浮点数

4. time库的使用

time库是Python中处理时间的标准库
它可以:
计算机时间的表达
提供获取系统时间并格式化输出功能
提供系统级精确计时功能,用于程序性能分析

time的引用使用方式:
import time
time.()

4.1 time库的三类函数

  • 时间获取: time() ctime() gmtime()
    insert image description here
  • 时间格式化: strftime() strptime()
    将时间以合理的方式展示出来
    格式化:类似字符串格式化,需要有展示模板
    展示模板由特定的格式化控制符组成
    strftime()方法
    insert image description here
    ts变量是指在gmtime函数中输出的格式
    tpl定义了输出效果

    格式化控制符

    举个例子
  • 程序计时: sleep(),perf_counter()
    程序计时指测量起止动作所经历时间的过程
    测量时间: perf_counter0)
    产生时间 : sleep0)

5."文本进度条"实例分析

进度条是计算机处理任务或执行软件中常用的增强用户体验的重要手段,它能够实时显示任务或软件的执行进度。接下来我们将利用 Python字符串处理方法实现文本进度条功能。

需求分析:
采用字符串方式打印可以动态变化的文本进度条
进度条需要能在一行中逐渐变化
刷新的原理是后面更新的内容覆盖前面的内容

问题分析:
如何获得文本进度条的变化时间?
采用sleep0模拟一个持续的进度

  • 方法一:
    最简单的方法,但不能实现单行刷新
# TextProBarQ1.py
import time
scale = 10
print("------执行开始------")
for i in range(scale+1):
    a = '*' * i
    b = '.' * (scale - i)
    c = (i/scale)*100
    print("{:^3.0f}%[{}->{}]".format(c, a, b))
    time.sleep(0.1)
print("------执行结束------")

  • 方法二:
    实现单行刷新
    刷新的关键是\r
    刷新的本质是: 用之后打印的字符覆盖之前的字符
    不能换行: print()需要被控制
    要能回退: 打印后光标退回到之前的位置 \r
    代码如下:
# TextProBarQ2.py
import time
for i in range(101):
    print("\r{:3}%".format(i), end="")
    time.sleep(0.1)

如图我们可以看到动态效果;

是不是还挺好玩的呢23333……

  • 方法三:
    较复杂的一个方法,具有格式框架,有进度’*'输出,又有时间记录的完整进度条.
# TextProBarQ3.py
import time
scale = 50
print("执行开始".center(scale//2, "-"))
start = time.perf_counter()
for i in range(scale+1):
    a = '*'*i
    b = '.'*(scale - i)
    c = (i/scale)*100
    dur = time.perf_counter() - start
    print("\r{:^3.0f}[{}->{}]{:.2f}s".format(c, a, b, dur), end='')
    time.sleep(0.1)
print("\n"+"执行结束".center(scale//2, '-'))

代码解析:
.center方法将"-"字符填充在"执行开始"和"执行结束"字符串的两侧,perf_counter函数计时,dur记录每一次打印文本进度条需要的时间,\r实现光标向行首移动,end参数赋值为空字符使得每次输出后不换行.

\r和end详解:
因为

  • input获得的输入会被保存为字符串类型
  • print输出函数后会默认换行到下一行

所以我们要使用\r和end参数

  • \r 在打印字符串信息之前,使光标退回到当前行的行首
  • end print()函数的一个参数,默认情况下不增加,指的是输出信息后,默认在最后增加一个换行换到下一行.但如果在**输出信息之后,增加",end="这样一个参数,它就能改变print输出最后增加的信息.**比如,我们将end赋值为空字符串,那么print每一次输出字符串后它都不会增加换行,它自会把光标停留在当初输出字符串的后面.




Category of website: technical article > Blog

Author:Poison

link:http://www.pythonblackhole.com/blog/article/78469/a43b701aa18a29f05388/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

21 0
collect article
collected

Comment content: (supports up to 255 characters)