循环语句 while for
i = 0
while i < 10:
score = int(input('请输入一个成绩:'))
if score > 100 or score < 0:
break
# continue
else:
score //= 10
if score == 9 or score == 10:
print('A')
elif score == 8:
print('B')
elif score == 7:
print('C')
elif score == 6:
print('D')
else:
print('E')
i += 1
else:
print("10个成绩判断完成")
练习1:读入一个整型数,将其每一位倒序输出,不允许转换为字符串 1998
n = int(input('整型数:'))
while n > 0:
print(n % 10)
n = n // 10
练习2:将读入字符串的每一个成员倒序输出
s = input('请输入一个字符串:')
i = len(s)-1
while i >= 0:
print(s[i])
i -= 1
i = -1
while i >= -len(s):
print(s[i])
i -= 1
控制语句
判断用户输入的年份是否为闰年,闰年能被4整除并且不能被100整除,或者能被400整除的
year = int(input('年份:'))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print('{}是闰年'.format(year))
else:
print('{}是平年'.format(year))
多个条件:输入一个月份,判断其所属季节
month = int(input('月份:'))
if month < 1 or month > 12:
print('无效月份')
elif 3 <= month <= 5:
print('春天')
elif 6 <= month <= 8:
print('夏天')
elif month >= 9 and month <= 11:
print('秋天')
else:
print('冬天')
读入一个成绩,判断其所属等级
90~100 A
80~89 B
70~79 C
60~69 D
0~59 E
if score > 100 or score < 0:
pass(空段)
else:
score //= 10
if score == 9 or score == 10:
print('A')
elif score == 8:
print('B')
elif score == 7:
print('C')
elif score == 6:
print('D')
else:
print('E')
for...in循环
for i in range(10):
print(i)
i = 0
while i < 10:
print(i)
i += 1
print('*******************************')
for i in range(5, 10):
print(i)
i = 5
while i < 10:
print(i)
i += 1
print('*******************************')
for i in range(10, 5, -1):
print(i)
i = 10
while i > 5:
print(i)
i -= 1
print('*******************************')
遍历字符串
for i in 'python':
print(i)
练习题
'''
练习1:读入两个整型数,求得两个数中较大的一个
'''
num1, num2 = eval(input('读入两个整型数:'))
if num1 > num2:
print(num1)
else:
print(num2)
'''
练习2:读入一个字符串,不使用len函数,求得字符串的长度
'''
s = input('请输入一个字符串:')
n = 0
for i in s:
n += 1
print('字符串{}的长度是{}'.format(s, n))
'''
练习3:打印99乘法表
'''
for i in range(1, 10): # row
for j in range(1, i+1): # col
print('{}*{}={:<2}'.format(j, i, j*i), end=' ')
print()
'''
练习4:读入一个整型数,判断其是否为质数(除了1和本身不能被其它数整除的数)
'''
n = int(input('整数:'))
prime = True
i = 2
while i < n:
if n % i == 0:
prime = False
break
i += 1
if prime:
print('yes')
else:
print('no')