2021-10-16


官网
国内相关贴子

安装Python与编译器*

  • 查看之前安装的python的版本号
  • python --version
  • 查看python 安装目录
python 
import sys
sys.path
  • Pycharm 对代码进行多行注释
  • Ctrl +/
    如何给Pycharm加上头行 # *coding:utf-8 *

File->Setting->Editor->Code Style->File and Code Templates->Python Script 后面加上 # *coding:utf-8 * 即可
在这里插入图片描述

练习3 数字和数学

+ plus,加号
- minus,减号
/ slash,斜杠
* asterisk,星号
% percent,百分号
< less-than,小于号
> greater-than,大于号
<= less-than-equal,小于等于号
>= greater-than-equal,大于等于号

练习5 更多的变量和打印

my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = "White"
my_hair = "Brown"
 
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print("He's ",round(weight/2.20,2), "kg heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on the coffee.")
 
# this line is tricky, try get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

知识点总结

  1. round()函数用于取小数点后的位数,用法round(数值,保留小数位)
  2. 其他取浮点类型小数点后位数的方法见 练习11

练习 6 字符串和文本

# -*- coding:utf-8 -*-
'''练习6'''
types_of_people = 10         # 定义一个变量并赋值
x = f"There are {types_of_people} types of people "
# 定义变量x,并在赋值时引用另一个变量且使用.format()函数使其能被其他函数引用

binary = "binary"       # 为 binary 赋值
do_not="don't"          # 为do_not赋值
y = f"Those who know {binary} and those who {do_not}."
# 为变量"y" 赋值时引用"binary","do_not"且用.format()函数使能被其他函数引用
print(x)  #打印变量'x'的值
print(y)   #打印变量'y"的值

print(f"I said:{x}")
print(f"I also said: '{y}'")

hilarious = False
Joke_evaluation = "Isn't that joke so funny?!{}"
w = "This is the left side of..."
e = "a string with a right side."

print(w + e)

知识点总结:
1.当为一个变量赋值,且希望之后可以引用它,可以用.format()函数;
2.当一个新的变量引用之前的变量时,使用{};

练习 7 更多打印

'''练习7'''
print("Mary had a little lamb.")
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("."* 10) # what"d that do ?   答:打印10个"."
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
#watch that comma at the end. try removeing it to see what h
print(end1 + end2 + end3 + end4 + end5 +end6,end= ' ' )
print(end7 + end8 + end9 + end10 + end11 +end12)

知识点总结:

  1. ".format()“函数有两种格式:
x = f("test1")
y = test 2 {x}test3 
y=("test2{}test2”.format('test1'))	 
  1. 字符串也可以用 算数符号“*”,“+” 连接

练习8 打印 + ".format()"函数

'''练习8'''

formatter = "{}{}{}{}"
print(formatter.format(1,2,3,4))
print(formatter.format("one,","two,","three,","four"))
print(formatter.format(True,False,False,True))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format(
    "Try your\n",
    "Own tex here\n",
    "Maybe a poem\n",
    "Or a song about fear"
))

知识总结:见练习6

练习10 转义符

