how do I make a loop remember information from previous iterations? - python

I want to make a loop where I can input numbers, and then the loop will give me the average of the numbers that I inputted. But a problem that I am facing is that I do not know how to make the loop remember the previous numbers that I inputted. I want the loop to end if I put -1.
x = (input ("enter a number: "))
while x != "-1":
y = int(input("enter another number: " ))
total = 0 + y
if total <= 0:
totally = total
print (totally)

you may use a list to store all your numbers, when you finish the input you can compute the average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
i = int(input("enter another number: " ))
avg = sum(nums) / len(nums)
print(avg)
if you like one-line solution:
from statistics import mean
from itertools import takewhile, count
print(mean(takewhile(lambda x : x !=-1, (int(input()) for _ in count() ))))
if you want to print intermediary average:
nums = []
i = int(input("enter another number: " ))
while i != -1:
nums.append(i)
print(sum(nums) / len(nums))
i = int(input("enter another number: " ))
also, you could use 2 variables to hold the current sum and the total count:
i = int(input("enter another number: " ))
s = 0
c = 0
while i != -1:
c += 1
s += i
print(s / c)
i = int(input("enter another number: " ))

Probably you should define your total var before, something like this:
x = int(input ("enter a number: "))
total = x
numLoops = 1
y = 0
while y != -1:
y = int(input("enter another number: " ))
total += y # This will store the summation of y's in total var
numLoops += 1
print(f"The average is: {total/numLoops}") # Prints the average of your nums

You can do the following:
values = []
while True:
x = int(input ("enter a number: "))
if x == -1:
break
else:
values.append(x)
print(sum(values)/len(values))

Related

i tried this but my answer came 0.00 in every input

The series:-
I want to write a python program in which we can can input the the value of x and n and solve this series.
can anyone help me please?
The Series:- x-x^2+x^3/3-x^4/4+...x^n/n
x = int (input ("Enter value of x: "))
numbed = int (input ("Enter value of n: "))
summed = 0
for a in range (numbed + 1) :
if a%2==0:
summed += (x**a)/numbed
else:
summed -= (x**a)/numbed
print ("Sum of series", summed)
**I tried this code, but no matter what values I enter, the output is always 0.00. **
This should do the trick:
x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))
total = x
for i in range(2, n+1):
if i%2==0:
total -= x**i/i
else:
total += x**i/i
print("Sum: ", total)
I assume the series you mentioned in your question is this: x - x^2/2 + x^3/3 - x^4/4 +... x^n/n.
If yes, try this:
x = int (input ("Enter value of x: "))
numbed = int (input ("Enter value of n: "))
sum1 = x
for i in range(2,numbed+1):
if i%2==0:
sum1=sum1-((x**i)/i)
else:
sum1=sum1+((x**i)/i)
print("The sum of series is",round(sum1,2))
just as an example of using recurcion:
x = int(input("Enter value of x: "))
n = int(input("Enter value of n: "))
def f(x,n,i=1,s=1):
return 0 if i>n else x**i/i*s + f(x,n,i+1,-s)
f(3,5) # 35.85

Program that prompts the user to input 5 integers and outputs these integers in reverse order

I need help with this Python program.
With the input below:
Enter number: 1​
Enter number: 2​
Enter number: 3​
Enter number: 4​
Enter number: 5​
the program must output:
Output: 54321​
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)

How do I use while function to complete this question

