2021-05-18 1.for与while循环

1.

注释  加#单行注释,''' '''多行注释

关键词 import keyword - keyword.kwlist

格式化输出  %d数字占位符  %s字符串占位符

例1:

age = 18

print(f"我的年纪是{age}岁")

print(f"我的年纪是:%d岁" % age)

print("我的名字是:%s,我的国籍是:%s" % ("小王", "中国"))

print("www", "baidu", "com", sep=".")     # sep表示分割

print("hello", end="")

print("world", end="\t")    # 后面加一个tab即空格键

print("python", end="\n")  # 换行

print("end")



2.判断数值类型

a = "abc"

print(type(a))    # 输出a的类型

import random  # 引入随机数库

x = random.randint(0, 2)  # 随机生成[0,2],包含0,1,2

print(x)



3.for循环

for i in range(12):

print(i)

name = "chengdu"

for i in name:

print(i, end="\t")

a= ["aa", "bb", "cc", "dd"]

for i in range(len(a)):

print(i, a[i])



4. while循环

i = 0

while i < 5:

print("当前是第%d次循环"%(i+1))

print("i=%d"%i)

i += 1

例:1-100求和

n = 100

sum = 0

counter = 1

while counter <= n:

sum= sum + counter

counter += 1

print("1到%d的和为:%d"%(n, sum))



*break与continue

i = 0

while i <= 10:

i = i +1

print("-"*5)

if i == 5:

break      #结束整个循环

print(i)

i = 0

while i <= 10:

i = i +1

print("-"*5)

if i == 5:

continue      #结束本次循环

print(i)

你可能感兴趣的:(2021-05-18 1.for与while循环)