《笨方法学python3》学习记录

更多的变量和打印(变量名要以字母开头)
tips:

my_name = 'RykerJu'
my_age = 24
#要使用python打印出变量对应的字符串有两种方法
print('my name is '+my_name+' and my age is '+str(my_age))#第一种方法字符串相加
print(f"my name is {my_name},and my age is {my_age}")#第二种方法式格式化字符串

显示结果:

"/Users/juran/Desktop/python review/venv/bin/python" "/Users/juran/Desktop/python review/ex5.py"
my name is RykerJu and my age is 24
my name is RykerJu,and my age is 24

Process finished with exit code 0

可以看到结果是一样的,第一种方法运用了太多的字符会有些杂乱,第二种直接在引号里加入大括号就好了。

字符串和文本

types_of_people = 10
x = f"There are {types_of_people} types of people."
print(x)
hilarious = "False"
joke_evaluation = "Isn't that joke so funny?! {}"
#暂时把它理解为待填项,有后面的format函数来填充上述对应变量
print(joke_evaluation.format(hilarious))
#也可以写成
print("isn't that joke so funny?!".format(hilarious))

运行结果:

"/Users/juran/Desktop/python review/venv/bin/python" "/Users/juran/Desktop/python review/ex6.py"
There are 10 types of people.
Isn't that joke so funny?! False
isn't that joke so funny?! False

Process finished with exit code 0

更多打印

print("hahaah",end = '       ')
#最后end=的作用应该是两段字符串要在同一行,中间的连接字符串就是等于号后面引号内的内容
print('hahaha')
print('hahaha')

打印,打印

formatter = "{} {} {} {}"
print(formatter.format(1,2,3,4))
print(formatter.format("one","two",'three','four'))
print(formatter.format('True','False','True','False'))

显示结果:

"/Users/juran/Desktop/python review/venv/bin/python" "/Users/juran/Desktop/python review/venv/ex8.py"
1 2 3 4
one two three four
True False True False

Process finished with exit code 0

目的就是强化对.format()函数的理解(填充大括号中的文本)

打印,打印,打印
这里主要是强调\n转行符,print(’’’
haahahaj
jaajajaa
ajhajahjja’’’)
多行文本同时打印

读写文件

from sys import argv    #导入argv模块
script,filename = argv   #设置两个待填变量
print(f"we are going to erase {filename}")
print("if you don't want that,hit CTRL-C(^c)") #终端默认CTRL-C为退出
print("if you do want that,hit RETURN.")
input("?")
print("opening the file...")
target = open(filename,'w')#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()

显示结果:

jurandeMacBook-Pro:python juran$ python3 ex16.py test.txt
we are going to erase test.txt
if you don't want that,hit CTRL-C(^c)
if you do want that,hit RETURN.
?
opening the file...
truncating the file.Goodbye!
now i'm going to ask you for three lines.
line1:we just try try try 
line2:be nice nice nice
line3:hahahaha
i'm going to write these to the file.
and finally,we close it.
jurandeMacBook-Pro:python juran$ 

open(filename,‘w’) write是用来写入文件,文件原有的数据全部抹掉
open(filename,‘r’) read只是读取文件
open(filename,‘a’) append是在原有文件内容上添加新的内容
读写的简单方式

filename = 'text.txt'
with open(filename,'w+') as file_project:
	file_project.write('hahahahhahahahaah')

这个是写入文件,open函数里面的’w‘如果没写,默认是只读模式

with open("text.txt",'r') as file_project:
	contents = file_project.read()
	print(contents)

这个是只读模式

函数

def break_words(stuff):
	words =stuff.split(' ')
	return words

运行结果:

>>> import ex25
>>> stuff =' i love you so much really,but you always leave me alone'
**>>> break_words(stuff)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'break_words' is not defined**    这几行都是有问题的,正确的在下面
>>> ex25.break_words(stuff)
['', 'i', 'love', 'you', 'so', 'much', 'really,but', 'you', 'always', 'leave', 'me', 'alone']
>>> 

习题26
原代码 错误较多

print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
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(filenme)

print("Here's your file {filename}:")
print(tx.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 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 - 
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 = 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(startpoint)
# 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 < 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.")

修改后:

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

from sys import argv
script, filename = argv #还没调用这个模块呢

txt = open(filename)

print("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 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 
print(f"This should be five: {five}")

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

start_point = 10000
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, {jars} jars, and {crates} crates.")

start_point = start_point / 10

print("We can also do that this way:")
formula = secret_formula(startpoint)
# 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.")

猜你喜欢

转载自blog.csdn.net/weixin_43580807/article/details/88194988
今日推荐