第16讲动动手第一题我这样写的程序为什么在else处报错
import randomcounts = int(input("请输入投币次数"))
i = 0
a = 0
b = 0
print("开始抛硬币实验:")
while i < counts:
if counts < 100:
num = random.randint(1,10)
if num % 2:
print("正面")
a += 1
else:
print("反面")
b += 1
i = i + 1
print("一个模拟了",counts,"次抛硬币,结果如下:")
print("正面:", a, "次",sep="")
print("反面:", b, "次",sep="")
else:
num = random.randint(1,10)
if num % 2:
a += 1
else:
b += 1
i = i + 1
print("一个模拟了",counts,"次抛硬币,结果如下:")
print("正面:", a, "次",sep="")
print("反面:", b, "次",sep="") 本帖最后由 jackz007 于 2022-11-7 20:10 编辑
很显然,那个 else 的缩进离群了。
import random
counts = int(input("请输入投币次数:"))
a = b = 0
print("开始抛硬币实验:")
for _ in range(counts):
num = random . randint(1 , 10)
if num % 2 : a += 1
else : b += 1
if counts < 100 :
print("正面") if num % 2 else print("反面")
print("一共模拟了" , counts , "次抛硬币 , 结果如下:")
print("正面:", a , "次" , sep="")
print("反面:", b , "次" , sep="") 我是这么理解的:
当第一次
print("一个模拟了",counts,"次抛硬币,结果如下:")
print("正面:", a, "次",sep="")
print("反面:", b, "次",sep="")
执行完成的时候python认为你的if语句已经完成。后面的else自然会出现语法错误。
修改如下:
import random
counts = int(input("请输入投币次数"))
i = 0
a = 0
b = 0
print("开始抛硬币实验:")
if counts < 100:
while i < counts:
num = random.randint(1,10)
if num % 2:
print("正面")
a += 1
else:
print("反面")
b += 1
i = i + 1
print("一个模拟了",counts,"次抛硬币,结果如下:")
print("正面:", a, "次",sep="")
print("反面:", b, "次",sep="")
else:
while i < counts:
num = random.randint(1,10)
if num % 2:
a += 1
else:
b += 1
i = i + 1
print("一个模拟了",counts,"次抛硬币,结果如下:")
print("正面:", a, "次",sep="")
print("反面:", b, "次",sep="")
页:
[1]