How do you add together numbers in string? - python-3.x

def sum_digits(user_input):
total = 0
for c in user_input:
if c.isdigit():
total += int(c)
print(total)
The problem I'm having is that when lets say the user enters car888 the program will output (8, 16 and 24)
But all I want it to output is the sum of the numbers so just 24.

I think your print is simply place in the wrong position. You currently have it nested under the if statement and so it will return each individual iteration.
Try this:
def sum_digits(user_input):
total = 0
for c in user_input:
if c.isdigit():
total += int(c)
print(total)

Related

Having an issue relating to finding an Armstrong number from a list in Python [duplicate]

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

Want to print consecutive 1's in

from array import *
n=int(input("Enter the number"))
m=bin(n)
#print(m)
a=array("u",[])
a=int(m[2:])
print(a)
count=0
for i in range(a):
if(a[i]=="1" and a[i+1]=="1"):
count=count+1
print(count)
Here i want to print'ONLY' the number of consecutive 1's that appear in a binary number.
If your logic is correct try this,
n = int(input('Enter a number : '))
nb =bin(n)
l = list(nb)[2:]
count = 0
for i in range(len(l)-1):
if l[i]=='1' and l[i+1]=='1':
count += 1
print(count)

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

Cumulative total from user's input string

I have tried to write a function that takes sequence of integers as input from the user and returns cumulative totals. For example, if the input is 1 7 2 9, the function should print 1 8 10 19. My program isn't working. Here is the code:
x=input("ENTER NUMBERS: ")
total = 0
for v in x:
total = total + v
print(total)
and here is the output:
ENTER NUMBERS: 1 2 3 4
Traceback (most recent call last):
File "C:\Users\MANI\Desktop\cumulative total.py", line 4, in <module>
total = total + v
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I don't know what this error means. Please help me to debug my code.
This code will work. Remember: read the code and learn how it works.
x = input("Enter numbers: ") #Take input from the user
list = x.split(" ") #Split it into a list, where
#a space is the separator
total = 0 #Set total to 0
for v in list: #For each list item
total += int(v) #See below for explanation
print(total) #Print the total so far
There are two new things in this code:
x.split(y) splits x up into a list of smaller strings, using y as the separator. For example, "1 7 2 9".split(" ") returns ["1", "7", "2", "9"].
total += int(v) is more complicated. I'll break it down more:
The split() function gave us an array of strings, but we want numbers. The int() function (among other things) converts a string to a number. That way, we can add it.
The += operator means "increment by". Writing x += y is the same as writing x = x + y but takes less time to type.
There is another problem with the code: You say you need a function, but this is not a function. A function might look like this:
function cumulative(list):
total = 0
outlist = []
for v in list:
total += int(v)
outlist.append(total)
return outlist
and to use it:
x = input("Enter numbers: ").split(" ")
output = cumulative(x)
print(output)
but the program will work just fine.
Cumulative totals
input_set = []
input_num = 0
while (input_num >= 0):
input_num = int(input("Please enter a number or -1 to finish"))
if (input_num < 0):
break
input_set.append(input_num)
print(input_set)
sum = 0
new_list=[]
for i in range(len(input_set)):
sum = sum + input_set[i]
new_list.append(sum)
print(new_list)

What is wrong with this code that tries to print a decrementing sequence of numbers?

I am very new to python and want to write a program that counts down. It has to start at 100 and ends at 1 or 0. How do i have to do that?
This is what i've got now:
def countdown(n):
while n > 0:
print (n)
n = n =2**123
print('Blastoff')
countdown(200)
n = n =2**123
??? What is this supposed to do? What are you trying to accomplish by setting n to 2 to the 123th power? I think
n = n - 1
or
n -= 1
would be more appropriate.
Here is the code:
#!/usr/bin/python
def countdown(count):
while (count >= 0):
print ('The count is: ', count)
count -= 1
countdown(10)
print ("Good bye!")
If you want to it count down in the terms of actual seconds, which I'm going to guess is what you are going for it would be done by causing the countdown to sleep for 1 second at each iteration:
#!/usr/bin/python
import time
def countdown(count):
while (count >= 0):
print ('The count is: ', count)
count -= 1
time.sleep(1)
countdown(10)
print ("Good bye!")
The output is:
The count is: 10
The count is: 9
The count is: 8
The count is: 7
The count is: 6
The count is: 5
The count is: 4
The count is: 3
The count is: 2
The count is: 1
The count is: 0
Good bye!
Let me know if you have any questions.
In python, the indentation matters. All of the lines inside the function have to be indented.
Your method should have been:
def countdown(n):
while n > 0:
print (n)
n = n-1
print("Blastoff")
or a more pythonic way could be:
def countdown(n):
for i in reversed( range(n) ):
print i
print "Blastoff"
Easy way is using range with negative increment parameter.
For example:
for n in range(10,0,-1):
print(n)
Another way: you can use yield command. It's using for making a generator. It's like to return command.
For example:
#this is generator function
def countdown(start,last):
n=start
while(n>last):
yield n
n-=1
for n in countdown(10,0):
print(n)
i would simply wright something like:
import time
num1 = 100
num2 = 0
while (num1 > num2):
print num1
num1 = num1 - 1
time.sleep(1)
Hay Try This You Can Input The Number You Need To Count Down From:
import time
numTimes = int(input("How Many Seconds Do You Wish To Have Untill LiftOff: "))
def countdown(count):
while (count >= 0):
print ("LiftOff In: ", count)
count -= 1
time.sleep(1)
countdown(numTimes)
print ("!WE HAVE LIFT OFF!")
The following code should work:
import time
start = int(input("How many seconds do you want?\nSeconds: "))
for i in range(start,-1,-1):
time.sleep(1)
print(i)
print "Countdown finish!"

Resources