How to add the numbers from a user's input [duplicate] - python

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])

Related

How to limit input integer in single digit? [python] [duplicate]

This question already has answers here:
Python excepting input only if in range
(3 answers)
Closed 2 years ago.
what's the easiest way to limit this code integer input to a single digit?
num = ["First","Second","Third"]
num_list = []
for a in num:
x = int(input(f"Enter Your {a} number: "))
num_list.append(x)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(num_list[i],num_list[j],num_list[k])
just a quick fix
def get_single_digit_input():
while True:
a = input('please enter number')
if not a.isnumeric():
print('please enter single digit Numeric only')
continue
a = int(a)
# your logic is here
if a<=9 and a>=0:
return a
else:
print('please enter single digit Numeric only')
a = get_single_digit_input()
You can check using a while statement. If the input is not a single digit, force it back to the input statement. Also you want to check if the input is a digit and not an alphabet or special character.
Here's a way to do it: I am using the walrus operator in python 3.9
while len(x:=input('Enter a single digit :')) > 1 or (not x.isnumeric()):
print ('Enter only a single digit')
print (x)
If you are using python < 3.9, then use this.
x = ''
while True:
x = input ('Enter a single digit :')
if (len(x) == 1) and (x.isnumeric()): break
print ('Enter only a single digit')
print (x)

Why that not get the total in python? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Python how to multiply results from input strings [duplicate]
(3 answers)
Closed 2 years ago.
number=input('Enter a number')
total=number*5
print(total)
This code is not print the total please help me.
This print only the number multiple times.
When you input a value, it will be saved as a str value. Instead, typecast the value into an integer using int. Note - when you multiply a string by an integer, it duplicates that value by the integer value.
>>> number=input('Enter a number')
5
>>> print(type(number))
<class 'str'>
>>> total=number*5
>>> print(total)
'55555'
Instead typecast the input using int()
>>> number=int(input('Enter a number'))
5
>>> print(type(number))
<class 'int'>
>>> total=number*5
>>> print(total)
15
If you want to print the number 5 times you got the code correct.
however I think you want to multiply the number by 5.
so convert the number in to integer. Then it will work.
You can check your type of variable by:
print(type(number))
Answer:-
number=input('Enter a number')
number=int(number)
total=number*5
print(total)
or use in single statement.
number=int(input('Enter a number'))
total=number*5
print(total)
Because input function returns str.
It's exmplained in documentation: Built-in functions: input.
>>> num = input("enter a number: ")
enter a number: 13
>>> type(num)
<class 'str'>
You need to cast it to int by int(num).
Since input returns a string you have to convert the string to int:
number = input('Enter a number')
total= int(number)*5
print(total)
When you get input from the user using input() it will save the varaible as a string by default. To remedy this you need to convert the string to int like this:
number = int(input('Enter a number: '))
total = number * 5
print(total)
It's because input returns a string. You need to cast it to int at somewhere. You can try this:
number = int(input('Enter a number'))
total = number*5
print(total)
#Enter a number 3
#15

Adding a large number from a user in python [duplicate]

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)

User input integer list [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 5 years ago.
I am trying to create a piece of code that allows me to ask the user to enter 5 numbers at once that will be stored into a list. For instance the code would would be ran and something like this would appear in the shell
Please enter five numbers separated by a single space only:
To which the user could reply like this
1 2 3 4 5
And then the numbers 1 2 3 4 5 would be stored into a list as integer values that could be called on later in the program.
Your best way of doing this, is probably going to be a list comprehension.
user_input = raw_input("Please enter five numbers separated by a single space only: ")
input_numbers = [int(i) for i in user_input.split(' ') if i.isdigit()]
This will split the user's input at the spaces, and create an integer list.
You can use something like this:
my_list = input("Please enter five numbers separated by a single space only")
my_list = my_list.split(' ')
This could be achieved very easily by using the raw_input() function and then convert them to a list of string using split() and map()
num = map(int,raw_input("enter five numbers separated by a single space only" ).split())
[1, 2, 3, 4, 5]
You'll need to use regular expressions as the user may also enter non-integer values as well:
nums = [int(a) for a in re.findall(r'\d+', raw_input('Enter five integers: '))]
nums = nums if len(nums) <= 5 else nums[:5] # cut off the numbers to hold five
Here is a subtle way to take user input into a list:
l=list()
while len(l) < 5: # any range
test=input()
i=int(test)
l.append(i)
print(l)
It should be easy enough to understand. Any range range can be applied to the while loop, and simply request a number, one at a time.

Python: the len() function doesn't recognize 0 at the start

I want to test whether a 10 digit number is of 10 length, but whenever the number begins with 0, len() only counts 9.
How can I fix this?
At the moment:
something is a variable made up of numbers, I converted the variable into a string, then made this statement.
if len(something) != 10:
(do something)
My current code:
number = int(input("Enter number: "))
number = str(number)
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
If I inputted a number with 10 digits it's fine, BUT, when I input a number with 10 digits and starting with zero, the len() function recognizes the number as 9 long. Help plz
Providing yout code, it's because you are casting your input to int, then casting it down to string (input automatic type is str in Python3, if you're using Python2, don't forget to cast as str or using raw_input like hackaholic).
Replace
number = int(input("Enter number: "))
number = str(number)
By
number = input("Enter number: ")
So number will directly be a string. And you can use len() on it. It even works with 0000000000
you forcing it to integer, input take values as string
number = input("Enter number: ")
if len(number) != 10:
print ("Not 10 digits long")
else:
print ("Good")
len function works on string
if you using python 2.x better to use raw_input("Enter Number: ")
Numbers starting with 0 are represented in base 8 (octal numbers) in python. You need to convert them to string to count their digits :
# Not converted
number1 = 0373451234
print "number: "+str(number1)+" digits:"+str(len(str(number1)))
> number: 65950364 digits:8
# Converted
number2 = "0373451234"
print "number: "+str(number2)+" digits:"+str(len(str(number2)))
> number: 0373451234 digits:10

Categories