7.3 循环结构
7.3.1 while循环
字符串拼接的方式:
1.str()
2.占位符 %s
3.print(“1+2+3+4的值”,num)
4.print(“1+2+3+4的值{}”.format(num))
while 条件:
#缩进
#循环体
补充:
dir(模块/对象/类) -------------- 调取模块中所有的属性和方法
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’,
‘TWOPI’, ‘Sequence’, ‘Set’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’,
‘accumulate’, ‘acos’, ‘bisect’, ‘ceil’, ‘cos’, ‘e’, ‘exp’, ‘floor’, ‘inst’, ‘log’, ‘os’, ‘pi’, ‘random’, ‘repeat’, ‘sha512’,
‘sin’, ‘sqrt’, ‘test’, ‘test_generator’, ‘urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’,
‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’,
‘randbytes’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’,
‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]
help(属性或者方法) ------- 调取帮助文档
练习:1.求100以内所有奇数的和
# sum = 0
# n = 1
# while n < 100:
# sum = sum + n
# n += 2
# print(sum)
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
2 打印三角形(要求:输入要打印的层数)
*
**
***
****
*****
layer = int(input("请输入要打印的层数"))
index = 1
while index <= layer:
#每层*的个数
j = 1
while j <= index:
print("*",end="")#help(print)------end换行
j += 1
print()
index += 1
- 打印九九乘法表
i = 1
while i <= 9:
j = 1
while j <= i:
print("%s X %s = %s " %(i,j,(i*j)),end = "")
j += 1
print()
i += 1
- 判断一个数是否为质数(素数)
num = eval(input('请输入一个数字:'))
if num <= 1:
print('这不是质数')
elif num == 2:
print('这是一个质数!')
else:
i=2
while i < num:
if num%i == 0:
print('这不是一个质数')
break
i += 1
else:
print ('这是一个质数!')