python中的if和while小节
今天结合input和if改的一个小用例
# -*- coding: utf-8 -*- a = input('请输入数值:') print('第一次a出现的类型',type(a)) if int(a)>0: print(int(a)) print('第二次a出现的类型',type(int(a))) else: print(-int(a)) print('第二次a出现的类型',type(-int(a)))
用例来源于廖雪峰的python3,如下:
name = input() print('hello,', name)
# print absolute value of an integer: a = 100 if a >= 0: print(a) else: print(-a)
那么如果将变量改成可以随机输入的话,可以省得重新改代码就可以重新输入一个新的数值了。
至于为什么加入type()主要还是刚开始的时候没有注意到str和int类的区别,是用来查看类型的。
开头a = input('请输入数值:')中a是一个str的字符变量,而到if中需要的是一个整形变量,所以需要用int来将str的a改变成整形变量,才能够去掉负号。
请输入数值:-23 第一次a出现的类型 <class 'str'> 23 第二次a出现的类型 <class 'int'>
当然还有学习几个其他的小用例如:
# 使用while打印出12345689 n=1 while n<11: if n==7: pass else: print(n) n = n + 1 print('end')
结果如下
1
2
3
4
5
6
8
9
10
end
用例二
#使用while求1-100的加法 n = 1 s = 0 while n < 101: s = s + n n = n + 1 print(s) # 使用rang()函数显然会更简便一些,range(101)是[0,100]内的数。 a = range(101) print(sum(a))
用例三
#使用while求1-100内的奇数 n =1 while n < 101: if n%2 == 1: print('100内的奇数:',n) else: pass #用pass来跳过不需要的步骤是循环语句完整 n = n + 1 #使用while求1-100内的偶数 n =1 while n < 101: if n%2 == 0: print('100内的偶数:',n) else: pass #用pass来跳过不需要的步骤是循环语句完整 n = n + 1
用例四
# 求1-2+3-4+5...+99的和 n = 1 s = 0 while n < 100: if n%2==0: s = s - n else: s = s + n n = n + 1 print(s)
用例五,用户密码核对以后加元组数据库结,调用数据库,登录界面的一小部分有了。其中的一种情况:
#!/usr/bin/u/ubv/a python #支持python2和3的格式 # -*- coding: utf-8 -*- # 用户登陆(三次机会重试) count = 0 while count < 3: user = input('请输入用户名:') pwd = input('请输入密码:') if user == 'alex' and pwd == '123': print('欢迎登陆') print('精彩内容稍后加载') break else: print('用户名或者密码错误') count = count + 1
当然while中的continue和break也是一大重点,以下的小例子来体现:
# -*- coding: utf-8 -*- count = 0 while count <10: count = count +1 print(count) continue #满足条件之后,继续执行直到不满足条件跳出循环 print('没有被执行到') #在continue和break后面的代码是不被执行的 print('end')
结果:
C:\Users\Administrator\PycharmProjects\python_s3\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/python_s3/day_10/while_if.py 1 2 3 4 5 6 7 8 9 10 end Process finished with exit code 0
另一种break的:
# -*- coding: utf-8 -*- count = 0 while count <10: count = count +1 print(count) break #满足条件之后就直接跳出循环 print('没有被执行到') #在continue和break后面的代码是不被执行的 print('end')
结果:
C:\Users\Administrator\PycharmProjects\python_s3\venv\Scripts\python.exe C:/Users/Administrator/PycharmProjects/python_s3/day_10/while_if.py 1 end Process finished with exit code 0