简单的一个求1到输入数的和的问题: 1、题目: ①输入一个数字,计算完成第一轮后,用户通过输入‘y’或者‘n’来决定继续执行还是结束; ②如果输入的不是‘y’或者‘n’就提示输入非法,然后重复要求用户输入y或者n;--到这一步都能实现 2、当前遇到的问题: ①当输入n时,我想结束整个程序,但目前我的代码是输入n时,只能结束判断是否继续的循环,不能结束整个循环; ②当我把break用于结束最上层的while循环时,就变成无论y或者n,都结束整个循环了; 我始终想不出该怎么实现,百度了些资料,可能是我表述的问题,一直搜不出想要的答案,求各位大佬解惑,代码如下:
while 1>0:
a = 1
sum = 0
num = int(input('please input a number:'))
while a <= num:
sum = sum + a;
a += 1;
print("the sum of 1 to %d is: %d" % (num, sum));
while True :
pro = str(input("是否继续? 继续:y,结束:n"))
if pro == 'y':
break;
if pro != 'n' and 'y':
print('非法命令,请重新输入!')
continue;
else:
print('bye')
break;
pro = ''
while pro != 'n':
a = 1
sum = 0
num = int(input('please input a number:'))
while a <= num:
sum = sum + a;
a += 1;
print("the sum of 1 to %d is: %d" % (num, sum));
while True :
pro = str(input("是否继续? 继续:y,结束:n"))
if pro == 'y':
break;
if pro != 'n' and 'y':
print('非法命令,请重新输入!')
continue;
else:
print('bye')
break;
你需要一个变量来控制主循环 关注我学python基础
i = 1
while i:
a = 1
sum = 0
num = int(input('please input a number:'))
while a <= num:
sum = sum + a
a += 1
print("the sum of 1 to %d is: %d" % (num, sum))
while True:
pro = str(input("是否继续? 继续:y,结束:n"))
if pro != 'n' and pro != 'y':
print('非法命令,请重新输入!')
continue
if pro == 'y':
break
if pro == 'n':
print('bye')
i = 0
break
while True:
a = 1
sum = 0
num = int(input('please input a number:'))
while a <= num:
sum = sum + a
a += 1
print("the sum of 1 to %d is: %d" % (num, sum))
pro = str(input("是否继续? 继续:y,结束:n"))
if pro == 'n':
print('bye')
break
if pro != 'n' and pro != 'y':
print('非法命令,请重新输入!')
continue
没有必要写两层while,一层就够了
把第11行去掉,下面的代码回一步缩进