This question already has answers here:
How do I add five numbers from user input in Python?
(5 answers)
Closed 6 years ago.
I'm trying to help my son who's got some Python homework from school...and I haven't coded since school and this is my first evening on python so forgive the dumb question.
Using a "For" statement I need to prompt the user to enter 10 numbers. When the entries have ended, I need to display the sum. I know I need to do something linking newsum/oldsum/+ value entered but I'm stuck. All help gratefully received.
Here's where I've got to:
total=int
runningtotal=int
thisinput=int
n=0
for num in range (1,11):
runningtotal=thisinput+n
print("enter number",num)
n=int(input())
thisinput=n
print(runningtotal)
The answer is:
inputs_sum = 0
for x in range(10):
inputs_sum += int(input('Enter number:'))
print('The sum is {}'.format(inputs_sum))
Enjoy!
In python3.x, using your code as a working model, probably something like this:
runningtotal=0
for num in range(10):
thisinput = input("enter number: ") # If using python2.x change input to raw_input
runningtotal+=int(thisinput)
print(runningtotal)
Another answer (was deleted) used list.append() to add numbers to list and sum the list elements like so:
num_list = []
for num in range(10):
thisinput = raw_input("enter number: ")
num_list.append(int(thisinput))
print sum(num_list)
Related
This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x
Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.
you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))
I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
count = 0
for i in range (num_length):
num = int(input('Enter number '+str(i+1)+ ':\n'))
nomlist.append(num)
this is a part of the solution for my homework, but now I need to rewrite it in a recursive form and I am not sure how I am supposed to change the above code in a recursive function. The above code basically asks the user to input a number and based on that number the program repeatedly asks the user for input and appends it into the list. Please help me.
num_length = int(input('Enter the length of the sequence:\n'))
nomlist=[]
def rec(l, count, num_length):
if count <= 0:
return
else:
num = int(input('Enter number '+str(num_length-count+1)+ ':\n'))
l.append(num)
rec(l, count-1, num_length)
rec(nomlist, num_length, num_length)
print(nomlist)
Here's a recursive function that makes use of default parameter values and conditional expressions to minimize the amount of code required:
def get_nums(length, numbers=None, entry=1):
numbers = [] if not numbers else numbers
numbers.append(input(f' Enter number {entry}: '))
return numbers if entry == length else get_nums(length, numbers, entry+1)
length = int(input('Enter the length of the sequence: '))
nomlist = get_nums(length)
print(nomlist)
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
I have created a python program that works fine. but I want to make it more neat, I ask the user for numbers, number1, number2 etc. up to 5. I want to just do this with a for loop though, like this
for i in range(0,5):
number(i) = int(input("what is the number"))
I realise that this code docent actually work but that is kind of what I want to do.
Code:
number = []
for i in range(5):
number.append(int(input("what is the number ")))
print(number)
The easiest I could think at the top of my had way would just to create a list and append the items:
numbers = []
for i in range(0,5):
numbers += [int(input("what is the number"))]
If you want to save also variable names you can use python dictionaries like this:
number = {}
for i in range(0,5):
number[f'number{i}'] = int(input("what is the number "))
print(number)
output:
{'number0': 5, 'number1': 4, 'number2': 5, 'number3': 6, 'number4': 3}
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I'm new to Yython programming. I create a simple program with random module, that ask for number, and person need to guess an number. I got problem with getting the answer. Even if I give the correct answer, program isn't stopping, here's the code:
import random
run = True
answer = random.randint(1,9)
guess = input("Give me an number in 1 to 9: ")
print(answer)
while run:
if guess == answer:
print("Congratulations, you won!\n" * 5)
run = False
else:
guess = input("Try again: ")
print(answer)
The print(answer) line is for me to know what is the answer, and even if I write it down, program isn't stopping.
answer is always an integer:
answer = random.randint(1,9)
and guess is always a string:
guess = input("Give me an number in 1 to 9: ")
thus they can never be equal.
You need to conver the inputted string to an integer:
guess = int(input("Give me an number in 1 to 9: "))
Or better yet, convert the generated random number to a string, to avoid the issue of the program crashing when the user inputs a non digit:
answer = str(random.randint(1,9))
The random function will return an integer and the input function will return a string in python, "1" is not equal to 1. To be able to check if the input is the same, convert the random number to a string by doing guess == str(answer) instead
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I want this python code comes out from loop when I enter 0 as input number of "num" variable But it continues printing these three lines constantly
Thanks
num = 10 #10 is dummy number for starting loop
while(num!=0):
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
print("Comes out from while loop!")
There reason behind is that the input takes input as a string and you have to either convert it to int:
num = int(input("Enter a number:"))
or change the while loop:
while(num!='0'):
print takes input as string , in order to come out of loop
use
num = int(input("Enter a number:"))
it will consider num variable as an integer but not an string and will come out of the loop.
You have got a correct answer before this but you can change your code too:
while True:
print("1)Test func1")
print("2)Test func2")
print("0)Exit")
num = input("Enter a number:")
if num == '0':
break
print("Comes out from while loop!")
at the begining while always get True, you don't need to set value, 'break' means 'stop current loop and exit'