出租广告位,需要合作请联系站长

+关注

# 笔记目的

## 习题5

``````# some basic details
name = 'Ivan Don'
age = 22
height = 168 #cm
my_eyes = 'black'

total = age + height
print(f"If I add my age {age} and my height {height}, and I will get \${total}")
``````

``````# 五种方法打印字符串与变量
#1
#2
#3
#4
x = "Let's talk about {}."
print(x.format(name))
#5
``````

## 习题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

end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "b"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

print(end1+end2+end3+end4+end5+end6,end=' ')
print(end7+end8+end9+end10+end11+end12)
``````

## 习题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",
))
``````

## 习题9

``````# Here's some new strange stuff, remeber type it exactly.

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

print("Here are the days: ", days)
print("Here are the months: ", months)

print('''
There is 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.
''')
``````

## 习题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)
``````

``````print("I'm a bs\ba")    #\b退格符，在后面还有字符的时候，会删除其前面一个的符号
print("I'm a bs\faa")    #退纸符，会将其后面的字符转到下一行并接着上一行字符结束的地方继续
print("\a")     #响铃符，执行之后电脑会发出声响，可以打开电脑声音试一试
``````

## 习题11-13

``````#--------------------No.11--------------------
print("How old are you?", end=' ') #end是为了结尾不换行，里面可以使用任何字符串
age = input()
print(f"So you're {age} years old.")

#------------------No.12------------------------
age = input("How old are you?") # input里面可以直接放出想要打印的字符串，并继续输入
print(f"So you're {age} years old.")

#-------------------No.13-------------------------------
from sys import argv
script, first, second, third = argv
print("The script is called:",script)
``````

## 习题15

``````from sys import argv

script, filename = argv
txt = open(filename)

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

## 习题16

``````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")
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")

#---第二种
target.write(line1+'\n'+line2+'\n'+line3+'\n')

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

``````#先告诉他要看什么文件
script, filename = argv
#接着要打开这个文件
txt = open(filename,'r')
#再是显示这个文件
``````

https://blog.csdn.net/jiruiYang/article/details/53887455

r+与w+的主要区别应该在于：使用前者，在写入的时候，写多少才覆盖原文件内容多少，比如原文是abcdef，使用r+输入123，结果为123def；使用后者，写一点就把原本的都覆盖，结果则为123。

## 习题17

``````from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

print(f"The input file is {len(indata)} bytes long.")
print(f"Does the output file exist? {exists(to_file)}")

input(">")

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

print("Done!")
out_file.close()
``````

cmd中也可以使用echo “Test” > test.txt 创建新文件且写入，在linux中的cat操作相当于windows中的ype。

``````outfile = open('test_out.txt','w').write(open('test.txt').read())
``````

## 习题18、19

``````#-----------------No.18-------
# *args pointless 属于list
def print_two(*args):
arg1, arg2 = args #将参数进行解包
print(f"arg1:{arg1}, arg2:{arg2}")
def print_two_again(arg1,arg2):
print(f"arg1:{arg1}, arg2:{arg2}")

def print_one(arg1):
print(f"arg1:{arg1}")

def print_nothing():
print("print it directly")

print_two("ivan1","slyvia1")
print_two_again("ivan1","slyvia1")
print_one("onlyOne")
print_nothing()

#----------------No.19------------------------
def  cheese_cracker(cheese_count, boxes_of_cracker):
print(f"""
You have {cheese_count} cheeses!
You have {boxes_of_cracker} boxes of crackers!
Man that's enough for a party!
Get a blanket!
""")
print("First method\n")
cheese_cracker(20,30)

print("sec\n")
x = 10
y = 50
cheese_cracker(x,y)

print("third\n")
cheese_cracker(10+20,5+6)

cheese_cracker(int(input('cheese count:')),int(input('crackers count:')))

``````

## 习题20

``````from sys import argv

input_file = input('输入要打开的文件：')

# 打印文件中所有内容
def print_all(f):

# 回到文件开头
def rewind(f):
f.seek(0)

# 打印文件中指定的一行
def print_a_line(line_count,f):

