﻿ Python: Add two binary numbers - w3resource

# Python Challenges: Add two binary numbers

## Python Challenges - 1: Exercise-31 with Solution

Write a Python program to add two binary numbers.

Explanation:

Sample Solution:-

Python Code:

``````def add_binary_nums(x,y):
max_len = max(len(x), len(y))

x = x.zfill(max_len)
y = y.zfill(max_len)

result = ''
carry = 0

for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1

if carry !=0 : result = '1' + result

return result.zfill(max_len)

```
```

Sample Output:

```100
100
1110
10000000
```

Flowchart:

Python Code Editor:

```def add_binary_nums(x,y):
max_len = max(len(x), len(y))

x = x.zfill(max_len)
y = y.zfill(max_len)

result = ''
carry = 0

for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1

if carry !=0 : result = '1' + result

return result.zfill(max_len)