《 笨方法学 Python 》_ 习题 2 - 5

习题 2:注释和 # 号
# 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.")

习题 3:数字和数学计算
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("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)

习题 4:变量和命名
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 acailable.")
print("Thers 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.")


习题 5:更多的变量和打印
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 = 'Brown'

print("Let's talk about %s." % my_name)
print("He's %d inches tall." % my_height)
print("He's %d pounds heavy." % my_height)
print("Actually that's not too heavy.")
print("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print("His teeth are usually %s depending on the coffee." % my_teeth)

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


Python 格式化字符:

%c     格式化字符及其ASCII码
%s     格式化字符串
%d     格式化整数
%u     格式化无符号整型
%o     格式化无符号八进制数
%x     格式化无符号十六进制数
%X     格式化无符号十六进制数(大写)
%f     格式化浮点数字,可指定小数点后的精度
%e     用科学计数法格式化浮点数
%E     作用同%e,用科学计数法格式化浮点数
%g     %f和%e的简写
%G     %f 和 %E 的简写
%p     用十六进制数格式化变量的地址

猜你喜欢

转载自blog.csdn.net/yz19930510/article/details/80514904
今日推荐