今天和大家分享几个for循环的小练习
for循环
可迭代对象:range,字符串,列表,字典,,,,
for 变量 in 可迭代对象:
你自己的代码
练习1.:请统计一个字符串中数字的个数
count = 0
content = "abc123def01ght456"
for x in content:
if x.isdigit():
count += 1
print("总共有{}个数字".format(count))
练习2.请计算1——100以内(包括100)5的倍数的和以及 既是2又是3的倍数的和
result_5 = 0
result_2_and_3 = 0
for x in range(1, 101):
if x % 5 == 0:
result_5 += x
if x % 2 == 0 and x % 3 == 0:
result_2_and_3 += x
print("1-100所有5的倍数的和为{}".format(result_5))
print("1-100所有2和3的倍数的和为{}".format(result_2_and_3))
练习3.请计算1——100内的和,如果和的结果超过1000就不再计算了
total_result = 0
for x in range(1, 101):
total_result += x
if total_result >= 1000:
break # 跳出整个循环:
print(total_result)
练习4.请输入1——100以内所有的奇数
for x in range(1, 101):
if x % 2 == 1:
print(x)
综合练习
100以内(包括100)的猜数字游戏:三局两胜
1.最多比赛三次
2.谁先胜利两次就输出 ***胜利,不再进行第三次比试
3.若三次都比完,没人胜利则平局
4.规则:谁的数字大谁胜利,相同则平手
from random import randint
user_win = 0
computer_win = 0
tied = 0
# enum:枚举/列举
for idx, x in enumerate(range(3)):
print("---------------第{}局开始---------------".format(idx+1))
user_num = input("请用户输入一个数字")
user_num = int(user_num)
computer_num = randint(1, 100)
if user_num > computer_num:
result = "用户胜利了"
user_win += 1
elif user_num == computer_num:
result = "平局"
tied += 1
else:
result = "电脑胜利了"
computer_win += 1
print("电脑的数是{},用户的数是{},{}".format(computer_num, user_num, result))
print("---------------第{}局结束---------------\n\n".format(idx + 1))
if user_win == 2:
print("*" * 30+"\n最终结果:用户赢了两次!Game Over\n"+"*" * 30)
break
elif computer_win == 2:
print("*" * 30+"\n最终结果:电脑赢了两次!Game Over\n"+"*" * 30)
break
elif tied == 3:
print("*" * 30+"\n最终结果:平局\n"+"*" * 30)
elif tied + user_win == 3:
print("*" * 30+"\n最终结果:用户赢了,平局{}次\n".format(tied)+"*" * 30)
elif tied + computer_win == 3:
print("*" * 30+"\n最终结果:电脑赢了,平局{}次\n".format(tied)+"*" * 30)
今天就分享到这里,,,加油