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
CodePudding user response:
There are two reasons of this behavior
- 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 be3
and will never hit 100 - Even if you fix the first problem, your example
sum
variable is going to be1, 3, 5, ..., 99, 101, ...
. You're checking if thesum
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
CodePudding user response:
You can remove the nested while loop by using built-in Python functions like range()
:
print("---Average2---" "\n")
s=0
average=0
counter=0
while True:
ifrom=int(input("From: "))
step=int(input("Step: "))
to=int(input("To: "))
l = list(range(ifrom, to, step))
s = sum(l)
average = s/len(l)
print("\n" "The sum is: ",s)
print("The average is: ",average,"\n")
break
Output: Note that the last number of the range to
is not inclusive
---Average2---
From: 0
Step: 1
To: 10
The sum is: 45
The average is: 4.5
CodePudding user response:
Don't pass a value returned from input() to any function that might result in an exception without handling such a possibility. This answer includes a general-purpose function for handling input.
This code assumes that the specified range is inclusive.
def getInput(prompt, t=str):
while True:
v = input(f'{prompt}: ')
try:
return t(v)
except ValueError:
print('Invalid input')
start = getInput('From', int)
step = getInput('Step', int)
to = getInput('To', int)
total = list(range(start, to 1, step)) or [0]
sum_ = sum(total)
print(f'The sum is: {sum_}')
print(f'The average is: {sum_/len(total)}')
Example:
From: 1
Step: 5
To: 100
The sum is: 970
The average is: 48.5