19.01.08python基础复习

习题三
数学和数学计算

  • 加减乘除号的应用
print("I will now count my chickens:")
#print Hens 25+30/6
print("Hens",25+30/6)
#print Rooster 100-25*3%4
print("Rooster",100-25*3%4)
print("Now I will count the eggs:")
#3+2+1-5+4%2-1/4+6
print(3+2+1-5+4%2-1/4+6)
#比较
print("Is it true that 3+2<5-7")
print(3+2<5-7)
print("what is 3+2?",3+2)
print("what is 5-7?",5-7)
print("oh,that's why it's False.")
print("How about some more")
print("Is it greater?",5>-2)
print("Is it greater or equal?",5>=-2)
print("Is it less or equal?",5<=-2)
`

习题四
变量和命名

  • 单等号=和==双等号
  • =的作用是将右边的值赋给左边的变量名。==的作用是检查作业两边的值是否相等。
cars = 100
space_in_a_car = 100
print("There are",cars,"cars avaiblable")
print("There are only",drivers,"drivers avaiblable")

习题5
更多的变量和打印
每一次用双引号“把文本括起来,就创建了一个字符串

  • format string格式化字符串
  • f"Hello {somevar}"
my_name = 'Baba liang'
my_age = 20
my_height = 63
my_weight = 170
my_eyes = 'Black'
my_teeth = 'white'
my_hair = 'Black'
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds 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")
total = my_age +my_height + my_weight
print(f"If I add {my_age},{my_height},and {my_weight}I get {total}")

习题6
字符串和文本

#定义一个变量
types_of_people = 10
#用format函数定义X
x = f"There are {types_of_people} types of people."
#定义两个变量
binary = "binary"
do_not = "don'todo"
#用format函数定义X,返回Those who know    and those who
y = f"Those who know {binary} and those who {do_not}."

print(x)
print(y)
print(f"I said :{x}")
print(f"I also said : '{y}'")
#
hilarious = "True"
joke_evaluation = "Isn't that joke so funny?!{}"

print (joke_evaluation.format(hilarious))

w = "This is the left side of..."
e = "a string with a right side"

print (w+e)

习题7
更多打印

print("Mary had a little lamb.")
#format函数的两种表现方式
#'snow'是字符串,不用定义
print("Its fleece was white as {}.".format('snow'))
print(f"Its fleece was white as {'snow'}.")
print("And everywhere that Mary went.")
print("."*10)#点乘10个

end1 = "B"
end2 = "B"
end3 = "L"
end4 = "z"
end5 = "u"
end6 = "i"
end7 = "s"
end8 = "h"
end9 = "u"
end10 = "a"
end11 = "i"
#末尾加上end= '',可以避免换行,且''里可以写东西
print(end1 + end2 + end3,end = ' ' )
print(end4 + end5 + end6,end = ' ' )
print(end7 + end8 + end9 + end10 + end11 )

习题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",
    "Own text here",
    "Maybe a poem",
    "Or a song about fear"
))

习题9
打印
三个连续冒号表示一段字符串
“”"


“”"

# Here's some new strange stuff , remember type it exactly

days = "Mon Tue Wed Thu Fri Sat Sun  "
months = "Jan\nFeb\nMat\nApr\nMay\nJun\nJul\nAug"

print("Here are the days :",days)
print("Here are the months:",months)
print("""
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want,or 5,or 6.
S
""")

习题10
转义符号\

转义符号表示内容
\\反斜杠\
单引号’
"双引号“
\aASCII响铃符(BEL)
\bASCII退格键(BS)
\nASCII换行符(LF)
N{name}Unicode数据库中的字符名,其中name是他的名字,仅Unicode适用
\rASCII回车符(CR)
\tASCII水平制表符(TAB)
\uxxxx值为16位十六进制xxxx的字符
\Uxxxx32位十六进制xxxx的字符
\v垂直制表符
\ooo八进制ooo的字符
\xhh十六进制值hh的字符
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
\a
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

习题11
接受输入
x = input(" xxx “)
x = int(input(” xxx "))

print("How old are you ?", end='')
age = input()
print("How tall are you?", end='')
height = input()
print("How much do you weight?", end='')
weight = input()

print("Do you love me?",end='')
love = input()

print("请输入X的值")
x = int(input())
print("请输入Y的值")
y = int(input())
print(f"So, you're {age} old,{height} tall and {weight} heavy,finally,I {love} you.")
print(x*y)

习题12

age = input("How old are you?")
height = input("How tall are you?")
weight = input("How weight are you?")

print(f"So,you're {age} old, {height} height and {weight} weight")

习题13
参数、解包和变量
from sys import argv
从sys库引用argv功能

from sys import argv
#read the WYSS section for how to run this
script, frist = argv
#解包,赋值给script,first


print ("dsdd",script)
print("dasdas",frist)

x=int(input("x"))
y=int(input("y"))
z=x+y
print(z)

习题14
命令体舒服设置成prompt
prompt = ‘>’

from sys import argv

script, user_name = argv
prompt = f"{script}"

print(f"Hi {user_name},I'm the {script} script.")
print("I'd like to ask you a few question.")
print(f"Do you like me {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_name}?")
lives = input(prompt)

print(f"you live is {lives} What kind of computer do you have")
computer = input(prompt)

print (f"""
Alright,so you said {likes} about liking me .
You live in {lives}. Not sure where that is.
And you have a {computer} computer.nice.
""")

习题15
读取文件
open() :函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。
打开方式
read():
参数
size – 从文件中读取的字节数。

返回值
返回从字符串中读取的字节
read(7)读取到第七个字节

txt=open(filename)
print(txt.read())

记得关闭文件
txt.close()

from sys import argv

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())

习题16
close:关闭文件。
read:读取文件的内容。可以把结果赋给一个变量
readline:只读取文本本件的第一行
truncate:清空文件
write(‘stuff’):将”stuff“写入文件。
seek(0):将读写位置移到文件开头
#赋予target以W写入形式filename
target = open (filename, ‘w’)
#擦除所有数据
target.truncate()

target.write(line1 + “\n” + line2 + “\n” + line3 + “\n”)

#从sys引用argv功能
from sys import argv
#把argv分配给script,filename
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以W写入形式filename
target = open (filename, 'w')

print("Truncating the file. Goodbye!")
#擦除所有数据
target.truncate()

print("Now I'm going to ask you for three lines.")
#赋值给line1 2 3
line1 = input("line 1:")
line2 = input("line 2:")
line3 = input("line 3:")

print("I'm going to write these to the file.")
#写入target,即目标文件
#target.write(line1)
#target.write("\n")
#target.write(line2)
#target.write("\n")
#target.write(line3)
#target.write("\n")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")



print("And finally, we close it.")
target.close()
#读取filename
target = open (filename)
print(target.read())

习题17
读取数据长度
in_file = open(from_file)
indata = in_file.read()
print(f"The input file is {len(indata)} bytes long")

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying 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 the 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

习题18
定义一个函数
def hanshuming(arg1,arg2):
print(f"arg1: {arg1},arg2: {arg2}")#函数内容

#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 actually pointless,we can just do this
def print_two_again(arg1,arg2):
    print(f"arg1: {arg1},arg2: {arg2}")

#this just takes one argument
def baliang(arg1):
    print(f"arg1: {arg1}")

#this one take no argument
def print_none():
    print("I got nothin.")

def babaliang(arg1,arg2):
    print(f"arg1:{arg1},arg2:{arg2}")

print_two("ba","liang")
print_two_again("ba","liang")
baliang("ba")
print_none()
babaliang("zhen","shuai")

习题19
函数和变量
#定义变量cheese_and_crackers
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 blanketself.\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)

print(“attack from uesrs”)
x = int(input(“输入x的值”, ))
y = int(input(“输入y的值”, ))
cheese_and_crackers(x , y)

习题20

#从sys库引用argv功能
from sys import argv
#功能赋给script,input_file
script, input_file = argv
#定义函数print_all
def print_all(f):
    print(f.read())
#定义函数rewind
def rewind(f):
    f.seek(0)
#定义函数print_a_line
def print_a_line(line_count,f):
    print(line_count,f.readline(),end="")
#定义变量current_file  加载input_file
current_file = open(input_file)

print("Frist let's print the whole file:\n")
#使用print_all函数
print_all(current_file)

print("Now let's rewind,kind of like a tape.")
#使用rewind 函数
rewind(current_file)

print("Let's print three lines:")

#current_line每行加一,后面输出文本
current_line = 1
print_a_line(current_line,current_file)

current_line +=1
print_a_line(current_line, current_file)

current_line +=1
print_a_line(current_line,current_file)

习题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"MULTIPLY {a} * {b}")
    return a * b

def divide(a,b):
    print(f"DIVIDE {a} / {b}")
    return a / b


print("Let's do some math with 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,"Can you do it by hand?")

def jia(a,b):
    print(f"{a} + {b} ")
    return a + b

def jian(a,b):
    print(f"{a} - {b}")
    return a - b

def cheng(a,b):
    print(f"{a} * {b}")
    return a * b

def chu (a,b):
    print(f"{a} / {b}")
    return a / b

jiaqian = jia(30,30)

shuliang = jian(5,2)

zhekou = cheng(jiaqian,shuliang)

zongjiaqian = chu(zhekou,shuliang)


print(zongjiaqian)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值