How to print sum of digits for a Python integer? [duplicate] - python

This question already has answers here:
Sum the digits of a number
(11 answers)
Closed last year.
Consider the following input prompt. I want to output the sum of digits that are inputted.
Example:
two_digit_number = input("Type a two digit number: ") 39
# program should print 12 (3 + 9) on the next line
If I input 39, I want to output 12 (3 + 9). How do I do this?

You can use sum(), transforming each digit to an integer:
num = input("Enter a two digit number: ")
print(sum(int(digit) for digit in num))

maybe like this:
numbers = list(input("Enter number: "))
print(sum(list(map(int, numbers))))
Read digits with input as a whole number of string type
split them with list() in characters in a list
use map() to convert type to int in a list
with sum() you're done.. just print()
Beware of invalid entries! "hundred" or "1 234 567"

you can achieve that like this:
a = input("Type a two digit number: ")
b = list(a)
print(int(b[0])+int(b[1]))

n = (int(input("Enter the two digit number\n")))
n = str(n)
p = int(n[0])+int(n[1])
print(p)

This is one of the many ways for it.
value = 39 # it is your input
value_string = str(value)
total = 0
for digit in value_string:
total += int(digit)
print(total)
new version according to need mentioned in comment:
value = 39
value_string = str(value)
total = 0
digit_list = []
for digit in value_string:
total += int(digit)
digit_list.append(digit)
print(" + ".join(digit_list))
print(total)

You can do that as follows:
two_digit_number = input("Type a two digit number: ")
digits = two_digit_number.split("+")
print("sum = ", int(digits[0])+int(digits[1]))
Explanation:
first read the input (ex: 1+1)
then use split() to separate the input statement into the strings of the input digits only
then use int() to cast the digit from string to int

Related

Output smiley faces based on number input [duplicate]

This question already has answers here:
How to print something a specific number of times based on user input?
(3 answers)
Closed 1 year ago.
The code is supposed to print :) based on the number inputted (an integer 1 to 10). With any positive integer, the code is supposed to print that many smiley faces (ex. if 5 is entered, 5 smiley faces should be printed).
It's required that the code should use += to add onto the end of a string and should also decrement to count down and use a loop.
x = input("enter number 1 to 10: ")
for i in len(x):
print(":) " * x)
I don't think you can multiply int values and str values, and I can't find another way to do this.
First things first, input() function returns a string. You want x to be an integer, use the int() function:
x = int(input("enter number 1 to 10: "))
Second You can either use a for loop or the multiplication operator to print n number of smileys.
# Using for loop to print n smileys :
x = int(input("enter number 1 to 10: "))
for i in range(x):
print(":) ",end="")
# Using multiplication operator :
x = int(input("enter number 1 to 10: "))
print(":) "*x)
# x should be an integer
x = int(input("enter number 1 to 10: "))
# define "s" as an empty string
s = ''
# increment ":)" to "s" x times
for _ in range(x):
s += ':)'
print(s)
You're almost there! In fact, you can multiply string and integer values. This code does what you described:
print(':) '*int(input("Enter number 1 to 10: ")))
If you really want to use a for loop and +=, you could also do this
x, s = input("enter number 1 to 10: "), ''
for i in range(x):
s += ':) '
print(s)
Answer: How to print a string x times based on user input
Credits to: NoobCoder33333
times = input('Enter number from 1 to 10: ')
word = ":-)"
print('\n'.join([word] * int(times)))

Is there a way to turn an input into a list?

I am trying to make an average calculator so that you can input as many numbers as you like and I am trying to turn an input into a list, how can I do this? Here is my code that I have so far.
numbers = []
divisor = 0
total = 0
adtonum = int(input("Enter numbers, seperated by commas (,): "))
numbers.append(adtonum)
for num in numbers:
divisor += 1
total = total + num
print(num)
print("Average: ")
print(total / divisor)
Try this:
adtonum = input("Enter numbers, separated by commas (,): ")
numbers = [int(n) for n in adtonum.split(',')]
Here, we split the line up by the delimiter (in this case a comma) and use list comprehension to construct the list of numbers -- converting each of the numbers in the input string into integers one by one.
Try this code.
# assign values using unpacking
divisor, total = 0, 0
# list comprehension
numbers = [int(x) for x in input("Enter numbers, separated by commas (,): ").split(',')]
for num in numbers:
divisor += 1
total += num
print(num)
print("Average: ")
print(total / divisor)
You can use eval function:
numbers = eval(input("Enter a list of numbers i.e; values separated by commas inside '[]' "))
Here you go;
divisor = 0
total = 0
adtonum = (input("Enter numbers, seperated by commas (,): "))
numbers = adtonum.split(',')
for num in numbers:
divisor += 1
total = total + int(num)
print(int(num))
print("Average: ")
print(total / divisor)
Explanation:
As you were trying to get the input from the user but the input provided by the user couldn't be parsed into int because it contained ,.
I simply got the input from the user, splited the input at commas. Note that split function returns a list of elements seperated by the character provided as the argument. Then i iterated over this list, parsed every element as int which is possible now. Rest is same.
You could use the eval() function here, like this-
numbers = list(eval(input("Enter numbers, seperated by commas (,): ")))
Since the input is just comma-separated numbers thus, the eval() function will evaluate it as a tuple, and then the list() function will convert it into a list.

