鸣沙山侧 月牙泉畔

Just another WordPress.com site


留下评论

《learn python the hard way(笨办法学 Python)》 习题 python3重写版(ex6~ex8)

EX6

# In less formal terms, the replacement field can start with a field_name
# that specifies the object whose value is to be formatted and inserted
# into the output instead of the replacement field. The field_name is
# optionally followed by a conversion field, which is preceded by an
# exclamation point ‘!’, and a format_spec, which is preceded by a colon ‘:’.
# These specify a non-default format for the replacement value.
# Three conversion flags are currently supported: ‘!s’ which calls str() on the value,
# ‘!r’ which calls repr() and ‘!a’ which calls ascii().
# Some examples:
# “Harold’s a clever {0!s}” # Calls str() on the argument first
# “Bring out the holy {name!r}” # Calls repr() on the argument first
# “More {!a}” # Calls ascii() on the argument first

 

x = “There are {:d} types of people.” .format(10)
binary = “binary”
do_not = “don’t”
y = “Those who know {:s} and those who {:s}.”.format(binary, do_not)

print (x)
print (y)

print (“I said: {!r}.” .format(x))
print (“I also said: ‘{!s}’.” .format(y))

hilarious = False
joke_evaluation = “Isn’t that joke so funny?! %r”
print (joke_evaluation % hilarious)

#这个写法其实是:
#hilarious = False
#joke_evaluation = “Isn’t that joke so funny?! %r” % hilarious
#print joke_evaluation
#其中%r calls repr(), which represents False (bool) as “False” (string).
#转成3.0版的写法就是:

hilarious = False
joke_evaluation = “Isn’t that joke so funny?! {!r}” .format(hilarious)
print (joke_evaluation)

# %s和%r区别如例:
# test = “””hello,\nworld”””
# print “this is test1: %s” %test
# print “this is test2: %r” %test
# 输出:
# this is test1: hello,
# world
# this is test2: ‘hello,\nworld’
# 由此可见,在python中格式化字符%r,表示打印的是对象,什么都打印
w = “This is the left side of…”
e = “a string with a right side.”

print (w + e)

===========================================================

EX7

print (“Mary had a little lamb.”)
print (“Its fleece was white as {:s}.” .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”

# watch that comma at the end. try removing it to see what happens
print (end1 + end2 + end3 + end4 + end5 + end6, end=”)
print (end7 + end8 + end9 +end10 + end11 + end12)

=======================================================

EX8

formatter = “{!r} {!r} {!r} {!r}”

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(
“I had this thing.”,
“That you could type up right.” ,
“But it didn’t sing.”,
“So I said goodnight.”
))

# 第8行的打印结果是:’I had this thing.’ ‘That you could type up right.’ “But it didn’t sing.” ‘So I
# said goodnight.’
#注意【”But it didn’t sing.“】是用了双引号,原因是【didn’t】有了单引号。


留下评论

《learn python the hard way(笨办法学 Python)》 习题 python3重写版(ex5)

my_name = ‘Zed A. Shaw’
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # Lbs
my_eyes = ‘Blue’
my_teeth = ‘White’
my_hair = ‘Brawn’

print (“Let’s talk about {}.”.format(my_name))
print (“He’s {:d} inches tall.”.format(my_height))
print (“He’s {:d} pounds heavy.”.format(my_weight))
print (“Actually that’s not too heavy.”)
print (“He’s got {} eyes and {} hair.” .format(my_eyes, my_hair))
print (“His teeth are usually {} depending on the coffee.”.format(my_teeth))

# this line is tricky, try to get it exactly right
#print (“If I add %d, %d, and %d I get %d.”) %(my_age, my_height,my_weight,my_age + my_height + my_weight)

============================================================

#习题1:修改所有的变量名字,把它们前面的“my_“去掉。确认将每一个地方的都改掉,不只是你使用“=“赋值过的地方。
#习题3:在网上搜索所有的 Python 格式化字符。 https://docs.python.org/3/library/string.html
name = ‘Zed A. Shaw’
age = 35 # not a lie
height = 74 # inches
weight = 180 # Lbs
eyes = ‘Blue’
teeth = ‘White’
hair = ‘Brawn’

print (“Let’s talk about {}.”.format(name))
print (“He’s {:d} inches tall.”.format(height))
print (“He’s {:d} pounds heavy.”.format(weight))
print (“Actually that’s not too heavy.”)
print (“He’s got {} eyes and {} hair.” .format(eyes, hair))
print (“His teeth are usually {} depending on the coffee.”.format(teeth))
# this line is tricky, try to get it exactly right
print (“If I add {:d}, {:d} and {:d},I get {:d}.”.format(age,height,weight,age + height + weight))

====================================================================

#习题4:试着使用变量将英寸和磅转换成厘米和千克。不要直接键入答案。使用 Python 的计算功能来完成。

name = ‘Zed A. Shaw’
age = 35 # not a lie
height_inch = 74 # inches
weight_pound = 180 # Lbs
eyes = ‘Blue’
teeth = ‘White’
hair = ‘Brawn’
height_centimeter = height_inch * 2.54
weight_kilogram = weight_pound * 0.454

print (“Let’s talk about {}.”.format(name))
print (“He’s {:f} centimeters tall.”.format(height_centimeter))
print (“He’s {:f} kilograms heavy.”.format(weight_kilogram))
print (“Actually that’s not too heavy.”)
print (“He’s got {} eyes and {} hair.” .format(eyes, hair))
print (“His teeth are usually {} depending on the coffee.”.format(teeth))
# this line is tricky, try to get it exactly right
print (“If I add {:d}, {:f} and {:f} ,I get {:f}.”.format(age,height_centimeter,weight_kilogram,age + height_centimeter + weight_kilogram))


留下评论

《learn python the hard way(笨办法学 Python)》 习题 python3重写版(ex1~ex4)

EX1

# -*- coding: utf-8 -*-

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.’)
#print的使用:
#print([object, …][, sep=’ ‘][, end=’\n’][, file=sys.stdout])
#
#
#Use this construct:
#for item in [1,2,3,4]:
# print(item, ” “, end=””)
#
#This will generate:
#1 2 3 4
#
#See this Python doc for more information:
#
#Old: print x, # Trailing comma suppresses newline
#New: print(x, end=” “) # Appends a space instead of a newline
#
#–Aside:
#in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,
#
#print(‘this’,’is’, ‘a’, ‘test’) # default single space between items
#this is a test
#
#print(‘this’,’is’, ‘a’, ‘test’, sep=””) # no spaces between items
#thisisatest
#
#print(‘this’,’is’, ‘a’, ‘test’, sep=”–*–“) # user specified separation
#this–*–is–*–a–*–test

==================================================================

EX2

# 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

# You can also use a comment to “disable” or comment out a piece of code:
# print “This won’t run.”
print (“This will run.”)

==================================================================

EX3

print (“I will now count my chickens:”)

print (“Hens”, 25 + 30 / 6)
print (“Roosters”, 100 – 25 * 3 % 4)
print (“Roosters”, round(100 – 25 * 3 % 4,3))

# round(number[, ndigits])
# Return the floating point value number rounded to ndigits digits after the decimal point. If ndigits is omitted, it defaults to zero.

print (“Now I will count the eggs:”)

print ( 3 + 2 + 1 – 5 + 4 % 2 – 1 / 4 + 6 )
print (“4 % 2”,4 % 2)
print (- 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)

==========================================================

EX4

#关于浮点数: http://zh.wikipedia.org/zh/%E6%B5%AE%E7%82%B9%E6%95%B0
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.”)