python 语句 笔记

1 比较两个值相等 使用 ==

1.0==1 true

可以用双等号来测试两个字符串的内容是否相同,甚至可以将该测试限定在字符串的某个范围内

序列也可以用双等号比较,如果第个序列中同一位置的每个元素都相同,那么两个序列相等。顺序不同不相等

字典也可以比较,一个字典中的每个键与值 必须 与别外一个字典的键与值一一对应,顺序可以不同。

2 比较两个值不相等 使用!= 如果不相等则返回true 适用于序列、字典

3 比较大小 >< >= <=

如果比较两个包含多个字符的字符串,将观察每个字母,直到找到一个不同的字母为止。比较的结果将取决于不同的字母。

使用字符串的lower()/upper()方法,变为相同的大小写。

4 取反 not 注意要小写

not 5

not True

 5 and 对多个运算求真值。如果左边为true,接着对右边求值,如果左边不为true 就停止运算并肯输出结果False,不再继续运算

or 运算:左边是false继续对右边表达式求值,如果它为True,将停止对更多的表达式求值

6 判断:if true : 语句 如果条件为真则执行其下的缩进语句

  if   :

  elif :

  else:

7 循环:while 运算测试一个条件的真值 while :,for运算使用一个列表中的所有值 for in :

i=10

while i>0:

  print("lift off in:%s"%i)

  i=i-1

range(start,stop[,step]) 可创建一个整数列表,一般用在for循环中。

start 计数开始 默认从:0,stop 计数结束,不包括stop;step:步长,默认为1 

break 终止循环

continue语句 跳过当前循环折剩余部分,条件重新求值进行下一轮循环。

for food in ("pate","cheese","crackers","yogurt"):

  if food=="yogurt":

    break

else: 

  print("there is no yogurt!")

8 错误处理:try:语句后跟一个except:语句 错误的正式名称是 异常。

>>> try:
if contents["orange juice"]>3:
print("sure,let's have some juice")
except (KeyError) as error:

print("there is no %s"%error)

如果需要处理一个异常,但是以什么都不做的方式处理它,可以通过特殊词 pass忽略这种情形:

>>> try:
if contents["orange juice"]>3:
print("sure,let's have some juice")
except (KeyError):
pass

可以使用else:语句放在try:代码块的末端,在没有捕获到任意异常时,它将被执行。

except语句提供的第一个值定义了错误的类型,如果提供的是错误类型的元组,就是多个错误类型。可以在该值后面提供词as 以及用来引用包含错误信息的数据的名称。

9 缩进在python中扮演着重要的角色。缩进中的空格数也很重要。

 10 接收客户端输入:ho=input("enter your num:")

>>> if 1==True:
print("1 is true")
else:
print("1 is false")

>>> i=1
>>> print (i)
1
>>> for j in range(10):
if i==j:
print("i is in the range")
break;

>>> for j in range(10):
print(j)

>>> food="orange"
>>> fruits=["apple","peach","orange"]
>>> if food==fruits[0]:
print ("%s is in the list[0]"%food)
elif food==fruits[1]:
print("%s is in the list[1]"%food)
else:
print ("%s is not in the list[0] or list[1]"%food)

>>> food_sought="egg"

>>> for f in fridge:
if f==food_sought:
print ("key:%s value:%s"%(f,fridge[f]))
break;
else:
print("there is no key %s in the fridge"%food_sought)

>>> fridge={"egg":"this is an egg","orange":"this is an orange","apple":"this is and apple"}
>>> fridge.keys()
dict_keys(['egg', 'orange', 'apple'])
>>> list(fridge.keys())
['egg', 'orange', 'apple']
>>> fridge_list=list(fridge.keys())

>>> while len(fridge_list)>0:
current_f=fridge_list.pop()
print("%s",current_f)
else:
print("there is not any key")

>>> try:
print("%s"%fridge["peach"])
except(KeyError):
print("this is no key peach")


this is no key peach

原文地址:https://www.cnblogs.com/caojuansh/p/11328537.html