布尔值 Boolean,True和False(注意True和False的首字母是大写的)
0、0.0、空字符串”被认为是False,其他值为True
比较操作符
# ==, !=, >, <, >=, <=
# 整型或浮点值永远不会与字符串相等
# 整型可以和浮点型比较
>>> '23' == 23
False
>>> 23 >= 22
True
>>> 23 != 23.0000
False
>>> 23 == 23.000000
True
>>> 'aabbcc' != 'aabbcc'
False
布尔操作符
# and, or, not,优先级为not,and,or
#!/usr/bin/env python3
# coding=utf-8
name = input("Please enter your name:")
if name == 'Mary':
print("Hello Mary")
password = input("Please enter your password:")
if password == 'hello':
print('Access granted')
else:
print('Wrong password')
age = int(input("Please enter your age: "))
if age < 0 :
print("age cannot less than zero")
elif age < 18:
print("you are too young for the game")
elif age < 70:
print("ok")
else:
print("you are too old for the game")
#!/usr/bin/env python3
# coding=utf-8
name = ''
while name != 'your name':
print("Please enter your name")
name = input()
print('Thank you!')
break语句,退出当前循环
#!/usr/bin/env python3
# coding=utf-8
count = 0
name = ''
while name != 'your name':
print('Please enter your name')
if count < 3:
name = input()
else:
print("All chance is used")
break #尝试次数大于三次,跳出当前循环
count += 1
print('you have tried ' + str(count) + ' times. You have ' + str(3 - count) + 'chance to test' )
print('Thank you, you have tried ' + str(count) + ' times.')
continue语句,跳过当次循环,跳回到循环语句开始处重新对循环条件求值
#!/usr/bin/env python3
# coding=utf-8
while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('hello, Joe. What is the passward?(hello)')
passward = input()
if passward == 'hello':
break
print('Access granted')
#!/usr/bin/env python3
# coding=utf-8
total = 0
for i in range(101):
total += i
print(total)
for循环可用等价的while循环实现,只是for循环更简洁
#!/usr/bin/env python3
# coding=utf-8
i = 0
total = 0
while i < 101:
total += i
i += 1
print(total)
range()函数可以有三个参数,参数之间用逗号隔开
1. 第一个参数是for循环变量的起始值,缺省为0
2. 第二个参数是for循环变量的终止值,但不包含它
3. 第三个参数是步长,每次迭代后循环变量增加的值,缺省为1
>>> for i in range(3):
print(i)
0
1
2
>>> for i in range(-2, 2):
print(i)
-2
-1
0
1
>>> for i in range(-5, 10, 5):
print(i)
-5
0
5
>>>
内建函数:Python程序可以调用的一组基本的函数,比如print(),input(),len()
标准库:一组模块,每个模块都是一个Python程序,包含一组相关的函数,比如math,random
1. 使用一个模块,需要import语句导入该模块
2. import 模块名1,模块名2,……模块名n
3. 使用模块中的函数,模块名.函数名
#!/usr/bin/env python3
# coding=utf-8
import random
for i in range(5):
print(random.randint(1,10))
from 模块 import *, 调用模块中的函数时不需要模块名.前缀
但是使用完整的名称更具可读性
#!/usr/bin/env python3
# coding=utf-8
from random import *
for i in range(5):
print(randint(1,10))
先导入sys模块
#!/usr/bin/env python3
# coding=utf-8
import sys
while True:
print('Type exit to exit')
response = input()
if response == 'exit':
sys.exit()
print('You typed '+response+'.')