解决中文乱码问题
在开头加上
-*- encoding:utf-8 -*-
if条件
if 条件:
结果
#if elif else是单选,只走一条路
1 num = input('Please input a number:') 2 if num == '1': 3 print(111) 4 print(323) #只要缩进就表示在if的循环里 5 elif num == '2': 6 print('good') 7 elif num == '3': 8 print('wonferful') 9 else: 10 print('有误!')
while循环
while 条件:
循环体
无限循环:
终止循环 1.改变条件:使其不成立
2.break
continue:结束单次循环
while
else #当while中被break打断时,else下的语句不会进入
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
计算 1-2+3-4+....-99除了88那一项之和 count = 1 sum = 0 while count < 100: if count == 88: count += 1 continue elif count %2 ==1: sum += count else: sum -= count count += 1 print("1-2+3-4+...-99=",sum)
格式化输出
1 name = input('Please input a name:') 2 age = input('Please input an age:') 3 height = input('Please input a height:') 4 msg = "我叫%s,今年%s岁,身高%s,学习进度3%%" %(name,age,height) 5 print(msg)
用户交互-->input出来的全部都是字符串
实例--允许最多输入3次
1 count = 1 2 while count <= 3: 3 name = input('input name:') 4 psd = input('input password:') 5 if name == 'mary' and psd == '22': 6 print('success login!') 7 break 8 else: 9 print('Error input,input again,you can input %d times!' %(3-count)) 10 if count == 3: 11 result = input('Have a try(Yes or No)') 12 if result == 'Yes': 13 print('Have no opportunity,stupid!') 14 count += 1
运算符-->and or not
优先级:() > not >and >or
其中:x or y #如果x为真(非0),则返回x,否则返回y
1 print(1 or 4) #返回1 2 print(0 or 10) #返回10
x and y #如果x为真(非0),则返回y,否则返回x
1 print(1 and 4) #返回4 2 print(0 and 10)#返回0
int转换成bool
非零转换成bool结果为True,0转换成bool是False
str转换成bool
#非空字符串即为True str1 = '' a = bool(str1) print(a) #结果False str2 = ' ' b = bool(str2) print(b) #结果True