I don't see how to add two numbers - python

num1 = bin(input())
num2 = bin(input())
answer = int(num1 ,2) + int(num2,2)
print (bin(answer)) [2:]
input ("press enter to finish")
How do I do it so I can put 2 binary numbers in and add them up, it only lets me put one in and then it just gives me a binary representation of the 1st one.
I really need to know how to do this.

Not quite sure if this is what you are looking for:
#! /usr/bin/python3.2
print (bin(int(input('>> '), 2) + int(input('>> '), 2))[2:])
Example usage:
>> 100
>> 101
1001

This solution assumes you are using Python 2.x. It's not clear if that's the case...
You appear to be using bin() incorrectly. You only need that when converting an integer to a binary string.
You want to use raw_input() instead of input(). The latter will attempt to convert the input to a number automatically, which you don't want.
So:
num1 = int(raw_input(), 2)
num2 = int(raw_input(), 2)
answer = num1 + num2
print bin(answer)[2:]

Guess I would do something like this:
from __future__ import print_function
import sys
if sys.version_info[0]==2: input=raw_input
def get_bin(txt):
while True:
s=input(txt)
try:
return int(s, 2)
except ValueError:
print('"{}" is not a valid binary number'.format(s))
li=[]
for i in range(1,3):
li.append(get_bin('Enter bin number {} >>> '.format(i)))
ans=sum(li)
w=len(bin(ans))
for i, e in enumerate(li):
op='+' if i else ' '
print('{}{:{w}b}'.format(op,e,w=w))
print(' ','='*w)
print(' {:{w}b}'.format(ans,w=w))
On Python 2 or 3, example:
Enter bin number 1 >>> 111111
Enter bin number 2 >>> 11
111111
+ 11
=========
1000010

Related

Calculator - trying to take first number from 'for' and using it as INIT_VALUE

I'm trying to take the first number from a list and use it as my initial value. When I started doing subtraction, I realized that you actually don't start at 0 as you do with adding number, but you start with first number written in 'for'.
For example, when you add 0+4+5, then 4+5 is actually the same thing; when subtracting, it's different to do 0-4-5 and 4-5. I'm just starting with Python and programming in general, so I'm wondering if this is even possible.
My code:
print ("You chose subtraction.")
b = int(input("Enter how many numbers you want to substract."))
c = [int (input( "Number: ")) for _ in range (b)]
result = functools.reduce(operator.sub, c, INIT_VALUE)
print("Your answer is:", result)
You can get the first number that was entered by accessing c[0] ( or values[0] in my example ), you also only need to subtract the values after this index so you can use c[1:] ( or values[1:] in my example )
import operator
import functools
print("You chose subtraction.")
total_numbers = int(input("Enter how many numbers you want to substract."))
values = [int(input("Number: ")) for _ in range(total_numbers)]
result = functools.reduce(operator.sub, values[1:], values[0])
print("Your answer is:", result)
>> You chose subtraction.
>> Enter how many numbers you want to substract.
> 5
>> Number:
> 10
>> Number:
> 1
>> Number:
> 1
>> Number:
> 1
>> Number:
> 1
>> Your answer is: 6
There are a few ways you can do this:
You could get the first number separately:
>>> INIT_VALUE = input('Number: ')
>>> numbers = [int(input('Number: ')) for _ in range(b - 1)]
>>> result = reduce(sub, numbers, INIT_VALUE)
Alternatively, you could use indexing:
>>> INIT_VALUE = c[0]
>>> rest = c[1:]
>>> result = reduce(sub, rest, INIT_VALUE)
Or, if you wanted to use a loop instead of reduce:
>>> result = int(input('Number: '))
>>> for _ in range(b - 1):
... result -= int(input('Number: '))
You can do reduce(sub, lst[1:], lst[0]), but you can also skip the inifializer altogether
reduce(sub, lst)
If you won't provide it, the first value will be taken
https://docs.python.org/3/library/functools.html#functools.reduce
Another option is itertools.accumulate in Python 3. This allows you see intermediate calculations.
import operator as op
import itertools as it
print("You chose subtraction.")
total_numbers = int(input("Enter how many numbers you want to substract? "))
values = [int(input("Number: ")) for _ in range(total_numbers)]
# You chose subtraction.
# Enter how many numbers you want to substract? 3
# Number: 0
# Number: 5
# Number: 6
results = list(it.accumulate(values, op.sub))
results
# [0, -5, -11]
results[-1]
# -11
See also this post comparing accumulate and reduce.

Printing multiple objects without spaces

I'm writing a basic program to convert any 4 digit number in reverse.
I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:
print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: "))
num1 = userNum % 10
userNum2 = userNum // 10
num2 = userNum2 % 10
userNum3 = userNum // 100
num3 = userNum3 % 10
userNum4 = userNum // 1000
num4 = userNum4 % 10
print(num1,num2,num3,num4)
The issue I'm having is the output from the print statement gives me
x x x x
When I would prefer to have
xxxx
Any advice?
If you read the description of the print(), you can see that you can change your last line for:
print(num1,num2,num3,num4, sep='')
Since you just want to convert the input in reverse order. You can take the following approach.
print("This program will display any 4-digit integer in reverse order")
userNum = input("Enter any 4-digit integer: ")
reverse_input = userNum[::-1]
reverse_input = int(reverse_input) # If you want to keep input as an int class
print(reverse_input)
If you want to use your own code then just change the print statement.
print(str(num1) + str(num2) + str(num3) + str(num4))
String concatenation does not add space so you should get desired result.
I used this as a sort of exercise for myself to nail down loops. There are a few loops you can use.
#if using python <3
from __future__ import print_function
x = 3456
z = x
print('While:')
while z > 0:
print(z % 10, end="")
z = z / 10;
print()
print('For:')
for y in xrange(4):
z=x%10
print(z, end="")
x = x / 10
Thanks for asking this question. It encouraged me to go look at python syntax, myself, and I think it's a good exercise.

