欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

笨办法学python2.0习题1-10

时间:2023-04-29
习题1 第一个程序

print('hello wrold')print('Hello Again')print('I like typing this')print('this is fun')print('Yah!Printing.')print("I'd much rather you 'not'.")print("i 'said'do not touch this")

#附加题1 让你的脚本再多打印一行。

print('n')

#附加题2 让你的脚本只打印一行。
知识点

python的print(" “)换行问题
print(” “)执行后,默认换行,光标停留在下一行.
要让print(” ")执行输出后不换行,方法:print("XXXXX “,end=” “)
原因:print(” “)之所以换行是因为print里的字符串”"的最后一个end为/n,即换行,要使其不换行,只需改变end即可

help(print)Help on built-in function print in module builtins:print(...) print(value, ..., sep=' ', end='n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.

print('hello wrold',end=" ")print('Hello Again',end=" ")print('I like typing this',end=" ")print('this is fun',end=" ")print('Yah!Printing.',end=" ")print("I'd much rather you 'not'.",end=" ")print("i 'said'do not touch this",end=" ")

#.附加题3 在一行的起始位置放一个 ‘#’ (octothorpe) 符号。它的作用是什么?
注释作用 HASH
程序里的注释是很重要的。它们可以用自然语言告诉你某段代码的功能是什么。在你
想要临时移除一段代码时,你还可以用注解的方式将这段代码临时禁用。

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

3.1 and 3.2

#打印一行字 我要计算我有多少鸡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 way it's False")#打印一行字 我们来计算下别的print("How about some more.")#打印并计算print("Is it greater?",5 >= -2)#打印并计算print("Is it less or equal?",5 <= -2)

3.3附加题

print("我的电信宽带500M 下个2G的电影要多少秒")print((2*1024)/(500/8))print(round(((2*1024)/(500/8)),2))

3.4 浮点数
浮点数,简单说就是有小数部分的数例如 3.0。
python2 在处理除法运算时整数相除只能保留整数部分,若想保留小数部分需要使用浮点数相除。python3 则可以正确处理。
目前了解的是所有常见的编程语言在十进制浮点数运算时都会遇到不准确的问题,python会尽力找一种精确的结果来显示,不过好在我们有其他办法获得更精确的十进制浮点数。

3.4.1、如何精确 python 浮点数python默认的浮点数是17位,我们通常用不到这么多,这样可以使用python内置函数 round() 或 格式化字符两种方式来精确小数位。而如果需要更多位数则可 以考虑用 decimal 模块round函数描述round() 方法返回浮点数 x 的四舍五入值,准确的说保留值将保留到离上一位更近的一端(四舍六入)。精度要求高的,不建议使用该函数。语法以下是 round() 方法的语法:round( x [, n] )参数x -- 数字表达式。n -- 表示从小数点位数,其中 x 需要四舍五入,默认值为 0。返回值返回浮点数x的四舍五入值。

习题4

4.0.1

cars = 100 #表示汽车数量的变量space_in_a_car = 4.0 #表示车辆乘坐容量drivers = 30 #表示现有司机数量的变量passengers = 90 #表示现有乘客数量的变量cars_not_driven = cars - drivers #表示没有司机操作的车辆的数量的变量cars_driven = drivers #表示有司机操作的车辆的变量carpool_capactiy = 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_capactiy,"people today.")print("We have",passengers,"to carpool today")print("We need to put about",average_passengers_per_car,"in each car")

运行结果There are 100 cars available.There are only 30 drivers available.There will be 70 empty cars todayWe can transport 120.0 people today.We have 90 to carpool todayWe need to put about 3.0 in each car进程已结束,退出代码0

4.0.2Traceback (most recent call last): File "ex4.py", line 8, in #第八行内容中average_passengers_per_car = car_pool_capacity / passenger NameError: name 'car_pool_capacity' is not defined #变量名称错误 找不到该变量4.0.3我在程序里用了 4.0 作为 space_in_a_car 的值,这样做有必要吗?如果只用 4 会有什么问题?答:没必要使用浮点数,因为:在 python2 中,整数在参与除法运算时才有可能产生小数部分被舍弃的问题, space_in_a_car 并未参与除法运算。在 python3 中,在处理出发时会自动变为浮点数,因此也不用使用浮点数。(就像我在 python3 环境中运行结果的最后一行)

习题5

my_name = "Zed A、Shaw"my_age = 35 # not a liemy_height = 74 #inchesmy_weight = 180 # lbsmy_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_weight )print("Acrually 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 is exactly righteprint("If I add %d,%d,and %d I get %d." % (my_age,my_height,my_weight,my_age+my_height+my_weight))

5.0.1 修改所有的变量名字,把它们前面的 ‘‘my_‘‘去掉。确认将每一个地方的都改掉,不只是你使用 ‘‘=‘‘赋值过的地方

name = "Zed A、Shaw"age = 35 # not a lieheight = 74 #inchesweight = 180 # lbseyes = 'Blue'teeth ='White'hair = 'Brown'print("Let's talk about %s." % name)print("He's %d inches tall." % height)print("He's %d pounds heavy." % weight )print("Acrually that's not too heavy")print("He's got %s eyes and %s hair" % (eyes,hair))print("His teeth are usually %s depending on the coffee." % teeth)# this lin is tricky ,try to get is exactly rightprint("If I add %d,%d,and %d I get %d." % (age,height,weight,age + height + weight))

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

print("Zed A.SHaw height is %.1f cm" % (height * 2.54))print("Zed A.SHaw weight is %.1f KG" % (weight * 0.45))

习题6

#定义一个变量xx = "There are %d types of people." % 10#定义一个变量binarybinary = "binary"#定义一个变量do_notdo_not = "don't"#定义一个变量yy = "Those who know %s and those who %s." %(binary,do_not)#打印变量xprint(x)#打印变量yprint(y)#打印字符串和格式化xprint("I said: %r."%x)#打印字符串和格式化yprint("I also said:'%s'."%y)#定义变量hilarioushilarious = False#定义变量 joke_evaluationjoke_evaluation = "Isn't that joke so funny?! %r"#打印字符串和格式化字符串print(joke_evaluation % hilarious)#定义ww = "This is the left side of ..."#定义ee = "a string with a right side"#打印两个变量print(w + e )

**6.0.3**木有了,其他两处看起来像但不是。因为没有引号,不是字符串:x = "There are %d types of people." % 10# 这里 10 是数字,不是字符串。如果是 '10' 就是了hilarious = Falsejoke_evaluation = "Isn't that joke so funny?! %r"# 如同我在注视中所写,这里是 hilarious 是布尔型变量,而非字符串**6.0.4** 解释一下为什么 w 和 e 用 + 连起来就可以生成一个更长的字符串字符串可以串联

习题7

print("Mary had a little lamb.")print("Its fleece was white as %s." % '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 happensprint(end1 + end2 + end3 + end4 + end5 + end6,)print(end7 + end8 + end9 + end10 + end11 + end12)

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

7.0.1 watch that comma at the end、try removing it to see what happens
逗号在 print 中的作用是分隔多个待打印的值,并在打印时变为空格分隔不太的值

习题8

formatter = "%r %r %r %r"print(formatter % (1,2,3,4))print(formatter % ("one","two","three","four"))print(formatter % (True,False,False,True))print(formatter % (formatter,formatter,formatter,formatter))print(formatter %( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ))

1 2 3 4'one' 'two' 'three' 'four'True False False True'%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r''I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

注意最后的双引号原因在于 %r 格式化字符后是显示字符的原始数据。而字符串的原始数据包含引号,所以我们看到其他字符串被格式化后显示单引号。而这条双引号的字符串是因为原始字符串中有了单引号,为避免字符意外截断,python 自动为这段字符串添加了双引号。

习题9

days = "Mon Tue Wen Thu Fri Sat Sun"months = "nJannFebnMarnAprnMaynJunnJulnAug"print("Here are the days:",days)print("Here are the months:",months)print("""There's somthing 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.""")

Here are the days: Mon Tue Wen Thu Fri Sat SunHere are the months: JanFebMarAprMayJunJulAugThere's somthing 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

print("I am 6'2" tall.")tabby_cat = "tI'm tabbed in."persian_cat = "I'm splitnon a line."backslash_cat = "I'm \ a \ cat."fat_cat ="""I'll do a listt* Cat foodt* Fishiest* Catnipnt* Grass"""print(tabby_cat)print(persian_cat)print(backslash_cat)print(fat_cat)

10.0.2 使用 ''' (三个单引号) 取代三个双引号,看看效果是不是一样的? Ture!10.0.3

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。