# 打开当前文件
current_file = open(input_file)
print("the whole content:")
print_all(current_file) # 输出当前文件中所有内容
print("\n")

print("rewind the file, let the pointer go to the beginning.\n")
rewind(current_file)
print("Print two lines:\n")
current_line = 1
print_a_line(current_line,current_file)
current_line+=1
print_a_line(current_line,current_file)
``````

## 习题21

``````# add two number
return a+b

#substract two number
def substract(a,b):
print(f"SUBSTRACT {a} - {b}")
return a-b
def divide(a,b):
print(f"DIVIDE {a} / {b}")
return a/b
def multiply(a,b):
print(f"MULTIPLY {a} * {b}")
return a*b

height = substract(78,4)
weight = multiply(90,2)
iq = divide(100,2)

print(f"age = {age},height = {height}, weight = {weight}, iq = {iq}")
print("A puzzle")
print("It is what equals to ",what)

``````

## 习题23

``````#之前是import argv from sys
import sys
script, encoding, error = sys.argv

def main(language_file, encoding, errors):
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("execise/languages.txt",encoding = "utf-8")
main(languages, encoding, error)
``````

1、strip()函数的用法：去除行中首尾所要去除的内容

2、encode和decode：代码中 next_lang其实与cooked_string是相等的，均为字符串。对于编码（encode）和解码（decode），可以理解为编码是为了让机器知道我们在说什么，所以编码之后输出是字节串，因此解码之后输出的就是字符串，为了让我们懂得机器在说什么。函数中的第二个error参数主要有五种：strict, replace, ignore, xmlcharrefreplace, backslashreplace，除此之外还可以使用codecs.regsiter_error注册自己的错误处理程序。

3、为什么使用Unicode：解决ASCII不同能同时编码多个国家的语言。

## 习题24

``````print("Let's practice everything.")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\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

# let these three variables be the value of the function that returns
beans, jars, crates= secret_formula(start_point)

print("With a starting point of: {}".format(start_point))
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")

start_point = start_point / 10
# formula is an array of numbers
formula = secret_formula(start_point)
print("We'd have {} beans, {} jars, and {} crates".format(*formula))
``````

## 习题25

``````# stuff is a sentence, which is also a list of string with space in it
def break_word(stuff):
"""This function will break up words for us."""
# words is an array of strings
words = stuff.split(' ')
return words

#words is an array of strings (short strings without any space)
def sort_words(words):
"""Sort the words."""
return sorted(words)

