learn python the hard way #exercise1~15

learn python the hard way

exercise 1

source file

print("Hello World")
print("Hello Again")
print("I like typing this.")
print("This is fun.")
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.')

run

E:\code\venv\Scripts\python.exe "E:/code/exercise 1.py"
Hello World
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.

Process finished with exit code 0

error
解释

exercise 2

大于小于<>的结果:true false

source file

# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print("I could have code like this.") # and the comment after is ignored
# print("this wont run.")
print ("This will run.")

run

E:\code\venv\Scripts\python.exe "E:/code/exercise 2.py"
I could have code like this.
This will run.

Process finished with exit code 0

exercise 3

source file

print("I will now count my chickens:")
print("Hens", 25+30/6)
print("Roosters", 100-25*3 % 4)
print("Now I will count the eggs:")
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("Is it greater?", 5 > -2)
print("Is it greater or equal?", 5 >= -2)
print("Is it less or equal?", 5 <= -2)

run

E:\code\venv\Scripts\python.exe "E:/code/exercise 3.py"
I will now count my chickens:
Hens 30.0
Roosters 97
Now I will count the eggs:
6.75
Is it true that 3+2<5-7?
False
What is 3+2? 5
What is 5-7? -2
Oh, that's why it's False.
Is it greater? True
Is it greater or equal? True
Is it less or equal? False

Process finished with exit code 0

exercise 4

source file

cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven

print("There are", cars, "cars available.")
print("There are only", drivers, "drivers available")
print("There will be", cars_not_driven, "empty cars today")
print("We can transport", carpool_capacity , "people today.")
print("We have", passengers, "to carpool today.")
print("We need to put about", average_passengers_per_car, "in each car.")

run

E:\code\venv\Scripts\python.exe "E:/code/exercise 4.py"
There are 100 cars available.
There are only 30 drivers available
There will be 70 empty cars today
We can transport 120.0 people today.
We have 90 to carpool today.
We need to put about 3.0 in each car.

Process finished with exit code 0

在这里插入图片描述
在这里插入图片描述
= 右边给左边的变量赋值
在这里插入图片描述
向后读文件:新添加的时候,可能添加在后面,从那儿开始阅读。
在这里插入图片描述

exercise 5

source file

name = 'Little Jiang'
age = 21 # not a lie
height = 165 # cm
weight = 48 # kg
eyes = 'Brown'
teeth = 'White'
hair = 'Black'

print(f"Let's talk about {name}.")
print(f"She's {height} cm tall.")
print(f"She's {weight} kg heavy.")
print("Actually that's not too heavy.")
print(f"She's got {eyes} eyes and {hair} hair.")
print(f"Her teeth are usually {teeth} depending on the coffee.")

# this line is tricky, try to get it exactly right
total = age + height + weight
print(f"If I add {age}, {height}, and {weight} I get {total}.")

run

E:\code\venv\Scripts\python.exe "E:/code/exercise 5.py"
Let's talk about Little Jiang.
She's 165 cm tall.
She's 48 kg heavy.
Actually that's not too heavy.
She's got Brown eyes and Black hair.
Her teeth are usually White depending on the coffee.
If I add 21, 165, and 48 I get 234.

Process finished with exit code 0

在这里插入图片描述

exercise 6

source file

types_of_people = 10

# 单引号与双引号没啥区别,多引号(三个引号)用于换行
x = f'There are {types_of_people} types of people.'
binary = 'binary'  # 二进制
do_not = "don't"

# f表示{}是一段格式化输出,{}可包含数字和字符串。格式化输出:%s,字符串。%d,十进制整数。%f浮点数。
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 = False
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)

run

There are 10 types of people.
Those who know binary and those who don't.
I said: There are 10 types of people.
I also said: 'Those who know binary and those who don't.'
Isn't that joke so funny?! False
This is the left side of...a string with a right side.

Process finished with exit code 0

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
知乎笔记exercise 6

exercise 7

code

print("Mary had a little lamb.")

# 不是一变量,是一个带有单词snow的字符串。变量不会有单引号
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("." * 10)  # ?

end1 = "C"  # 把字符C赋值给变量end1
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"

#end=""传递一个空字符串,这样print函数不会在字符串末尾添加一个换行符
# why end=. not end = ? 两个单词间加了个空格' '
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end10 + end11 + end12)

run result

Mary had a little lamb.
Its fleece was white as snow.
And everywhere that Mary went.
..........
Cheese Burger

change code

#watch end='' at the end. try removing it to see what happens
#将被赋值字符串的end变量相加,如果删除end='',print会默认换行
print(end1 + end2 + end3 + end4 + end5 + end6)
print(end7 + end8 + end9 + end10 + end11 + end12)

