python中比较操作符有:
> >= < <= == !=
这些操作符返回True或False
1 >>> 1 < 3
2 True
3 >>> 1 > 3
4 False
5 >>> 1 == 1
6 True
7 >>> 1 != 1
8 False
9 >>> 1 == 2
10 False
11 >>> 1 != 2
12 True
分支语法
if 条件:
循环体
else:
循环体
number = 5
guess = int(input("please input a number:"))
if guess == number:
print("T")
else:
print("F")
多次分支语法
if 条件:
循环体
elif 条件:
循环体
else:
循环体
scores = int(input("please input your score:")) if scores >= 90:
print("A")
elif scores >= 80:
print("B")
elif scores >= 70:
print("C")
elif scores >= 60:
print("D")
else:
print("E")
while循环语法
while 条件:
循环体
i = 0
while i < 10:
print(i)
i += 1
一个例子:
import random
secret = random.randint(1,10)
print("----------you are welcome----------") for i in range(3):
guess = int(input("please input a number:")) if guess == secret:
print("right")
break
elif guess > secret:
print("much big")
else:
print("much small")
else:
print("the number is ", secret) print("Over")
条件表达式
语法:x if 条件 else y
x, y = 4, 5
small = x if x < y else y
print(small)
断言assert
assert关键字被成为“断言”,当这个关键字后边的条件为假的时候程序会自动崩溃并抛出AssertionError的异常。例如:
>>> assert 3 > 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
一般来说,可以用Ta在程序中置入检查点,当需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert关键字就非常有用了。
for循环语法
for 目标 in 表达式:
循环体
Python中for循环非常智能和强大,可以自动调用可迭代对象的迭代器,返回下一个迭代对象。表达式是一个可迭代对象,如列表,元组,字符串,字典等。
>>> favourite = "python"
>>> for i in favourite:
... print(i)
...
p
y
t
h
o
n
>>> number = ['one', 'two', 'three', 'four']
>>> for i in number:
... print(i)
...
one
two
three
four
range()
语法:range([start, ]stop[,step = 1])
生成从start开始,步长为step,到stop参数的值结束的数字序列。通常搭配for循环使用。
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(5,10,2))
[5, 7, 9]
break 和 continue
break:跳出循环
continue:结束本次循环