'''练习10'''
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line."
backslash_cat = "I'm \\ a \\ cat."
fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* Grass
"""

print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

知识点总结:

  1. 在特殊符号前加转义符"",使其成为普通字符
  2. 打印时可以用"""开始,"""结尾,进行段落打印,
    print(""" 也是一种转义字符""")

练习11 "input()"函数

'''练习11'''
print("How old are you?")
age = input()
print("How tall are you ?")

height = input()
print("How much do you weigh?")
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")

在这里插入图片描述
在这里插入图片描述
知识点总结:
print("一串字符串",end=' ') 时,打印结果与input内容在同一行换行,
print("一串字符串")时,打印结果换行后再进行input

'''练习11'''
age = input ("How old are you?")
height = input("How tall ara you?")
weight = input("How much do you weigh?")
F = f"So,you're {age} old,{height} tall and {weight} heavy."
print(F)

可以直接在函数input() 中输入提醒,同时将输入的值赋予一个函数;
如果想用输入的值做数学运算,可以使用"int"整形函数或其他类型的函数将输入字符变为数字,例:

x = int(input("请输入一个整形数值"))
y = float(input("请输入一个小数"))
print("他们的乘积为{:.3f}".format(x*y))

P= x*y
print("他们的乘积为%.2f" %P)

注:注意以上代码中指定浮点函数输出小数点后位数的方式有两种

练习12 pydoc 的作用

附加练习
在 Terminal 里输入 pydoc input ,看看它会说什么。如果你用的是 Windows, 输入 python3.6 -m pydoc input 。
输入 q ,退出 pydoc 。
到网上查查 pydoc 命令的作用。
用 pydoc 读一读关于 open,file,os,和 sys 的内容;浏览一遍即可,把有意思的东西记下来。

答:pydoc 用于以获取内置函数的帮助信息
input函数 网上解读

(venv) I:\LPHW>python -m pydoc input
Help on built-in function input in module builtins:
#关于内置模块中input函数的帮助:
input(prompt=None, /)
#input()函数默认提示字符串为空
    Read a string from standard input.  The trailing newline is stripped.
#从标准输入读取一个字符,尾部换行符默认剥离(意思就是不换行直接开始读取输入,跟下一段描述对应)。
    The prompt string, if given, is printed to standard output without a
    #如果给了提示符input("提示符"),会先输出一行提示,然后换行开始读取输入。
    trailing newline before reading input.

    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.
#在input读取输入时如果读到用户在输入EOF则会发生EOF错误(系统快捷键,*nix: Ctrl-D, Windows: Ctrl-Z+Return);
#(EOF为End Of File的缩写,通常在文本的最后存在此字符表示资料结束。)*
# 在*nix 系统上,如果允许,可以使用readline。(这句我理解有问题,目前不知道怎么解释) 

open 函数 网上解读

(venv) I:\LPHW>python -m pydoc open
Help on built-in function open in module io:
# 关于内置函数open()的帮助信息:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
#open()函数的参数格式。
    Open file and return a stream.  Raise OSError upon failure.
	# 打开文件并返回一个信息,如果失败会返回系统错误。
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    #file 是给出要打开文件的描述符,可以是文本,字符串或文件的绝对路径,如果I/O返回值为False,说明给出的描述符不存在。
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    # mode 是一个可选的字符串,可以指定文件以哪一种方式打开,默认值为'r',这种方法是打开并读取文本内容。
    #其他常见的值"w" 是只写(如果文件已存在,则将文件重写覆盖。truncating:截断),
#'x'是创建和写一个新的文件,'a'是在文本内追加内容(一些Unix系统,不管当前指定的位置在哪,都会把内容写入文件末尾)
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
#在文本中进行mode(读,写等),如果编码方式没有指定,则优先选择当前系统依赖的系统环境进行编码。
#(读写原始字节使用二进制编码)可用的模式有:
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
              #只读,不指定时默认
    'w'       open for writing, truncating the file first
    		  #写入,并覆盖原文件
    'x'       create a new file and open it for writing
              #创建一个文件并写入
    'a'       open for writing, appending to the end of the file if it exists
              #如果文件存在,在文件末尾追加内容
    'b'       binary mode
              #二进制模式
    't'       text mode (default)
              #文本模式(默认)
    '+'       open a disk file for updating (reading and writing)
    		  #打开磁盘文件进行跟新(读写)
    'U'       universal newline mode (deprecated)
              #通用换行模式(不推荐)
    ========= ===============================================================

    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    # 默认的mode 是 "rt"(打开并读取文本)。对于二进制随机模式,'w+b'会覆盖文件从0bytes开始写,而'r+b'不会。
    #'x'模式,如果文件已经存在会报`FileExistsError`这个信息。
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
# 用python打开文件会主动区分二进制文件和文本文件,即使底层操作系统没有区分。
#当打开二进制文件时,会将'b'附加到mode参数,返回内容为没有任何解码的字节。
#当打开文本文件时,默认将't'附加到mod参数,
文件内容以字符串的形式返回,并如果没有指定编码方式,则首先使用平台默认的编码方式。
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
#'U'模式已经弃用,在python3中没有效果
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
# buffering 是可选参数,用于设置缓冲策略(只在二进制下有效),
#如果 buffering 的值被设为 0,(只在二进制下生效)就不会有寄存。如果 buffering 的值取 1,
#(在文本文件中生效)访问文件时会寄存行。如果将 buffering 的值设为大于 1 的整数,表明了这就是的寄存区的缓冲大小。
#如果取负值,寄存区的缓冲大小则为系统默认。

    * Binary files are buffered in fixed-size chunks; the size of the buffer
    #在系统中二进制文件缓冲区是在底层系统上的固定大小的缓冲块中读取的
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
       # 尝试向底层设备向底层设备发送信号'block size',并返回'io.DEFALT_BUFFER_SIZE'(默认缓冲块大小).
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
      #许多系统的缓冲区通常是4096或8192字节大小
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    #交互式文本文件使用isatty()方法 返回True
    .........

练习12 参数,解包,变量

from sys import argv
# read te WYSS section for how to run this

script,first,second,third= argv

print("The script is called:",script)
print("your first variable is:",first)
print("your second variable is:",second)
print("your third variable is:",third)

直接运行这个脚本会报错
在这里插入图片描述
因为需要你提前输入参数,供脚本读取,脚本中的变量有4个所以需要输入4个参数,
当前只能读到"day2.py,所以报错信息说:ValueError:没有足够的值来解包(预期为 4,得到 1)"

正确方式为在"day2.py" 后面输入三个参数,并用空格隔开:
在这里插入图片描述

练习14

练习15

# -*- coding:utf-8 -*-
from sys import argv #引用sys模块中的argv函数
script,filename = argv #获取取两个值到argv变量,如果获取的值不是两个,就报错
# 输入值后scrip=ex15.py,filename=ex15_samle.txt

txt = open(filename)      # 打开已经获取到的文件ex15_samle.txt
print(f"Here's your file {filename}:") # 打印fielname,当前filename=ex15_samle.txt
print(txt.read()) #读取txt文件,当前txt=open(ex15_samle.txt)

print("Type the filename again:") #重新打印提示
file_again = input(">")  # input 获取文件名,输入为ex15_samle.txt

txt_again = open(file_again) # 打开输入的文件当前file_again=ex15_samle.txt

print(txt_again.read()) # 打印读取到的文件内容,ex15_samle.txt

练习16 读写文件

  • close - 关闭文件,就像编辑器中的 “文件->另存为”一样。
  • read - 读取文件内容。你可以把读取结果赋给一个变量。
  • readline - 只读取文本文件的一行内容。
  • truncate - 清空文件。清空的时候要当心。(***truncate() 方法***
    )
  • write(‘stuff’) - 给文件写入一些“东西”。
  • seek(0) - 把读/写的位置移到文件最开头
# -*- coding:utf-8 -*-

from sys import argv
#引用sys模块中的argv函数,argv=参数

script,filename = argv      # 脚本运行前读取两个参数

print(f"We're going to erase {filename}.")          # 打印提醒: 将要擦除 {文件名}.
print("If you don't wat that ,hit CTRL -C (^C).") # 打印提醒: 如果不这么做,输入CTRL+C 退出
print("If you do want that,hit RETURN.")            # 打印提醒: 如果要这么做,点击返回


input("?")                                             # 读取动作
target = open(filename,'w')                           # 打开 filename,并进行写的动作(当前filename=运行脚本时输入的第二个参数)

print("Truncating the file, Goodbye!")           # 打印提示
target.truncate()                                     # 截断,默认为size

print("Now I'm going to ask you for three lines.")

target.write('line1')
target.write("\n")
target.write('line2')
target.write("\n")
target.write('line3')
target.write("\n")

print("And finally,we close it.")
target.close()

from sys import argv

script,red_filename = argv

RD = open(red_filename,encoding='utf-8',mode='r') # 当open()有多个参数时,必须写明参数类型
print(RD.read())

总结:

练习17 更多文件 (exists函数与文件copy)

# -*- coding:utf-8 -*-
from sys import  argv
from os.path import exists
# exists 函数判断输入的路径是否存在,如果存在,不管时文件或者路径,都返回True,否则返回False。
script,from_file,to_file = argv
print(f"Copying from {from_file} to {to_file}")
#告知将要把from_file 的内容拷贝到to_file
# We could do these two on one line,how?

in_file = open(from_file) #打开from_file
indata = in_file.read()# 读取from_file 的内容

print(f"The input file is {len(indata)} bytes long") #打印from_file 内容的字节长度
print(f"Does the output file exist? {exists(to_file)}")# 查找是否存在to_file这个文件
print("Ready,hit RETURN to continue, CTRL-C to abort.")#选择继续或者推出
input()                     # 从交互界面接受输入字符串

out_file = open(to_file,'w') # 打开to_file,并进行写的动作
out_file.write(indata)   # 将 from_file 的内容写入 to_file
print("Alright,all done.") # 打印已经完成所有
out_file.close()   #关闭to_file
in_file.close()    #关闭from_file

总结
exists 函数判断输入的路径是否存在,如果存在,不管时文件或者路径,都返回True,否则返回False。

练习 18 函数

#-*- encoding=utf-8 -*-

# this one is like your scripts with argv
def print_two(*args):     # 定义函数print_two,未知参数个数,用占位符*args
    arg1, arg2 = args     # 参数为两个字符串arg1,args
    print(f"arg1: {arg1}, arg2: {arg2}")   #函数内容为:打印字符串

# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):    # 定义函数print_two_again,已知参数为两个,分别用占位符arg1,arg2表示
    print(f"arg1: {arg1}, arg2: {arg2}") # 函数内容为:打印字符串

# this just takes one argument
def print_one(arg1):   #定义函数print_one,参数为一个,用占位符arg1
   print(f"arg1: {arg1}")     #函数内容为:打印字符串

# this one takes no arguments
def print_none():        #定义无参数的函数,调用时直接执行函数内容
	print("I got nothin'.") #函数内容为打印字符串


print_two("Zed","Shaw")        # 调用函数print_two,输入两个参数
print_two_again("Zed","Shaw") #调用函数print_tow_again,输入两个参数
print_one("First!")			#调用函数print_one,输入一个参数
print_none()				#调用无参数函数

知识点总结:
1.定义函数:

def 定义函数名(参数):
        *#如果需要调用多个参数,用占位符(*argv)占用参数位置
        如果已知函数需要调用几个变量,就用几个占位符,占位符用","隔开
        如果不需要调用变量,则函数名后的()中为空。*
        函数内容

附加联系

#-*- encoding=utf-8 -*-
#一个列表,用于检查创建函数的步骤是否正确
def check_list(args):
	print(f"checklist\n")
	print(f"1.你是否用 def 来创建函数了?\n")
	print(f"2.你的函数名是只包含字符和 _ (下划线)吗?\n")
	print(f"3.你在函数名后面放 ( (左圆括号)了吗?\n")
	print(f"4.你在左圆括号后面放参数(argument)了吗?参数之间是以逗号隔开的吗?)\n")
	print(f"5.你的每个参数都是唯一的吗(即没有重名)?\n")
	print(f"6.你在参数后面放 ) (右圆括号)和 : (冒号)了吗?\n")
	print(f"7.你在与这个函数相关的代码行前面加上四个空格的缩进了吗?(不能多,也不能少)\n")
	print(f"8.你是通过另起一行不缩进来结束你的函数的吗?\n")
	
#一个列表,用于检查调用函数的步骤是否正确
def run_def(arg):
	print(f"run_def_list\n")
	print(f"1.你是通过输入函数名称来运行/调用/使用一个函数的吗?\n")
	print(f"2.你运行的时候有在名称后面加 ( 吗?\n")
	print(f"3.你有把你想要的值放在圆括号里并用逗号隔开了吗?\n")
	print(f"4.你是以 ) 来结束调用这个函数的吗?\n")

#调用以上两个函数
check_list("call")
run_def("call")

练习19 函数和变量

#-*-encoding=utf-8-*-

#定义函数cheese_and_crackers,调用时输入两个参数
def cheese_and_crackers(cheese_count,boxes_of_crackers):  
	# 打印“你有{cheese_count}奶酪”
	print(f"You have {cheese_count} cheeses!")   
	# 打印“你有{boxes_of_crackers}盒饼干”
	print(f"You have {boxes_of_crackers}boxes of crackers")
	print("Man that's enough for a party")
	print("Get a blanket.\n")
	
	
print("We can just give the function numbers directly:")
cheese_and_crackers(20,30)  #调用函数,并输入两个参数
print("OR, we can use variables from our script:")
amount_of_cheese = 10   #为变量  amount_of_cheese 赋值  
amount_of_crackers = 50 #为变量 amount_of_crackers赋值

cheese_and_crackers(amount_of_cheese, amount_of_crackers) # 调用函数并将刚才赋值的变量作为参数输入

print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)   # 调用函数并输入参数,参数为 10+20的和与5+6的和

print("And we can combine the two, variables and math:")
# 调用函数,并输入参数,参数为amount_of_cheese + 100,amount_of_crackers + 1000
#即:10+100,50+1000    即(110,1050)
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) 

练习21 函数的返回值

def add(a,b):
	print(f"ADDING{a}+{b}")
	return a+b	
def subtract(a,b):
	print(f"SUBTRACTING{a}-{b}")
	return a - b 
	
def multiply(a,b):
	print(f"MULTIPLYING {a}*{b}")
	return a*b
	
	
def divide(a,b):
	print(f"DIVIDING{a}/{b}")
	return a / b

print("Let's do some math whith just functions!")	

age = add(30,5)

height = subtract(78,4)

weight = multiply(90,2)
iq = divide(100,2)

print(f"Age:{age},Height(height),Weight:{weight},IQ:{iq}")

# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what,"\nCan you do it by hand?")

知识点总结
1、函数 return 可以返回到对应公式的值,调用函数后,打印出来的结果是 return 后的值

2、return 就像一个过程,执行后面的公式,只不过没打印,使用时直接加公式即可

3、函数内部可以调用函数,顺序是从内向外执行的,当函数执行到return后,跳出函数,函数结束。但将return语句放在try语句块中,是个例外。

习题23 编码与解码

开始前请下载:languages.txt点开,右键,“另存为” txt 格式,放在你的练习文件夹,再打开。

import sys
script, encoding, error = sys.argv


def main(language_file, encoding, errors):
    line = language_file.readline()

    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)


def print_line(line, encoding,errors):
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors = errors)
    cooked_string = raw_bytes.decode(encoding, errors = errors)

    print(raw_bytes, "<==>", cooked_string)


languages = open("languages.txt", encoding = "utf-8")

main(languages, encoding, error)

知识点总结
1、编码可以理解成把字符转换成计算机语言(数字),解码就是逆转换

2、pen(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
file = “文件名”,mode=‘模式(r,w)’,encoding=编码方式(utf-8,ASCII等)

3、read 读取整个文件,readline 读取一行,readlines 读取全部拆成一行的列表

4、encode和decode都是(编码格式,错误的处理方法)

练习 25 更多练习

def break_words(stuff):
	"""This function will break up words for us."""
	words = stuff.split(' ') # 以空格' '将句子分解为单词(切片)
	return words

def sort_words(words):
    """Sorts the words."""
    # sorted(iterable, cmp=None, key=None, reverse=False) ,iterable是迭代对象
    # 对所有字符串进行迭代排序(reverse = True是降序 ,False是升序(默认))
    return sorted(words) 
def print_first_word(words):
    """Prints the first word after popping it off."""
    # 移除列表中的一个元素(默认最后一个元素,即:words.pop(-1)),并且返回该元素的值,words.pop(0)表示移除words中第0个。;
    word = words.pop(0)
    print(word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    #移除列表中的最后一个元素,并返回该元素的值
    word = words.pop(-1)
    print(word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words"""
    #引用break_words()函数对句子切片之后,再引用sort_words函数,进行排序。
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    # 引用break_words()函数,对句子切片,并删除第一个元素与最后一个元素
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    # 引用sort_sentence()函数,对句子进行切片排序,并删除第一个元素与最后一个元素
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