How do I calculate the sum of the individual digits of an integer and also print the original integer at the end?

I wish to create a Function in Python to calculate the sum of the individual digits of a given number
passed to it as a parameter.
My code is as follows:
number = int(input("Enter a number: "))
sum = 0
while(number > 0):
remainder = number % 10
sum = sum + remainder
number = number //10
print("The sum of the digits of the number ",number," is: ", sum)
This code works up until the last print command where I need to print the original number + the statement + the sum. The problem is that the original number changes to 0 every time (the sum is correct).
How do I calculate this but also show the original number in the print command?
Keep another variable to store the original number.
number = int(input("Enter a number: "))
original = number
# rest of the code here
Another approach to solve it:
You don't have to parse the number into int, treat it as a str as returned from input() function. Then iterate each character (digit) and add them.
number = input("Enter a number: ")
total = sum(int(d) for d in number)
print(total)
You can do it completely without a conversion to int:
ORD0 = ord('0')
number = input("Enter a number: ")
nsum = sum(ord(ch) - ORD0 for ch in number)
It will compute garbage, it someone enters not a number
number = input("Enter a number: ")
total = sum((int(x) for x in list(number)))
print("The sum of the digits of the number ", number," is: ", total)
As someone else pointed out, the conversion to int isn't even required since we only operate a character at a time.

Only the last item is being appended to a list in a while loop (Python)

I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. However, it only appends the last digit of the number to the list.
Code -
num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0
while x < numlen:
digits = []
a = numstr[x]
digits.append(a)
x = x + 1
print(digits)
So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1.
Try this code:
digits = [i for i in str(num)]
You cannot do better than digits = list(str(num)). In fact, since input returns a string, even the conversion to a number is not necessary:
num = input("Enter a number: ")
digits = list(num)
(You still may want to ensure that what's typed is indeed a number, not a random string.)

ISBN final digit finder

I am working in python 3 and I am making a program that will take in a 10 digit ISBN Number and applying a method to it to find the 11th number.
Here is my current code
ISBN=input('Please enter the 10 digit number: ')
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Digit1=int(ISBN[0])*11
Digit2=int(ISBN[1])*10
Digit3=int(ISBN[2])*9
Digit4=int(ISBN[3])*8
Digit5=int(ISBN[4])*7
Digit6=int(ISBN[5])*6
Digit7=int(ISBN[6])*5
Digit8=int(ISBN[7])*4
Digit9=int(ISBN[8])*3
Digit10=int(ISBN[9])*2
Sum=(Digit1+Digit2+Digit3+Digit4+Digit5+Digit6+Digit7+Digit8+Digit9+Digit10)
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)
I want to create some kind of loop so that the number after "Digit" for the variable name increases starting from 1 (or zero if it makes life easier), the number in the square brackets increases starting from 0 and the multiplication number to decrease from 11 to 2.
Is there any way of doing this code in a more efficient way?
I think this should do what you want.
def get_isbn_number(isbn):
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
digit_11 = 11 - (sum(digits) % 11)
if digit_11 == 10:
digit_11 = 'X'
digits.append(digit_11)
isbn_number = "".join(map(str, digits))
return isbn_number
EXAMPLE
>>> print(get_isbn_number('2345432681'))
22303640281810242428
>>> print(get_isbn_number('2345432680'))
2230364028181024240X
Explanation of second line:
digits = [(11 - i) * num for i, num in enumerate(map(int, list(isbn)))]
Could be written out like:
isbn_letters = list(isbn) # turn a string into a list of characters
isbn_numbers = map(int, isbn_letters) # run the function int() on each of the items in the list
digits = [] # empty list to hold the digits
for i, num in enumerate(isbn_numbers): # loop over the numbers - i is a 0 based counter you get for free when using enumerate
digits.append((11 - i) * num) # If you notice the pattern, if you subtract the counter value (starting at 0) from 11 then you get your desired multiplier
Terms you should look up to understand the one line version of the code:
map,
enumerate,
list conprehension
ISBN=int(input('Please enter the 10 digit number: ')) # Ensuring ISBN is an integer
while len(ISBN)!= 10:
print('Please make sure you have entered a number which is exactly 10 characters long.')
ISBN=int(input('Please enter the 10 digit number: '))
continue
else:
Sum = 0
for i in range(len(ISBN)):
Sum += ISBN[i]
Mod=Sum%11
Digit11=11-Mod
if Digit11==10:
Digit11='X'
ISBNNumber=str(ISBN)+str(Digit11)
print('Your 11 digit ISBN Number is ' + ISBNNumber)

Categories

Resources