How to add digits within a string from user input - python

I'm still learning Python and I ran into a problem. My professor wants me to ask the user for input of a number with several digits with nothing separating them. Then, he wants me to write a program that would add those digits together and print the result. I can't do it because I don't understand how.
This is what I'm trying:
inp = input("Please enter a number with several digits with nothing separating them: ")
for number in inp:
count += int(len[inp])
print(count)
There are other ways I tried to do this, but it's just not working. What am I doing wrong? Exactly how should I do this? This is from Chapter 6 in "Python for Everybody" book.

First of all you need to define count variable:
count = 0
input() method returns a string without the trailing newline. You can iterate over characters in inp to sum up their numeric values:
for n in inp:
count += int(n)

Did you try in that way?
inp = input("Please enter a number with several digits with nothing separating them: ")
count=0
for number in inp:
count += int(number)
print(count)
Example if the user enter 25, the result should be 7, is it?

you need to add count variable to store the sum of each iterable value
instead of count+=int(list(inp)) you need to use count+=number as you are iterating the input string and already accessing each digit in for loop
inp = input("Please enter a number with several digits with nothing separating them: ")
count = 0
for number in inp:
count += int(number)
print(count)

Related

Sequence of numbers - python

i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.

Python - script counts wrong, but why?

I'm just at the beginning to learn Python.
As an exercise I wrote this little script:
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number,
detect their mistake using try and except and print an error message and skip to the next number.
It does what it should in general, but: When I played with it a little I noticed one strange behavior: As it takes several (int) numbers after the prompt it won't - and shouldn't - take characters. So far so good, but then I tried a float as input. The script won't take it as valid input but would count it and put the truncated number into the total.
Code:
total = float(0) # sum of items
count = int(0) # number of items
avrg = float(0) # average of items
input_in = True
while input_in:
try:
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
for itervar in line:
total = total + float(itervar)
count = count+1
avrg = total / count
except:
print('Invalid input')
Output:
Enter a number: 1.5
1.5
Invalid input
Enter a number: 5
5
Enter a number: 5
5
Enter a number: 5
5
Enter a number: done
total: 16.0 count: 4 average: 4.0
What I tried - and didn't work: Assign the variables line and/or itervar as float().
I tried the included Debugger but I'm not able to understand it.
I have no clue how this could work.
Your line:
for itervar in line:
Is walking over each character of the input, which for your first input (1.5) results in three iterations:
1
.
5
So for the first iteration, your total is increased by 1, and for the second iteration, you're trying to use . as a number, and failing. (Hence why your final value, after adding 5 + 5 + 5, is 16)
Instead of using a for loop to iterate over your input, you should look into converting the entire input string into a number.
And as an added bonus...
Consider whether you actually need to be recalculating your average each loop. Since you have the total, and the count, I'd recommend instead calculating your average value on-demand, as a result of those two numbers.
As you've already figured out, input() returns a string.
When you iterate through a string with a for loop, you iterate over each character individually. This means that, when you enter '1.5', you get three iterations:
itervar = '1'
itervar = '.'
itervar = '5'
Due to how you wrote your code, the first one goes correctly, but then when it tries to convert '.' to a float, it produces an error.
Why not just consider the entire input as a whole, instead of character-by-character?
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
total = total + float(line)
count = count+1
avrg = total / count

to allow the user to input a 3-digit number, and then output the individual digits in the number

how would i allow a user to input a 3-digit number, and then output the individual digits in the number in python
e.g. If the user enters 465, the output should be “The digits are 4 6 5”
sorry if this sounds basic
You use for your number num:
num % 10 to extract the last digit.
num = num // 10 to remove the final digit (this exploits floored division).
Finally, you want to get out the leading digit first. Therefore you adopt a recursive function to perform the above (which calls itself prior to printing the digit).
The solution using str.isdigit and re.sub functions:
import re
num = input('Enter number:')
if num.isdigit():
num_sequense = re.sub(r'(\d)(?=\d)', r'\1 ', num)
print("The digits are:", num_sequense)
else:
print("There should be only digits", num)
The output for the input 123:
The digits are: 1 2 3
The output for the input a1s2d3:
There should be only digits a1s2d3
Hard to make in one line, anyway this should do exactly what you want:
inp = list(input())
print("The digits are ", end ='')
for i in inp:
print(i, end=' ')
If you don't care for formatting, one-liner is possible:
print("The digits are ",list(input()))

Python: How to use a Variable Integer to Call a Specific Part of a String

Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !

Adding up the sum of digits

I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]

Categories

Resources