This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 5 years ago.
def main():
number = input("enter large number:")
number = int(number)
result = 0
for i in number:
result = result + i
print("result is:",result)
is giving me an error with the int,I'm not sure how to fix it.
I need the user to type in a large number like 2541 and it needs to be separated like 2,5,4,1 and added to give me the result of 12 is not supposed to be just 4 number but needs to be a large number.
You can't iterate over a number, so for i in number will fail.
What you want is to start with the input as a string, iterate over that, then convert to an int when adding it to result:
number = str(input("enter large number:"))
result = 0
for i in number:
result = result + int(i)
print("result is:",result)
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
How do I parse a string to a float or int?
(32 answers)
Closed last year.
I am creating a calculator and I place the numbers taken by the user into a list.I had to make the input a string since I place the input in a while loop and gave it a string to break the loop (q).
while True:
numbers = input('Enter the numbers for calculation: ')
if numbers == 'q':
break
operations.append(numbers)
I want to turn the list where the user's input is kept into a float so that I can perform operations on them.
This is the list: operations = []
I'm still learning Python, so don't judge too harshly.
operations = []
while:
number = input('Enter number\n')
if number == 'q':
print('QUIT')
break
else:
number = float(int(number))
operations.append(number)
print(operations)
I just couldn't make a check for the input of any other letters, except for "q"
This question already has answers here:
Sum the digits of a number
(11 answers)
Closed 3 years ago.
So I am trying to get a user's input and add it's numbers together.
input('Enter number: ')
And then say the user entered 458 then I wanted to add all it's digits up? I have tried using + but it doesn't work. Any solutions?
The problem you probably came across is that you have a string.
>>> answer = input('Enter number: ')
Enter number: 458
>>> print(type(answer))
<class 'str'>
But if you want to add each of the digits up, you'll need to convert each digit to an int. Thankfully, because we have a string here, we can actually iterate through each character in the string (try not to read it as "each digit in the number", because we have a string '458' here with characters '4', '5', '8'.)
>>> total = 0
>>> for character in answer:
... total = total + int(character)
...
>>> print(total)
17
Notice how I convert each character in the string to an integer, then add it to a total integer.
Perhaps this will work:
user_number = input('please enter your number')
sum = 0
for num in user_number:
sum += int(num)
print(sum)
You could convert your input into a list then use list comprehension:
num = input('Enter number: ')
sum([int(i) for i in num])
This question already has answers here:
for or while loop to do something n times [duplicate]
(4 answers)
Closed 3 years ago.
I am relatively new to programming and especially to Python. I am asked to create a for loop which prints 10 numbers given by the user. I know how to take input and how to create a for loop. What bothers me, is the fact that with my program I rely on the user to insert 10 numbers. How can I make the program control how many numbers are inserted? Here is what I tried:
x = input('Enter 10 numbers: ')
for i in x:
print(i)
You need to
ask 10 times : make a loop of size 10
ask user input : use the input function
for i in range(10):
choice = input(f'Please enter the {i+1}th value :')
If you want to keep them after, use a list
choices = []
for i in range(10):
choices.append(input(f'Please enter the {i + 1}th value :'))
# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]
What if input is row that contains word (numbers) separated by spaces? I offer you to check if there are 10 words and that they are numbers for sure.
import re
def isnumber(text):
# returns if text is number ()
return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)
your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items
# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))
# raising exception if there are any words that are not numbers
for word in splitted_text:
if not(isnumber(word)):
raise ValueError(word + 'is not a number')
# finally, printing all the numbers
for word in splitted_text:
print(word)
I borrowed number checking from this answer
This question already has an answer here:
Return value of 'print' function?
(1 answer)
Closed 6 months ago.
def hourstominutes(minutes):
hours = minutes/60
return hours
h = int(input(print("Enter the number of minutes:")))
print(hourstominutes(h))
Because you are adding the function print() within your input code, which is creating a None first, followed by the user input. Here is the solution:
def hours_to_minutes(minutes):
hours = minutes/60
return hours
h = int(input("Enter the number of minutes: "))
print(hours_to_minutes(h))
Output:
Enter the number of minutes: 50
0.8333333333333334
Input is printing the result of print("Enter the number of minutes:", and print() returns None. What you want is int(input("Enter the number of minutes:")) with no print().
This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 years ago.
For example, if you wanted to accept say 2 input values it would be something like,
x = 0
y = 0
line = input()
x, y = line.split(" ")
x = int(x)
y = int(y)
print(x+y)
Doing it this way however, would mean that I must have 2 inputs at all times, that is separated by a white space.
How do I make it so that a user could choose to enter any number of inputs, such as nothing (e.g. which leads to some message,asking them to try again), or 1 input value and have an action performed on it (e.g. simply printing it), or 2 (e.g. adding the 2 values together) or more.
You can set a parameter how many values there will be and loop the input and put them into a map - or you make it simple 2 liner:
numbers = input("Input values (space separator): ")
xValueMap = list(map(int, numbers.split()))
this will create a map of INT values - separated by space.
You may want to use a for loop to repeatedly get input from the user like so:
num_times = int(input("How many numbers do you want to enter? "))
numbers = list() #Store all the numbers (just in case you want to use them later)
for i in range(num_times):
temp_num = int(input("Enter number " + str(i) + ": "))
numbers.append(temp_num)
Then, later on, you can use an if/elif/else chain to do different actions to the numbers based on the length of the list (found using the len() function).
For example:
if len(numbers) == 0:
print("Try again") #Or whatever you want
elif len(numbers) == 1:
print(numbers[0])
else:
print(sum(numbers))
Try something like this. You will provide how many numbers you want to ask the user to input those many numbers.
def get_input_count():
count_of_inputs = input("What is the number you want to count? ")
if int(count_of_inputs.strip()) == 0:
print('You cannot have 0 as input. Please provide a non zero input.')
get_input_count()
else:
get_input_and_count(int(count_of_inputs.strip()))
def get_input_and_count(count):
total_sum = 0
for i in range(1,count+1):
input_number = input("Enter number - %s :"%i)
total_sum += int(input_number.strip())
print('Final Sum is : %s'%total_sum)
get_input_count()