def print_first_word(words):
"""Prints the first word after popping it off"""
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."""
words = break_word(sentence)
return sort_words(words)

def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_word(sentence)
print_first_word(words)
print_last_word(words)

def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
``````

``````>>>import sys #先导入一个最基础的sys
>>>sys.path #查看这些库和包都被放在哪里
>>>sys.path.append(r"H:\VScode") #把你自己写的脚本所在目录加进去，就可以了！
``````

## 习题26

``````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("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print('Let\'s practice everything.')
print('You\'d need to know \'bout escapes with \\ 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
cats = 30
dogs = 15

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

if people > cats:
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.")
``````

## 习题29、31

``````----------------No.29------------
people = 30
cars = 40
trucks = 15

if cars > people:
print("We should take the cars.")
elif cars < people:
print("We should not take the cars.")
else:
print("We can't decide.")

if trucks > cars:
print("That's too many trucks.")
elif trucks < cars:
print("May be we could take the trucks.")
else:
print("We still can't decide.")

if people > trucks:
print("Alright, let's just take the trucks.")
else:
print("Fine,let's stay home then.")

#-----------No.31------------
print("""You enter a dark room with two doors.
Do you go through door #1 or door #2?
""")

door = input(">")

if door == "1":
print("""There's a gaint bear here eating a cheese cake.
What do you do?
1. Take the cake.
2. Scream at the bear.
""")

bear = input(">")

if bear == "1":
print("The bear eats your face off. Good job!")
elif bear == "2":
print("The bear eats your leg off. Good job!")
else:
print(f"""Well, doing {bear} is probably better.
The bear runs away""")

elif door =="2":
print("You stare into the endless abyss at Cthulhu's retina.")
print("1. Blueberries.")
print("2. Yellow jacket clothespins.")
print("3. Understanding revolvers yelling melodies.")

insanity = input(">")

if insanity in range(1,3):
print("Good job!")
else:
print("The insanity rots your eyes into a pool of muck.")
print("Good job!")

else:
print("You stumble around and fall on a knife and die. Good job!")
``````

## 习题32

``````the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']

#this first kind of for-loop goes through a list
for number in the_count:
print(f"This is count {number}")

for fruit in fruits:
print(f"A fruit of type: {fruit}")

#also we can go through mixed lists too
for i in change:
print(f"I got {i}")

elements =[]
for i in range(0,6):
elements.append(i)

for i in elements:
print(f"Element was :{i}")
``````

1、list：上述代码中，像the_count, fruits, change这类都属于list，它和array数组又不太一样，list可以将不同数据类型的变量都放在里面比如change，array不仅在numpy包中，而且只允许一类数据类型的变量在里面。

2、list一些最基本使用
list[-1] : 读取列表中倒数第一个元素
list[1:] : 读取第二个及以后的元素
del list[1] : 删除列表中第二个位置的元素
len(list) : list的长度
list1+list2 : 将两个列表合并
list * 4 : 重复输出四次list中的内容
3 in list : 判断list中有没有“3”这个元素

## 习题33

``````i = 0
numbers = []

while i <6:     #for i in range(0,6):
print(f"At the top i is {i}.")
numbers.append(i)

i+=1
print("Numbers now:",numbers)
print(f"At the bottom i is {i}.")

print("The numbers:")
for num in numbers:
print(num,end='')
``````

## 习题35

``````from sys import exit

# a function that
def gold_room():
print("This room is full of gold. How much do you take?")

choice = input(">")

# if I enter 2 what'll happen??
if choice.isdigit():
how_much = int(choice)
else:
dead("Man, learn to type a number.")

if how_much < 50:
print("Nice, you're not greedy, you win!")
exit(0)
else:

def bear_room():
print("""There is a bear here.
The bear has a bunch of honey.
The fat bear is in front of another door.
How are you going to move the bear?
""")
bear_moved = False

while True:
choice = input(">")

if choice == "take honey":

# see if the bear is moved
elif choice == "taunt bear" and not bear_moved:
print("The bear has moved from the door.")
print("You can go through it now.")
bear_moved = True
elif choice == "taunt bear" and bear_moved:
elif choice == "open door" and bear_moved:
gold_room()
else:
print("I got no idea what that means.")

def cthulhu_room():
print("""Here you see the great evil Cthulhu.
He, it, whatever stares at you and you go insane.
""")

choice = input(">")

if "flee" in choice:
start()
else:
cthulhu_room

print(why,"Good job!")
exit(0)

def start():
print("""You are in a dark room.
There is a door to your right and left.
Which one do you take?
""")
choice = input(">")

if choice == "left":
bear_room()
elif choice == "right":
cthulhu_room()
else:
print("You stumble around the room until you starve.")

start()
``````

## 习题36

``````from sys import exit
import time
# the initial fund and share
total = 20000
share_tesla = 0
share_gilide = 0
share_5G = 0
money_tesla = 200
money_gilide = 100
money_5G = 50
choice_error = 0   #times that the users enter the wrong choice
buy_error = 0   #times that the users enter the wrong stock name

def three_stock():

# declare that we're using tha variable that defined outside the func
global total, share_5G, share_gilide, share_tesla, first_buy, choice_error
print("There are three kinds of stock:")
print("Tesla, Gilide, 5G")
print("--------------------------------")
print("And you have initial fundmentation: \$20,000.")
stock = input("Which one do you want to buy?\n>")
else:
print(f"Your cash is \${total}, you've {share_tesla} shares of Tesla, {share_gilide} shares of Gilide, {share_5G} shares of 5G")
print("Do you want to buy some more or sell some?")
choice = input(">")
print("Which one do you want to buy? Tesla, Gilide, 5G")
stock = input(">")
elif 'sell' in choice:
print("Which one do you want to sell? Tesla, Gilide, 5G")
print(f"You have {share_tesla} shares of Tesla, {share_gilide} shares of Gilide, {share_5G} shares of 5G.")
print("You can only sell all the shares you have.")
stock = input(">")
sell(stock)
else:
if choice_error <= 3:
else:
choice_error+=1

global money_tesla, money_gilide, money_5G
if stock == 'Tesla':
print("Tesla: \$200 per share, how many shares do you want to buy?")
# tell the input I'm going to enter an int type
share_tesla = int(input(">"))
if share_tesla*money_tesla > total:
dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
else:
total = total - share_tesla*200
if share_tesla > 52:
print("Crude oil plunged, Tesla dead, and you have lost all the money that invested it.")
share_tesla = 0
# set the money to the initial
money_tesla = 200
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
#continue to play or not
cont_stop()
elif share_tesla in range (1,53):
print(f"You've bought {share_tesla} shares, and your cash now is \${total}.")
time.sleep(2)
print("...wait!!")
time.sleep(4)
print("Tesla factory in Shanghai begins to produce cars!!!")
print("Tesla stock is going up to \$400 per share!")
money_tesla = 400
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
else:
dead("Could you enter a NUMBER that greater than 0?")

elif stock == 'Gilide':
print("Gilide: \$100 per share, how many shares do you want to buy?")
share_gilide = int(input(">"))

if share_gilide*money_gilide > total:
dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
else:
total = total - share_gilide*100
if share_gilide > 41:
print(f"You've bought {share_gilide} shares, and your cash now is \${total}.")
time.sleep(2)
print("2019-nCov is out-break!! OMG!")
time.sleep(2)
print("WHAT!!!!!!!!!! Gilide has an effective medicine which can treat it!!")
time.sleep(4)
print("Gilide stock is going up to \$200 per share!")
money_gilide = 200
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
elif share_gilide in range (1,42):
print("Gilide is too good to maintain its company, and it closed, everything gone.")
share_gilide = 0
money_gilide = 100
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
#continue to play or not
cont_stop()
else:
dead("Could you enter a NUMBER that greater than 0?")

elif stock == '5G':
print("5G: \$50 per share, how many shares do you want to buy?")
share_5G = int(input(">"))
if share_5G*money_5G > total:
dead("You don't have enough money to buy it!\n And I don't want who can't do math to play this game!")
else:
total = total - share_5G*money_5G
if share_5G > 58:
print(f"You've bought {share_5G} shares, and your cash now is \${total}.")
time.sleep(2)
print("HuaWei has invented 5G! Good news!!")
time.sleep(2)
print("!!!!!!!!!! US begins to supress HuaWei due to the new technology!")
time.sleep(2)
print("5G stock Gone!")
share_5G = 0
money_5G = 50
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
elif share_5G in range (1,59):
print("5G is invented. The stock is going up to \$100 per share.")
money_5G = 100
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
#continue to play or not
cont_stop()
else:
dead("Could you enter a NUMBER that greater than 0?")

else:
print("Please choose a stock that the game has!!")
else:
dead("Stupid! I told you three times! ENTER A STOCK THAT THE GAME HAS!")

def sell(stock):
global total, share_tesla, share_gilide, share_5G, money_tesla, money_gilide, money_5G
if stock == 'Tesla':
total = total + share_tesla*money_tesla
share_tesla = 0
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
elif stock == 'Gilide':
total = total + share_gilide*money_gilide
share_gilide = 0
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
elif stock == '5G':
total = total + share_5G*money_5G
share_5G = 0
print(f"Now your cash is \${total}, Tesla share: {share_tesla}, Gilide share: {share_gilide}, 5G share: {share_5G}")
cont_stop()
else:
dead("You don't even have that stock!!!")
# continue to play the game or not
def cont_stop():
choice = input("Do you want to continue? (Y/N) >")
if choice == 'Y':
three_stock()
elif choice == 'N':
else:
dead("Stupid! You can't even enter the Y and N correctly!")

print(why,"Game lost!!")
exit(0)

three_stock()
``````

5 0

pdf(new) 更多>