sum up a numeric string (1111 = 1+1+1+1=4) - python

#Develop a program that reads a four-digit integer from the user and displays the sum of the digits in the number. For example, if the user enters 3141 then your program should display 3+1+4+1=9.
ri = input("please enter four digits")
if len(ri) == 4 and ri.isnumeric() == True:
print(ri[0]+ri[1]+ri[2]+ri[3])
else:
print("Error: should be four digits!")
How do I do this? Haven't seen something like this before I'm sure, and as you can see my code fails....

ri = input("please enter four digits: ")
res = 0
for n in ri:
res += int(n)
print (ri[0]+"+"+ri[1]+"+"+ri[2]+"+"+ri[3]+"="+str(res))

ri = input("please enter four digits: ")
if len(ri) == 4 and ri.isnumeric():
print(f'{ri}={"+".join(ri)}={sum(map(int, ri))}')
else:
print("Error: should be four digits!")
please enter four digits: 3141
3141=3+1+4+1=9

Here is a one-liner for that. The length of the input doesn't matter to this one. Its up to you what to specify for the length or to take the length check away completely.
ri = input('please enter four digits:')
if len(ri) == 4 and ri.isnumeric():
print('+'.join(i for i in ri), '=', str(sum([int(a) for a in ri])))
else:
print('Error: should be four digits')
Output:
please enter four digits: 3149
3+1+4+9 = 17

ri = input("please enter some digits: ")
try:
print("Digit sum: " + str(sum([int(x) for x in ri])))
except:
raise ValueError("That was no valid number!")
For this solution, the length of the input does not matter.

Edit for better answer
input_string = input("Enter numbers")
output_string = ""
sum = 0
count = 0
for n in input_string:
if count < len(input_string)-1:
output_string += str(n) + "+"
else:
output_string += str(n) + "="
sum += int(n)
count += 1
output_string += str(sum)
print (output_string)
Output:
1+1+1+1=4

Related

Checksum of seven-digit number input through keyboard

I am trying to get the checksum of a seven-digit number input through the keyboard. The input would be restricted to exactly 7 digits. I already have this code below but can't get to restrict it to only 7 digits.
n = int(input("Enter number"))
total = 0
while n > 0:
newNum = n % 10
total = total + newNum
n = n // 10
print(total)
If I enter 4 digits, the code will still run. I just want to restrict it to only 7 digits.
Instead of instantly converting the input to an integer, keep it as a string, so you can make a condition for the length of the input.
something like:
n = input("Enter number ")
m = int(n)
total = 0
while m > 0 and len(n)==7:
newNum = m%10
total = total + newNum
m = m//10
print(total)
You could keep the input number as a string, so that you have an easy way to count and sum over the digits:
s = ''
while len(s) != 7:
s = input("Enter a 7-digit number")
total = sum(int(char) for char in s)
print(total)
num = str(input("Enter a seven-digit number: "))
if len(num) !=7:
print("Please Enter a seven-digit number!")
else:
sumNum = 0
m = int(num)
while m>0:
newnum = m%10
sumNum = sumNum + newnum
m = m//10
print("The sum of its digits is: ",sumNum)
Check the length of the input before turning it into a int.
Since strings can be iterated over, like list, their length can be checked in the same way as lists with the len() function. as so:
if len(n) != 7:
print("input must be seven digits long")
n = input("Enter number")

Python: Continue if variable is an 'int' and has length >= 5

I have a piece of code that does some calculations with a user input number. I need a way to check if user entry is an integer and that entered number length is equal or more than 5 digits. If either one of conditions are False, return to entry. Here is what i got so far and its not working:
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "
If anyone has a solution, I'd appreciate it.
Thanks
This would be my solution
while True:
stringset = raw_input("Enter a number: ")
try:
number = int(stringset)
except ValueError:
print("Not a number")
else:
if len(stringset) >= 5:
break
else:
print("Re-enter number")
something like this would work
while True:
number = input('enter your number: ')
if len(number) >= 5 and number.isdigit():
break
else:
print('re-enter number')
Use this instead of your code
while True:
stringset = raw_input("Enter number: ")
if len(stringset)>=5:
try:
val = int(userInput)
break
except ValueError:
print "Re-enter number:
else:
print "Re-enter number:
Do not use isdigit function if you want negative numbers too.
By default raw_input take string input and input take integer input.In order to get length of input number you can convert the number into string and then get length of it.
while True:
stringset = input("Enter number: ")
if len(str(stringset))>=5 and isinstance(stringset, (int, long)):
break
else:
print "Re-enter number: "

ValueError: could not convert string to float — user input with Python

I'm trying to write a 'while' loop that takes a users input, if it is a number it remembers it, if it is a blank space it breaks. At the end it should print the average of all entered numbers. This is giving me the error 'could not convert string to float: '. What exactly is wrong here? Thanks!
EDIT: I re-wrote it like this and I get the same error about converting, but it seems to be on the final (count += 1) line?
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
My guess is that you directly hit enter when you don't want to pass numbers anymore. In that case, comparing with a space is incorrect.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
number += float(user_number)
count += 1
print (number / count)
Also a statement after a break is unreachable.
If you want a cleaner alternative, I would recommend appending to a list, and then computing the average. This removes the need for a separate counter. Try this:
numbers = []
while True:
user_number = input('Enter a number: ')
if user_number == '':
break
numbers.append(float(user_number))
print (sum(numbers) / len(numbers))
Additionally, you could remove the need for a break by testing in the head of while, but you'll need to take an additional input outside the loop.
You should change the order, right now you try to convert everything into floats, even blank spaces.
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
print (number / count)
break
count += 1
number = number + float(user_number)
Additionally, you should do the print of the average value before the break.
I changed your if condition to break if any input except a number is entered, it should be a bit more general than before.
Change order and it should solve the problem, you should first check is enterned input is string or not then go to number part
#!/usr/bin/python
number = 0.0
count = 0
while True:
user_number = raw_input('Enter a number: ')
if user_number == (' '):
print (number / count)
break
number = number + float(user_number)
count += 1
This should work for you.
lst= []
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
lst.append(int(user_number))
print(int(user_number))
print("Average : " + str(sum(lst)/len(lst)))
This code works correctly.
I think you are giving Other than space as input to break.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if user_number == ' ':
break
print (number / count)
number = number + float(user_number)
count += 1
or else use below code:
--> Break will be triggered for non-digit input.
number = 0.0
count = 0
while True:
user_number = input('Enter a number: ')
if not user_number.isdigit():
break
number = number + float(user_number)
count += 1
print("user_number", number)
print("Count", count)
print (number / count)