知识点总结

  1. 可以用 import 导入脚本
  2. .split() 函数用于切片,参数为间隔符,如:以空格为间隔符切片
>>> words = "All good things come to those who wait."
>>> words.split(' ')
输出结果为:
>>> ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
  1. .pop()函数,用于移除列表中的一个元素(默认最后一个元素,即:words.pop(-1)),并且返回该元素的值,words.pop(0)表示移除words中第0个。
  2. sorted()函数用于对所有字符串进行迭代排序
    格式:sorted(iterable, cmp=None, key=None, reverse=False) ,iterable是迭代对象(reverse = True是降序 ,False是升序(默认))

练习 26 测试

源脚本文件:
官方下载 exercise26.txt文件

排错过程:

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 5
    weight = input()
    ^
SyntaxError: invalid syntax
# 1.报错第5行,无效的语法(其实是4行print()缺少一个')').

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 23
    print('Let's practice everything.')
               ^
SyntaxError: invalid syntax
# 2.语法错误,Let's 的"'" 需要转义符,应为print('Let\'s practice everything.')或print("Let's practice everything.")
┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 24
    print('You\'d need to know \'bout escapes
                                              ^
SyntaxError: EOL while scanning string literal
# 3.ecapes 是EOF字符串,需要转译为普通字符串,"\secapes"

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 35
    print("--------------)
  # 4.缺少 ' " '                       ^
SyntaxError: EOL while scanning string literal

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 40
    five = 10 - 2 + 3 -
                        ^
SyntaxError: invalid syntax
# 5.缺少数字

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 43
    def secret_formula(started)
    ^
SyntaxError: invalid syntax
# 6.定义函数名称后需要跟 ':'

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 46
    crates = jars  100
                   ^
SyntaxError: invalid syntax
#7.缺少运算符,此处为除 '/'

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 73
    print "Too many cats! The world is doomed!"
          ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Too many cats! The world is doomed!")?
# 8.报错信息完整,应为print("Too many cats! The world is doomed!")

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 81
    if people > dogs
                    ^
SyntaxError: invalid syntax
# 9.缺少 ':'

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 90
    if people <= dogs
                     ^
SyntaxError: invalid syntax
# 10.缺少 ':'

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 91
    print("People are less than or equal to dogs.)
                                                  ^
SyntaxError: EOL while scanning string literal
# 11.缺少 ' " '

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
  File "/home/sxf/ex26.py", line 94
    if people = dogs:
              ^
SyntaxError: invalid syntax
#12.此处不应赋值,应为相等,相等的符号为'=='

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
How old are you? 31
How tall are you? How much do you weigh? 170  56
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 6, in <module>
    print(f"So, you're {age} old, {height} tall and {weight} heavy.")
NameError: name 'height' is not defined
# 13.未找到变量,检查代码发现缺少该变量,进行添加

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
How old are you? 31
How tall are you? How much do you weigh? ^CTraceback (most recent call last):
  File "/home/sxf/ex26.py", line 5, in <module>
    print("How much do you weigh?", end=' ')
KeyboardInterrupt
#14.缺少 ' " '

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 9, in <module>
    script, filename = argv
NameError: name 'argv' is not defined
# 15.未找到 'argv',检查代码发现未引用sys.argv 模块,进行引用

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 12, in <module>
    txt = open(filenme)
NameError: name 'filenme' is not defined
#16.未找到对应变量,检查发现该处字符串拼写错误,应为"filename"

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your file {filename}:
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 15, in <module>
    print(tx.read())
NameError: name 'tx' is not defined
# 17.拼写错误,应为print(txt.read())


┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your file {filename}:

Type the filename again:
> test.txt
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 22, in <module>
    print(txt_again_read())
NameError: name 'txt_again_read' is not defined
# 18.语法错误,应为 print(txt_again.read())

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your filetest.txt:

Type the filename again:
> test.txt

Let's practice everything.
You'd need to know 'bout \escape
 swith \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 53, in <module>
    beans, jars = secret_formula(start_point)
ValueError: too many values to unpack (expected 2)
# 19.参数数量错误,检查发现缺少函数,进行添加,并去掉空格,
#应为: beans,jars,crates = secret_formula(start_point)

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your file test.txt:

Type the filename again:
> test.txt

Let's practice everything.
You'd need to know 'bout \escape
 swith \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.
We can also do that this way:
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 63, in <module>
    formula = secret_formula(startpoint)
NameError: name 'startpoint' is not defined
# 20.拼写错误,应为'start_point' 

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your file test.txt:

Type the filename again:
> test.txt

Let's practice everything.
You'd need to know 'bout \escape
 swith \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.
We can also do that this way:
We'd have 500000.0 beans, 500.0 jars, and 5.0 crates.
Traceback (most recent call last):
  File "/home/sxf/ex26.py", line 74, in <module>
    if people < cats:
NameError: name 'cats' is not defined
#21.22.拼写错误,变量名应为'cates'

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─# python3 ex26.py test.txt
How old are you? 31
How tall are you? 170
How much do you weigh? 56
So, you're 31 old, 170 tall and 56 heavy.
Here's your file test.txt:

Type the filename again:
> test.txt

Let's practice everything.
You'd need to know 'bout \escape
 swith \ that do
 newlines and    tabs.
--------------

        The lovely world
with logic so firmly planted
cannot discern
 the needs of love
nor comprehend passion from intuition
and requires an explanation

                where there is none.

--------------
This should be five: 5
With a starting point of: 10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates.
We can also do that this way:
We'd have 500000.0 beans, 500.0 jars, and 5.0 crates.
Too many cats! The world is doomed!
Not many cats! The world is saved!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

┌──(root💀LAPTOP-M307CQ78)-[/home/sxf]
└─#

修改之后的代码

from sys import argv
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weigh?", end=' ')
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")

script, filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())


print('Let\'s practice everything.')
print("""You\'d need to know \'bout \escape\n swith \\ that do \n newlines and \t tabs.""")

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""

print("--------------")
print(poem)
print("--------------")


five = 10 - 2 + 3 - 6
print(f"This should be five: {five}")

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans / 1000
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans,jars,crates = secret_formula(start_point)

# remember that this is another way to format a string
print("With a starting point of: {}".format(start_point))
# it's just like with an f"" string
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10

print("We can also do that this way:")
formula = secret_formula(start_point)
# this is an easy way to apply a list to a format string
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))



people = 20
cates = 30
dogs = 15


if people < cates:
    print("Too many cats! The world is doomed!")

if people < cates:
    print("Not many cats! The world is saved!")

if people < dogs:
    print("The world is drooled on!")

if people > dogs:
    print("The world is dry!")


dogs += 5

if people >= dogs:
    print("People are greater than or equal to dogs.")

if people <= dogs:
    print("People are less than or equal to dogs.")


if people == dogs:
    print("People are dogs.")

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值