笨办法学python习题9-20

习题九:打印2.0
代码截图

运行结果

·python"""允许一个字符串跨越多行,字符串中可以包含换行符、制表符以及其他特殊字符
·三引号的语法是一对连续的单引号或者双引号(通常都是成对的用)
·"""还可以用来多行注释

习题10:习题九扩展
代码截图

运行结果

https://www.cnblogs.com/zzdbullet/p/10025301.html
·在不使用三个双引号的时候,可以在每一行的末尾添加\来实现分行,但是输出时依旧显示为连接为一行的字符串,无法实现一行一个输出

习题11:输入
代码截图

运行结果

·在前三行的输出后面都加end=''来告诉print函数不要用换行符结束这一行
·input函数用来从控制台输入一个字符串,输入的字符串会返回一个变量,当遇到input的时候会阻塞程序的运行,只有输入内容回车之后可执行
·如何读取用户输入的数字并进行数学计算?可以用x = int(input()),它会从print函数获取用户输入的字符串形式的数值,然后用int强转

习题12:提示别人
代码截图

运行结果

·键入input()函数时,可以让它显示一个提示符(比如你想要作为提示的字符串),从而告诉别人应该输入什么东西
·pydoc命令https://www.cnblogs.com/jackzz/p/10718934.html

习题13:参数、解包和变量
代码截图

运行结果

·当仅仅使用命令python zwj.py时Windows Power Shell返回错误:ValueError: not enough values to unpack (expected 4, got 1)
此时未定义足够的参数,修改命令为之后发现命令将参数传递给变量,四个变量均正常输出
·sys为内置模块,当执行import sys之后,python在sys.path变量中所列目录中寻找sys模块文件,运行sys模块在主块中的语句进行初始化即可使用
https://www.runoob.com/python3/python3-module.html
如果传递的参数个数大于定义的变量个数则Windows Power Shell返回错误:

argv传递的命令行参数与input一样,均为字符串,如果涉及到数字运算则需要类型强转

习题14:提示与传递
代码截图

运行结果

·将input的用户提示符设置为变量prompt,这样就不需要每次在用到input时反复输入

习题15:读取文件
代码截图

运行结果

·read命令会接受一个参数,并且返回一个file对象,可以将这个值赋给一个变量,这就是打开文件的过程
尝试在使用close函数关闭文件之后再使用tell函数尝试计算文件的字节值,观察是否能正常计算
错误提示

调整之后正常运行

习题16:读写文件
·close:关闭文件,保存
·read:读取文件内容,将结果赋值给一个变量
·readline:只读取文本文件中的一行
·truncate:清空文件,请小心使用
·write('stuff'):将'stuff'写入文件
·seek(0):将读写位置移动到文件开头
代码展示

from sys import argv
script,filename = argv

print(f"We're going to erase {filename}.")
print("If you don't want that,hit CTRL-c(`C).")
print("If you do want that,hit RETURN.")

input("?")

print("Opening the file...")
target = open(filename,'w')

print("Truncating the file.GoodBye!")
target.truncate()#清空文件

print("Now I'm going to ask you for three lines.")
line1 = input("line1:")
line2 = input("line2:")
line3 = input("line3:")

print("I'm going to write these to the file.")
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()

运行结果

巩固练习:尝试用一个target.write()将line1、line2、line3打印出来
将原来的6行target.write()代码改为target.write(f"{line1}\n{line2}\n{line3}\n")
https://www.runoob.com/python/python-file-write.html
w-写,r-读,a-追加,open函数还有一个+修饰符,可用来修饰前三种模式,实现文件同时用读写模式打开,且r为open函数的默认行为

习题17:更多文件操作
代码展示

from sys import argv
from os.path import exists

script,from_file,to_file = argv

print(f"Coping from {from_file} to {to_file}.")
#we could do these two on one line,how?
in_file = open(from_file)
indata = in_file.read()

print(f"The input file is {len(indata)} bytes long")

print(f"Does thr output file exist?{exists(to_file)}")
print("Ready,hit RETURN to continue,CTRL-C to abort.")
input()

out_file = open(to_file,'w')
out_file.write(indata)

print("Alright,all done.")

out_file.close()
in_file.close()

运行结果

·导入命令exists,这个命令将文件名字符串作为参数,如果文件存在则返回True,否则返回False,通过from os.path import exists导入
·用echo创建了文件,又用cat命令显示了文件内容
·由运行结果可知,出现错误提示:
Coping from test.txt to new-file.txt.
Traceback (most recent call last):
File "E:\My-python\17.py", line 9, in
indata = in_file.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence
https://blog.csdn.net/mighty13/article/details/107132272/
https://www.cnblogs.com/ohlala/p/11394503.html
百度可知这是由于打开的文件编码格式不正确,将第8行代码修改如下:

结果显示程序正常运行

习题18:命名、变量、代码和函数
代码展示:

#this one is like your scripts with argv
def print_two(*args):
    arg1,arg2 = args
    print(f"arg1:{arg1},arg2:{arg2}")

#ok,that *args is artually pointless,we can just do this
def print_two_again(arg1,arg2):
    print(f"arg1:{arg1},arg2:{arg2}")

#this just takes one arguments
def print_one(arg1):
    print(f"arg1:{arg1}")

#this one takes no arguments
def print_none():
    print("I gor nothjng!")

print_two("Zwj","Yang")
print_two_again("Zwj","Yang")
print_one("First!")
print_none()

运行结果

·使用def命令创建/定义一个函数,函数命名由字母数字和下划线组成,且不能以数字开头
·args的:告诉python将函数的所有参数都接收进来,然后放到名叫args的参数列表里面去,和之前习题中一直用的argv有点类似

习题19:函数和变量
代码展示

def cheese_and_crackers(cheese_count,boxes_of_crackers):
    print(f"You have {cheese_count} cheeses!")
    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_crackers = 50

cheese_and_crackers(amount_of_cheese,amount_of_crackers)

print("We can even do math inside too:")
cheese_and_crackers(10+20,5+6)

print("And we can combine the two,variables and math:")
cheese_and_crackers(amount_of_cheese + 100,amount_of_crackers + 1000)

运行结果

习题20:函数和文件
代码展示

from sys import argv

script, input_file = argv

def print_all(f):
    print(f.read())

def rewind(f) :
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file,encoding='utf-8',errors = 'ignore')

print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")

rewind(current_file)

print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

运行结果

·python文件seek函数详解
·seek()方法用于移动文件读取指针到指定位置,每次运行seek(0)就回到了文件的开始,seek()函数的处理对象是字节而非行
·运行f.readline()则会读取文件的一行,realine()里面的代码会扫描文件的每一个字节,直到找到一个\n为止,然后它停止读取文件,并且返回此前发现的文件内容,文件f会记录每次调用readline()后的读取位置,这样它就可以在下次被调用时读取接下来的一行了
·为什么文件里会有间隔空行
read()函数返回的内容中包含文件本来就有的\n,而print函数打印的时候又会添加\n,这样以来就会多出一个空行,解决办法是在print函数中添加一个参数end="",这样就u不会出现多余的\n

posted @ 2020-10-29 14:46  20209135张文锦  阅读(108)  评论(0)    收藏  举报