adding numbers in a string in python [duplicate] - python

This question already has answers here:
Sum of digits in a string
(10 answers)
Closed 2 years ago.
I have a string of numbers, for example 12458960. How can I go about adding them so that it would be 1+2+4+5+8+9+6+0 = 35
I have the numbers already recorded into a variable called ccn. I just need to get the sum now. I tried adding the string numbers using,
ccn[0]+ccn[1]+ccn[2]+ccn[3]+ccn[4]+ccn[5]+ccn[6]+ccn[7]
But that didnt work.
Any help would be much appreciated.

You can do this:-
a = '12458960'
res = sum(map(int, a))
print(res)
Output:-
35

Try with this one liner:
a = '12458960'
print (sum(int(i) for i in a))

Here is a very basic way:
num = '123458960'
number = 0
for n in num:
number += int(n)
print(number)

Related

How to i make this while loop " not equal to" [duplicate]

This question already has answers here:
Is there a "not equal" operator in Python?
(10 answers)
Closed 3 years ago.
So theres a small chunk of code im working on for a school project but im not sure if this while command is possile:
array = []
list_amount = int(input("Enter how many numbers will be in the list"))
while len(array) == list_amount:
array.append(int(input("Enter a number")))
In the line, while len(array) == list_amount:
I want it to be not equal to
So that it will keep letting you add numbers until the length of the array and the amount you entered are the same then the loop will break.
Replace == with !=. != is a python syntax for "not equal to".
Use the != operator:
array = []
list_amount = int(input("Enter how many numbers will be in the list"))
while len(array) != list_amount:
array.append(int(input("Enter a number")))
Just do != instead of ==. It means not equal to and is basically the opposite of ==.
array = []
list_amount = int(input("Enter how many numbers will be in the list"))
for i in range(list_amount):
array.append(int(input("Enter a number")))

How to count the amount of digits in an input? [duplicate]

This question already has answers here:
Correct output for function that counts occurrences of each digit in a string
(3 answers)
Closed 5 years ago.
I would like to count the amount of numbers in an input for example in the four digit number 4256 how would I find out how many fours, twos, fives and sixes there are. I would be looking for the amount of numbers in a random number.
EDIT:
I continued to work on this and this is what I got. Apologies for asking a duplicate question.
import random
import random
guess = random.randint(1000,9999)
guess = str(guess)
correct = 0
print(guess) #this was only here for testing
number = input("Enter ")
list(number)
if number[0] in guess:
correct = correct + 1
print (correct)
To count how many times x appears in y, use
z = y.count(x)

Calculate sum of list of values entered by users [duplicate]

This question already has answers here:
How do I add five numbers from user input in Python?
(5 answers)
Closed 6 years ago.
I'm trying to help my son who's got some Python homework from school...and I haven't coded since school and this is my first evening on python so forgive the dumb question.
Using a "For" statement I need to prompt the user to enter 10 numbers. When the entries have ended, I need to display the sum. I know I need to do something linking newsum/oldsum/+ value entered but I'm stuck. All help gratefully received.
Here's where I've got to:
total=int
runningtotal=int
thisinput=int
n=0
for num in range (1,11):
runningtotal=thisinput+n
print("enter number",num)
n=int(input())
thisinput=n
print(runningtotal)
The answer is:
inputs_sum = 0
for x in range(10):
inputs_sum += int(input('Enter number:'))
print('The sum is {}'.format(inputs_sum))
Enjoy!
In python3.x, using your code as a working model, probably something like this:
runningtotal=0
for num in range(10):
thisinput = input("enter number: ") # If using python2.x change input to raw_input
runningtotal+=int(thisinput)
print(runningtotal)
Another answer (was deleted) used list.append() to add numbers to list and sum the list elements like so:
num_list = []
for num in range(10):
thisinput = raw_input("enter number: ")
num_list.append(int(thisinput))
print sum(num_list)

why am i getting invalid syntax? [duplicate]

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 8 years ago.
generate 10 random integers 1-100 store them in a list. Use a loop. Use a second loop to process the list. In this latter loop, display all numbers in the list and determine the sum of the odd numbers and the sum of the even numbers. Display these sums after the second loop has ended. what's wrong?
import random
randomList = [] # create list
sumEven= sumOdd = 0
for x in range(10):
r = random.randint(1,100)
print(r),
randomList.append(r)
for x in range(len(randomList)):
if (randomList[x]%2 == 0): #even number
sumEven += randomList[x]
else:
sumOdd += randomList[x]
print "\nSum of even numbers =",sumEven
print "Sum of odd numbers =",sumOdd
In the future, please post the full error message.
That being said, print is a function. You should use parentheses with it.
https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function

Python - Write a for loop to display a given number in reverse [duplicate]

This question already has answers here:
Using Python, reverse an integer, and tell if palindrome
(14 answers)
Closed 8 years ago.
How would I have the user input a number and then have the computer spit their number out in reverse?
num = int(input("insert a number of your choice "))
for i in
That is all I have so far...
I am using 3.3.4
Here's an answer that spits out a number in reverse, instead of reversing a string, by repeatedly dividing it by 10 and getting the remainder each time:
num = int(input("Enter a number: "))
while num > 0:
num, remainder = divmod(num, 10)
print remainder,
Oh and I didn't read the requirements carefully either! It has to be a for loop. Tsk.
from math import ceil, log10
num = int(input("Enter a number: "))
for i in range(int(ceil(math.log10(num)))): # => how many digits in the number
num, remainder = divmod(num, 10)
print remainder,
You don't need to make it int and again make it str! Make it straight like this:
num = input("insert a number of your choice ")
print (num[::-1])
Or, try this using for loop:
>>> rev = ''
>>> for i in range(len(num), 0, -1):
... rev += num[i-1]
>>> print(int(rev))
Best way to loop over a python string backwards says the most efficient/recommended way would be:
>>> for c in reversed(num):
... print(c, end='')
Why make it a number? 'In reverse' implies a string. So don't cast it to int but use it as string instead and just loop over it backwards.
You've got here a variety of different answers, many of which look similar.
for i in str(num)[::-1]:
print i
This concise variation does a few things worth saying in english, namely:
Cast num to a string
reverse it (with [::-1], an example of slicing, a pythonic idiom that I recommend you befriend)
finally, loop over the resultant string (since strings are iterable, you can loop over them)
and print each character.
Almost all the answers use [::-1] to reverse the list -- as you read more code, you will see it more places. I recommend reading more about it on S.O. here.
I hate to do your problem for you since you didn't really try to actually solve it or say what you're specifically having a problem with, but:
num = str(input("..."))
output = [num[-i] for i in range(len(num))]
print(output)
output = input("Insert number of your choice: ")[::-1]
print("Your output!: %s" % output)
In python 3.x+ input is automatically a string, doing [::-1] reverses the order of the string

Categories

Resources