Multiplication in a variable

I am writing a piece of code that needs to multiply numbers by different values, all the code for the entering and validation of the 7 digit number works however the multiplication doesn't work. This is my code.
while True:
try:
num = int(input("enter a 7 digit number: "))
check = len(str(num))
if check == 7:
print("This code is valid")
break
else:
num = int(input("enter a number that is only 7 digits: "))
except ValueError:
print("you must enter an integer")
num = int(num)
def multiplication():
num[0]*3
num[1]*1
num[2]*3
num[3]*1
num[4]*3
num[5]*1
num[6]*3
return total
multiplication()
When I run it, I get the following error:
Traceback (most recent call last):
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 29, in <module>
multiplication()
File "\\hpdl3802\stuhomefolders$\12waj066\Year 10\Computing\A453\Code\Test v2.py", line 20, in multiplication
num[0]*3
TypeError: 'int' object is not subscriptable
Any feedback is welcome
Of course, your code might be written in a number of ways, optimized (check #Kasravand answer, it's awesome) or not, but with a minimal effort this is what I get:
while True:
try:
num = input("enter a 7 digit number: ")
check = len(num)
int(num) # will trigger ValueError if not a number
if check == 7:
print("This code is valid")
break
else:
print("bad length, try again")
except ValueError:
print("you must enter an integer")
def multiplication(num):
total = int(num[0])*3
total += int(num[1])*1
total += int(num[2])*3
total += int(num[3])*1
total += int(num[4])*3
total += int(num[5])*1
total += int(num[6])*3
return total
print("Answer: ", multiplication(num))
If you're bound to use an integer instead of a list for the input, you can do one of the following:
You could access the individual digits using a combination of integer division and modulo, for example:
first_digit = num // 1000000 * 3
second_digit = num // 100000 % 10 * 1
# and so on
Or you could get the input as a string and access and convert the individual digits:
# [...]
num = input("enter a number that is only 7 digits: ")
# [...]
first_digit = int(num[0]) * 3
second_digit = int(num[1]) * 3
When you convert the input number to an integer you can not use indexing on that object since integers don't support indexing. If you want to multiply your digits by a specific number you better do this before converting to integer.
So first off replace the following part:
num = int(input("enter a number that is only 7 digits: "))
with:
num = input("enter a number that is only 7 digits: ")
The you can use repeat and chain functions from itertools module in order to create your repeated numbers, then use a list comprehension to calculate the multiplication:
>>> from itertools import repeat, chain
>>> N = 7
>>> li = list(chain.from_iterable(repeat([3, 1], N/2 + 1)))
>>> num = '1290286'
>>> [i * j for i, j in zip(map(int, num), li)]
[3, 2, 27, 0, 6, 8, 18]
This code will works:
while True:
try:
num = int(input("enter a 7 digit number: "))
except ValueError:
print("you must enter an integer")
else:
if len(str(num)) != 7:
print("enter a number that is only 7 digits")
else:
break
num = str(num)
def multiplication():
total = 0
for i,m in enumerate([3,1,3,1,3,1,3]):
total += int(num[i])*m # transform the index of text into a integer
return total
print(multiplication())
This should help
num = ''
check = 0
while True:
try:
num = raw_input("enter a 7 digit number: ")
check = len(num)
if check == 7:
print("This code is valid")
break
else:
print "enter a number that is only 7 digits"
except ValueError:
print("you must enter an integer")
def multiplication():
total = 0
for i in range(check):
if i % 2 == 0:
total += int(num[i]) * 3
else:
total += int(num[i]) * 1
print total
multiplication()

How to count how many tries are used in a loop

For a python assignment I need to ask users to input numbers until they enter a negative number. So far I have:
print("Enter a negative number to end.")
number = input("Enter a number: ")
number = int(number)
import math
while number >= 0:
numberagain = input("Enter a number: ")
numberagain = int(numberagain)
while numberagain < 0:
break
how do I add up the number of times the user entered a value
i = 0
while True:
i += 1
n = input('Enter a number: ')
if n[1:].isdigit() and n[0] == '-':
break
print(i)
The str.isdigit() function is very useful for checking if an input is a number. This can prevent errors occurring from attempting to convert, say 'foo' into an int.
import itertools
print('Enter a negative number to end.')
for i in itertools.count():
text = input('Enter a number: ')
try:
n = int(text)
except ValueError:
continue
if n < 0:
print('Negative number {} entered after {} previous attempts'.format(n, i))
break
The solution above should be robust to weird inputs such as trailing whitespace and non-numeric stuff.
Here's a quick demo:
wim#wim-desktop:~$ python /tmp/spam.py
Enter a negative number to end.
Enter a number: 1
Enter a number: 2
Enter a number: foo123
Enter a number: i am a potato
Enter a number: -7
Negative number -7 entered after 4 previous attempts
wim#wim-desktop:~$

Categories

Resources