For example, if user keys in 6, the output is 21 (1+2+3+4+5+6)
sum = 0
num = int(input("Enter number: "))
…..
….
This is my code below:
x=0
sum = 0
nums = int(input("enter num "))
while sum <= nums:
sum+=1
x= x + sum
y = x - nums -1
print(y)
First of all, I suggest not to use sum as variable name, this will shadow the built-in sum() function.
There are two ways to do it using while loop, the first one is close to yours but turn <= to < in the condition so you don't need extra - num - 1 at the end.
n = 0
total = 0
num = int(input("enter num "))
while n < num:
n += 1
total += n
print(total)
Second one adds number in descending order, it also change the value of num. If you need num for later use, use the first one.
total = 0
num = int(input("enter num "))
while num:
total += num
num -= 1
print(total)
If loop is not needed, as you are going to obtain a triangular number, just use the formula.
num = int(input("enter num "))
print(num * (num + 1) // 2)
If you don't have use a loop you could do it in a single line:
print(sum(range(1, int(input('Enter a number: ')) + 1)))
Test:
Enter a number: 6
21

can a condition be in range in python?

can a range have a condition in python? for example, I wanna start at position 0 but I want it to run until my while statement is fulfilled.
total = 0
num = int(input ( "Enter a number: " ))
range[0,while num != 0:]
total += num
I want to be able to save different variables being in a while loop.
The purpose of my program is to print the sum of the numbers you enter unil you put in 0
my code
num = int(input ( "Enter a number: " )) #user input
number_enterd = str() #holds numbers enterd
total = 0 #sum of number
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
number_enterd = num
print( "Total is =", total )
print(number_enterd) #check to see the numbers ive collected
expected output:
enter an integer number (0 to end): 10
1+2+3+4+5+6+7+8+9+10 = 55
as of right now I'm trying to figure out how to store different variables so i can print them before the total is displayed. but since it is in a loop, the variable just keeps getting overwritten until the end.
If you want to store all the numbers you get as input, the simplest way to do that in Python is to just use a list. Here's that concept given your code, with slight modification:
num = int(input ( "Enter a number: " )) #user input
numbers_entered = [] #holds numbers entered
total = 0 #sum of number
while num != 0:
total += num
numbers_entered.append(num)
num = int(input ( "Enter a number: " ))
print("Total is = " + str(total))
print(numbers_entered) #check to see the numbers ive collected
To get any desired formatting of those numbers, just modify that last print statement with a string concatenation similar to the one on the line above it.
I used a boolean to exit out of the loop
def add_now():
a = 0
exit_now = False
while exit_now is False:
user_input = int(input('Enter a number: '))
print("{} + {} = {} ".format(user_input, a, user_input + a))
a += user_input
if user_input == 0:
exit_now = True
print(a)
add_now()
If you want to store all of the values entered and then print them, you may use a list. You code would end like this:
#number_enterd = str() # This is totally unnecessary. This does nothing
num = int(input ( "Enter a number: " ))
total = 0 #sum of number
numsEntered = [] # An empty list to hold the values we will enter
numsEntered.append(num) # Add the first number entered to the list
while num != 0:
total += num
num = int(input ( "Enter a number: " ))
#number_enterd = num # Unnecesary as well, this overwrites what you wrote in line 2
# It doesn't even make the num a string
numsEntered.append(num) #This adds the new num the user just entered into the list
print("Total is =", total )
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
For example, user enters 5,2,1,4,5,7,8,0 as inputs from the num input request.
Your output will be:
>>>Total is = 32
>>>Numbers entered: [5, 2, 1, 4, 5, 7, 8, 0]
Just as a guide, this is how I would do it. Hope it helps:
num = int(raw_input("Enter a number: "))
numsEntered = [] # An empty list to hold the values we will enter
total = 0 #sum of numbers
while True:
numsEntered.append(num) #This adds the num the user just entered into the list
total += num
num = int(raw_input("Enter a number: "))
print("Total is =", total)
print("Numbers entered:", numsEntered) #check to see the numbers you've collected
In this case, the last 0 entered to get out of the loop doesn't show up. At least, I wouldn't want it to show up since it doesn't add anything to the sum.
Hope you like my answer! Have a good day :)

I am not able get the sorted values from the input

problem with sorting
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
while i <= n:
s = input()
total = total + int(s)
i = i + 1
s.sort()
print s
print('The sum is ' + str(total))
Because you are trying to sort on input. sort only work on iterating like list and tuples.
I just rewrite your code,
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
Edit
Just change whole operation into a function and put yes/no question in a while loop, And for wrong entry exit from program.
def foo():
n = int(input("Enter the number of inputs : "))
inputs = []
for i in range(n):
s = input()
inputs.append(int(s))
inputs.sort()
print inputs
print('The sum is ',sum(inputs))
while True:
a = raw_input("Do you know the number of inputs ?(y/n)")
if a == 'y':
foo()
elif a == 'n':
print 'We are giving one more option.'
continue
else:
print 'Wrong entry'
break
n = int(input("Enter the number of inputs : "))
total = 0
i = 1
array = []
while i <= n:
s = int(input())
array.append(s)
total = total + int(s)
i = i + 1
array.sort()
print(array)
print('The sum is ' + str(total))
this will solve your problem, sort applies on list not on str object
Store the numbers in a list. Then use sum(list) to get the sum of elements in the list, and sorted(list) to get the list sorted in ascending order.
n = int(input("Enter the number of inputs: "))
l=[]
for i in range(n):
s = input()
l.append(int(s))
print('The sum is', sum(l))
print('Sorted values', sorted(l))
Were you looking for this?

Categories