result

Cheese
Burger

exercise 8

code

formatter = "{} {} {} {}"

# 格式化字符串函数str.format(),通过 {} 和 : 来代替以前的 %
# 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"
))

result

1 2 3 4
one two three four
True False False True
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text here Maybe a poem Or a song about fear

question:

  1. formatter.format()
  2. 重复练习习题7的加分习题
formatter = "{}{}{}{}{}{}{}{}{}{}{}{}"
print(formatter.format("C", "h", "e", "e", "s", "e", "B", "u", "r", "g", "e", "r"))

result

CheeseBurger

exercise 9

code

# Here is some new stranger stuff, remember type it exactly.

days = "Mon Tue Whe Thu Fri Sat Sun"
# Jan 前面也加上换行\n
months = "\n Jan \n Feb \n Mar \n Apr \n May \n Jun \n Jul \n Aug"

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

result

Here are the days:  Mon Tue Whe Thu Fri Sat Sun
Here are the months:  
 Jan 
 Feb 
 Mar 
 Apr 
 May 
 Jun 
 Jul 
 Aug

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.

exercise 10

code

tabby_cat = "\t I'm tabbed in."  # 平纹猫 标记
persian_cat = "I'm split \n on a line."  # 波斯猫 分裂
backslash_cat = "I'm \\ a \\ cat"  # 反斜杠猫

fat_cat = """
I'll do a list:
\t * Cat food 
\t * Fishes 
\t * Catnip \n \t * Grass  
"""
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

result

     I'm tabbed in.
I'm split 
 on a line.
I'm \ a \ cat

I'll do a list:
	 * Cat food 
	 * Fishes 
	 * Catnip 
 	 * Grass

change code

tabby_cat = "\t I'm tabbed in."  # 平纹猫 标记
persian_cat = "I'm split \n on a line."  # 波斯猫 分裂
backslash_cat = "I'm \\ a \\ cat"  # 反斜杠猫

fat_cat = '''
I'll do a list:
\t * Cat food 
\t * Fishes  
\t * Catnip \n \t * Grass  

'''  # 猫薄荷
print(tabby_cat)
print(persian_cat)
print(backslash_cat)
print(fat_cat)

result
一模一样,在本题中单引号和双引号没有差别。

	 I'm tabbed in.
I'm split 
 on a line.
I'm \ a \ cat

I'll do a list:
	 * Cat food 
	 * Fishes  
	 * Catnip 
 	 * Grass  

在这里插入图片描述

exercise 11

code

print("What's your name?", end='')
name = input("")
print("Who is your lover?", end='')
lover = input("")
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(f"So, your name is {name}, your lover is {lover}, you are {age} years old, {height} cm tall and weigh {weight} kg.")

result

What's your name? little jiang
Who is your lover? vincent lee
How old are you? 22
How tall are you? 165
How much do you weight? 48
So, your name is  little jiang, your lover is  vincent lee, you are  22 years old,  165 cm tall and weigh  48 kg.

input(),让用户输入字符串,并存放在一个变量里。注意数字直接使用(),如果输入文本得带入双引号“”,或者转换格式。

ex 12

code

# 用input重写上节,所有提示都能用input实现
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weight?")

print(f"So, you are {age}, {height}cm tall and {weight}kg heavy.")

result

How old are you? xiaojiang
How tall are you? 165
How much do you weight? 48
So, you are  xiaojiang,  165cm tall and  48kg heavy.

ex 13

code

from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv, "Anything Here 1", "Anything Here 2", "Anything Here 3"
# 脚本

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
#  error: 没有足够的值来解包

result

The script is called: ['E:/code/exercise 13.py']
Your first variable is: Anything Here 1
Your second variable is: Anything Here 2
Your third variable is: Anything Here 3

code

from sys import argv  # system系统复制命令,import输入,
# read the 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)
#  error: 没有足够的值来解包
#  sys.argv是获取运行python文件的时候的命令行参数。
#  Sys.argv[ ]是一个列表,里边的项为用户输入的参数,参数是从程序外部输入的,而非代码本身的什么地方。
#  要想看到它的效果就应该将程序保存了,从外部来运行程序并给出参数。

命令行运行
在这里插入图片描述
Tab键可以选择

e:\code>python "exercise 13.py" xiaov love xiaojiang
The script is called: exercise 13.py
Your first variable is: xiaov
Your second variable is: love
Your third variable is: xiaojiang

加分题

from sys import argv  # system系统复制命令,import输入,
# read the WYSS section for how to run this
script, first, second, third = argv, "xiaov", "love", "xiaojiang"
# 脚本