Writing a program that accepts a two digit # that breaks it down

I am currently using Python to create a program that accepts user input for a two digit number and will output the numbers on a single line.
For Example:
My program will get a number from the user, lets just use 27
I want my program to be able to print "The first digit is 2" and "The second digit is 7"
I know I will have to use modules (%) but I am new to this and a little confused!
Try this:
val = raw_input("Type your number please: ")
for i, x in enumerate(val, 1):
print "#{0} digit is {1}".format(i, x)
It was not clear from your question whether you are looking to use % for string substitution, or % for remainder.
For completeness, the mathsy way using modulus operator on ints would look like this:
>>> val = None
>>> while val is None:
... try:
... val = int(raw_input("Type your number please: "))
... except ValueError:
... pass
...
Type your number please: potato
Type your number please: 27
>>> print 'The first digit is {}'.format(val // 10)
The first digit is 2
>>> print 'The second digit is {}'.format(val % 10)
The second digit is 7
Think about the two digit number as though it were a string. It is easier to grab each digit this way. Using str() will change the integer to a string. Modulos allow you to place these strings into your text.
Assuming the user inputs 27 into the variable called num, the code is:
print 'The first digit is %s and the second digit is %s' % (str(num)[0], str(num)[1])
Another way of coding Python:
val = raw_input("Type your number please: ")
for i in list(val):
print i
Note: val is read as string. For integer manipulation, use list(str(integer-value)) instead
two_digit_number = input("Type a two digit number: ")
print("The first digit is " + two_digit_number[0] + " The second digit is " +
two_digit_number[1])
You don't need modules to solve this question.

Adding the sum of three digits

So I am writting a program that inputs a 3 # digit and breaks it apart. I am having trouble figuring out how to then add the separate digits altogether?
For example: The user inputs 345
My program will break the #'s apart to 3,4,5 but how do I then add those numbers together?
this is my code thus far,
#set variable
val = raw_input("Type your three digit number please: ")
print 'The first digit is {}'.format(val[0])
print 'The second digit is {}'.format(val[1])
print 'The third digit is {}'.format(val[2])
#set variable
total = [val[0] +val [1] + val[2]]
total_value = total
print 'The sum of the three digits is' total_value
A short way to add all of the number's digits together is:
In [3]: sum(map(int, val))
Out[3]: 12
Here, map(int, val) iterates over the characters of val and converts each of them into an int, and sum(...) adds together all those ints.
The nice thing about this approach is that it works for any number of digits.
The reason your original code doesn't work is that val[0] etc are strings, so using + simply concatenates those strings back together. To add the numeric values, you would have to convert the characters to int first:
In [5]: int(val[0]) + int(val[1]) + int(val[2])
Out[5]: 12
You have to convert the individual components to numbers to be able to add them:
total = int(val[0]) + int(val[1]) + int(val[2])
Or, more concise:
total = sum(int(x) for x in val)
An elegant solution is to use python's builtin functions map and sum:
val = raw_input("Type your three digit number please: ")
total = sum(map(int, val))
print 'The sum of the three digits is', total
You just have to do this :
total = int(val[0]) + int(val[1]) + int(val[2])
Since the digits in val are characters, they have to be converted to integers first.
Note that there are no [ ] around the value affected to total as in your code (you don't want a list, you want a single value).
Try this:
res = raw_input("Enter value: ")
print sum(map(int, res))
i think the answer you looking for is something like this:
a = int(input("3 digit number:"))
x = a // 100
y = a // 10 % 10
z = a % 10
print (x + y + z)
i'm a total noob and its an ez question for noobs learning but when looking for an ez answer i couldn't find it anywhere (here) The question is Adding the sum of "THREE" digits...
I got hung up on if the digits were 5 or 6 long dunno what the code would look like if digits weren't defined.
answer:
a = int(input("enter a few numbers:"))
conversion = str(a)
number =[]
for i in conversion:
a = int(i)
number.append(a)
print (sum(number))
or as shown before me:
number = map(int, str(input('Enter a number: ')))
print(sum(number))
but i still have a ways to goes till i understand this properly

Display number int in Python

How to display numbers integer in python ?
For example:
number1 = raw_input('Write one number: ')
number2 = raw_input('Write other number: ')
result = number1 + number2
print "The sum of the numbers is: %d" % result # here, display the result of the operatio n.
You want
result = int(number1) + int(number2)
raw_input returns strings.
raw_input returns strings. If you mean for them to be integers, then use int(x) to convert them to ints.
You have to convert the inputted strings into numbers:
result = int(number1) + int(number2)
Like this;
In [1]: numstr="5"
In [2]: int(numstr)
Out[2]: 5
So in your code result = int(number1) + int(number2)
You'd want to do some input sanitation check though. Users have a bad habit of making mistakes.

Categories

Resources