05笨方法学Python|ex27-ex34
2018-01-27 本文已影响13人
ericazhan
ex27
True 和False 的首字母必须大写。
ex28
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
ex29
写完if语句后,下一行print命令如果不缩进,就会报错。
写完要加冒号的东西,如function,if,里面的内容都需要TAB缩进,以此告诉电脑,这是一个block的。
ex 30
- 每一个 if 开启一个岔路口;
elif 只是其中一条分支;
else 是除上所述的所有剩余分支。 - 如果多个elif语句为真,会怎样?
Python的启动和运行只会针对第一个为真的代码块,所以你说的那种情况,只会执行第一块。
ex31
- 每一个选择都要加冒号:
- Q: 可以用if-else替换elif 吗?
某些情况下可以, 但是这个也依赖于每一个if/else是怎么写的 。这也意味着, Python会检查每个if-else的组合,而不是只检查if-elif-else组合中的第一个为假的分支,尝试用两种方式多编写一些代码,以找出他们的不同点。 - 怎么表达数字的范围?
两种选择:
经典语句是 0 < x < 10 or 1 <= x < 10
或者 x in range(1, 10).
num = raw_input("give me a number. ")
numm = float(num)
if numm < 0.:
print "This is a negative."
elif numm in range(1,10):
print "It's in the range of 1 to 10."
elif numm > 100:
print "more than 100!"
else:
print "Game over."
ex32
- 关于range
range可以生成一串整数,来配合for循环。
在range里,默认起始是0。
range有两种写法:
range(stop)
stop表示生成几个整数,“数目”
ex: range(3) ==[0,1,2]
range([start], stop[, step])
stop表示截止到哪个数,但不包括这个数;
step是间隔,如果不写,默认是1。
ex: range(0, -10, -2) == [0,-2,-4,-6,-8] #是的,可以是负数。
猜猜这个程序会输出什么结果?
for i in range(99, 0, -1):
if i == 1:
print "1 bottle of beer on the wall, 1 bottle of beer!"
print 'So take it down, pass it around, no more bottles of beer on the wall!'
elif i == 2:
print '2 more bottles of beer on the wall, 2 more bottles of beer!'
print 'So take one down, pass it around, 1 more bottle of beer on the wall!'
else:
print "%r bottles of beer on the wall, %r bottles of beer!" %(i,i)
print "So take it down, pass it around, %r more bottles of beer on the wall!" %(i-1)
以上关于range的解释和题目来源于这个网页:pythoncentral
for i in range(5):
a = i + 1
print a
#-----这两个代码打印的结果很不一样!--------
for i in range(5):
a = i + 1
print a
- 注意选择 [ ] 和( )
range后面用 ( )
打印列表中某个项是 [ ]
append后面是 ( )
for i in range(0,len_fruits):
elements.append(i)
for i in elements:
print elements[i]
- 关于 list
发现google上有非常好的 python course,排版很漂亮,而且是python 2, 点击看list 这节
除了append,其他常用的method有:
list method
来源:programiz 还有互动敲代码窗口~
ex33
附加题参考以下:
https://stackoverflow.com/a/24353790
ex34
ordinal number 序数词,如第一,第二,第三。。
cardinal number 基数词,如0,1,2,3。。。
注意,在python里,序数由0开始。所以0,对应列表list 里的第一。
#-*- coding:utf-8 -*-
goals = ["carrier","development","entertainment","finance","health","contribution","relationship"]
def plan(a):
content = goals[a-1]
print "The thing you want to do is of order %d, in the position %d." %(a,(a-1))
print "You have these choices for your next year."
print goals
choice = int(raw_input("What you want to do in the year 2018? "))
if choice in range(1,8):
plan(choice)
else:
print "You should give me a number from 1 to 6"
最近在排新年计划,正好顺手用了一下,哈~