python小白入门知识2

一:逻辑计算

#and or not
优先级,()> not > and > or

print(2 > 1 and 1 < 4)
print(2 > 1 and 1 < 4 or 2 < 3 and 9 > 6 or 2 < 4 and 3 < 2)
T or T or F
View Code

#T or F

1 print(3>4 or 4<3 and 1==1)  # F
2 print(1 < 2 and 3 < 4 or 1>2)  # T
3 print(2 > 1 and 3 < 4 or 4 > 5 and 2 < 1)  # T
4 print(1 > 2 and 3 < 4 or 4 > 5 and 2 > 1 or 9 < 8)  # F
5 print(1 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6)  # F
6 print(not 2 > 1 and 3 < 4 or 4 > 5 and 2 > 1 and 9 > 8 or 7 < 6) # F
View Code

#ps  int  ----> bool   非零转换成bool True   0 转换成bool 是False

1 print(bool(2))
2 print(bool(-2))
3 print(bool(0))
View Code

#bool --->int

1 print(int(True))   # 1
2 print(int(False))  # 0
View Code

'''x or y x True,则返回x'''

1 print(1 or 2)  # 1
2 print(3 or 2)  # 3
3 print(0 or 2)  # 2
4 print(0 or 100)  # 100
5 print(2 or 100 or 3 or 4)  # 2
6 print(0 or 4 and 3 or 2)
View Code

'''x and y x True,则返回y'''

1 print(1 and 2)
2 print(0 and 2)
3 print(2 or 1 < 3)
4 print(3 > 1 or 2 and 2)
View Code

二:例子

1、使用while循环输入 1 2 3 4 5 6 8 9 10

 1 count = 0
 2 while count < 10:
 3     count += 1  # count = count + 1
 4     if count == 7:
 5         print(' ')
 6     else:
 7         print(count)
 8 
 9 count = 0
10 while count < 10:
11     count += 1  # count = count + 1
12     if count == 7:
13         continue
14     print(count)
View Code

2、输出 1-100 内的所有奇数

 1 方法一:
 2  count = 1
 3  while count < 101:
 4      print(count)
 5      count += 2
 6 方法二:
 7  count = 1
 8  while count < 101:
 9      if count % 2 == 1:
10          print(count)
11      count += 1
View Code

3、求1-2+3-4+5 ... 99的所有数的和

1  sum = 0
2  count = 1
3  while count < 100:
4      if count % 2 == 0:
5          sum = sum - count
6      else:
7          sum = sum + count
8      count += 1
9  print(sum)
View Code

4、用户登陆(三次机会重试)input 心中有账号,密码 while

1 i = 0
2 while i < 3:
3     username = input('请输入账号:')
4     password = int(input('请输入密码:'))
5     if username == '咸鱼哥' and password == 123:
6         print('登录成功')
7     else:
8         print('登录失败请重新登录')
9     i += 1
View Code

三:格式化输出 % s d

 1 name = input('请输入姓名')
 2 age = input('请输入年龄')
 3 height = input('请输入身高')
 4 msg = "我叫%s,今年%s 身高 %s" %(name,age,height)
 5 print(msg)
 6 
 7 name = input('请输入姓名:')
 8 age = input('请输入年龄:')
 9 job = input('请输入工作:')
10 hobbie = input('你的爱好:')
11 
12 msg = '''------------ info of %s -----------
13 Name  : %s
14 Age   : %d
15 job   : %s
16 Hobbie: %s
17 ------------- end -----------------''' %(name,name,int(age),job,hobbie)
18 print(msg)
19 
20 
21 name = input('请输入姓名')
22 age = input('请输入年龄')
23 height = input('请输入身高')
24 msg = "我叫%s,今年%s 身高 %s 学习进度为3%%s" %(name,age,height)
25 print(msg)
View Code

猜你喜欢

转载自www.cnblogs.com/huihuangyan/p/12944433.html