I've made this console application and it works...but only when you enter small numbers in the input like 1 in 'ifrom', 2 in 'step', and 3 in 'to'...but when I enter bigger numbers in 'to' for example 100 it just do nothing!!! It even doesn't give me any error! Thanks!

print("---Average2---"+"\n")

sum=0
average=0
counter=0

while True:
    ifrom=int(input("From: "))
    step=int(input("Step: "))
    to=int(input("To: "))
    while sum<=to:
        sum=ifrom+step
        counter+=1
        if sum==to:
            print("\n"+"The sum is: ",sum)
            average=sum/counter
            print("The average is: ",average,"\n")
            sum=0
            average=0
            counter=0
            break

推荐答案

There are two reasons of this behavior

  1. You're adding constantly sum = ifrom + step which is a constant value (in your example: 1 + 2 = 3). So in every loop iteration your sum will be 3 and will never hit 100
  2. Even if you fix the first problem, your example sum variable is going to be 1, 3, 5, ..., 99, 101, .... You're checking if the sum is 100 and the program is doing nothing, because it will bever hit 100.

Possible solutions:

  • use range syntax (recommended - you can use this solution )

  • check if the variable reached 100 (instead of checking if it is equal 100) like below:

print("---Average2---"+"\n")

average=0
counter=0
tmp=0

while True:
   ifrom=int(input("From: "))
   step=int(input("Step: "))
   to=int(input("To: "))
   tmp = ifrom
   sum = tmp
   while tmp<=to:
       tmp+=step
       sum+=tmp
       counter+=1
       if tmp>=to:
           if tmp>to:
             sum-=tmp
           print("\n"+"The sum is: ",sum)
           average=sum/counter
           print("The average is: ",average,"\n")
           sum=0
           average=0
           counter=0
           break

Python相关问答推荐

运行Python脚本时,用作命令行参数的SON文本

有症状地 destruct 了Python中的regex?

根据二元组列表在pandas中创建新列

Django REST Framework:无法正确地将值注释到多对多模型,不断得到错误字段名称字段对模型无效'<><>

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

当递归函数的返回值未绑定到变量时,非局部变量不更新:

Plotly Dash Creating Interactive Graph下拉列表

isinstance()在使用dill.dump和dill.load后,对列表中包含的对象失败

如何更改groupby作用域以找到满足掩码条件的第一个值?

如何在Pyplot表中舍入值

网格基于1.Y轴与2.x轴显示在matplotlib中

如何在海上配对图中使某些标记周围的黑色边框

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行

分解polars DataFrame列而不重复其他列值

上传文件并使用Panda打开时的Flask 问题

Scipy.linprog的可行性有问题吗?(A_ub@x0<;=b_ub).all()为True-但是-linprog(np.zeros_like(X0),A_ub=A_ub,b_ub=b_ub)不可行

使用Scikit的ValueError-了解

为什么这个正则表达式没有捕获最后一次输入?

为什么fizzbuzz在两个数字的条件出现在一个数字的条件之后时不起作用?

判断字典中是否有多个值对