print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
#  error: 没有足够的值来解包
#  sys.argv是获取运行python文件的时候的命令行参数。
#  Sys.argv[ ]是一个列表,里边的项为用户输入的参数,参数是从程序外部输入的,而非代码本身的什么地方。
#  要想看到它的效果就应该将程序保存了,从外部来运行程序并给出参数。

from sys import argv
script, flower, grass = argv, "rose", "green"
print("The script is called:", script)
print("Your first variable is:", flower)
print("Your second variable is:", grass)

from sys import argv
# 松鼠,旱獭
script, pikachu, lion, monkey, squirrel, marmot = argv, "pikachu", "lion", "monkey", "squirrel", "marmot"
print("thr script is called", script)
print("the first variable is", pikachu)
print("the second variable is", lion)
print("the third variable is", monkey)
print("the fourth variable is", squirrel)
print("the fifth variable is", marmot)

animal = input("What is your first variable")
print(f"So your first variable is {animal}.")

result

The script is called: ['E:/code/exercise 13.py']
Your first variable is: xiaov
Your second variable is: love
Your third variable is: xiaojiang
The script is called: ['E:/code/exercise 13.py']
Your first variable is: rose
Your second variable is: green
thr script is called ['E:/code/exercise 13.py']
the first variable is pikachu
the second variable is lion
the third variable is monkey
the fourth variable is squirrel
the fifth variable is marmot
What is your first variable pikachu
So your first variable is  pikachu.

ex 14

code

from sys import argv

script, user_name = argv, "little jiang"
prompt = '>'

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

print(f"Where do you live {user_name}?")
lives = input(prompt)
print("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.""")

result

Hi little jiang, I'M THE ['E:/code/ex 14.py'] script.
I'd like to ask you a few questions.
Do you like me little jiang?
>yes
Where do you live little jiang?
>Shanghai
What kind of computer do you have?
>HONOR Magicbook

Alright, so you said yes about liking me. You live in Shanghai.
Not sure where that is. And you have a HONOR Magicbook computer. Nice.

加分题
code

from sys import argv

script, user_gender, user_name = argv, "Miss", "Jiang"
prompt = '>>>>'  # 提示。将prompt变量改成完全不同的内容再运行一遍。

# 给我的脚本再添加一个参数,并使用这个参数
print(f"Hi {user_gender} {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_gender} {user_name}?")
likes = input(prompt)

print(f"Where do you live {user_gender} {user_name}?")
lives = input(prompt)
print("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.""")

result

Hi Miss Jiang, I'm the ['E:/code/ex 14.py'] script.
I'd like to ask you a few questions.
Do you like me Miss Jiang?
>>>>yep
Where do you live Miss Jiang?
>>>>Shanghai
What kind of computer do you have?
>>>>magicbook

Alright, so you said yep about liking me. You live in Shanghai.
Not sure where that is. And you have a magicbook computer. Nice.

ex15
code

from sys import argv  # 引入sys的部分模块argv(参数变量)
script, filename = argv, "ex15_sample.txt"  # 将参数解包并赋值给script脚本和filename这两个变量

txt = open(filename)  # open函数接收参数filename并将接收到的值赋值给变量txt

print(f"Here's your file {filename}:")  # 将变量filename嵌入到字符串中并打印
print(txt.read())  # 让txt执行read函数,无需任何参数,并打印出来

print("Type the filename again:")  # 打印字符串
file_again = input(">")  # 用户在>输入字符串并赋值给变量file_again

txt_again = open(file_again)  # open函数接收参数file_again并将接收到的值赋值给变量txt_again

print(txt_again.read())  # 让txt_again执行read函数并打印出来

result

Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

change

filename = input("Type your filename:")
txt = open(filename)  # open函数接收参数filename并将接收到的值赋值给变量txt

print(f"Here's your file {filename}:")  # 将变量filename嵌入到字符串中并打印
print(txt.read())  # 让txt执行read函数,无需任何参数,并打印出来

print("Type the filename again:")  # 打印字符串
file_again = input(">")  # 用户在>输入字符串并赋值给变量file_again

txt_again = open(file_again)  # open函数接收参数file_again并将接收到的值赋值给变量txt_again

print(txt_again.read())  # 让txt_again执行read函数并打印出来

result

Type your filename:ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
>ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

命令行提示符下使用open打开一个文件

C:\Users\Little Jiang>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open("e:\ex15_sample.txt")
>>> f.read()
'This is stuff I typed into a file.\nIt is really cool stuff.\nLots and lots of fun to have in here.'
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值