**Magic Number in Python** | A magic number is a number, when the digits are added recursively it gives a single-digit equal to 1. Also see:- Armstrong Number Program in Python

**We will see these below Python program examples:–**

- What is a magic number in python
- Magic number program in python
- Find all magic numbers in the interval in python
- Python program to find magic number list

## What is a Magic Number in Python

A number is said to be magic when its digits are added recursive till we get a single digit which is equal to 1, this approach uses brute force, which keeps on adding the digit until a single digit is obtained.

**For example: **1234 = 1 + 2 + 3 + 4 = 10

1 + 0 = 1

Therefore, 1234 is a magic number.

## Magic Number Program in Python

Now, let us code to find the magic number in python, for this, we use a while loop to iterate and find the sum of the digits until it becomes a single digit. We have defined a function “Magic” to find the magic number.

Program description:- **Write a program to check whether the number is a magic number or not in python**

```
def Magic(n):
sum = 0
while (n > 0 or sum > 9):
if (n == 0):
n = sum
sum = 0
sum = sum + n % 10
n = int(n / 10)
return True if (sum == 1) else False
n = 1234
if (Magic(n)):
print("The given number is Magic Number.")
else:
print("The given is not a Magic Number.")
```

Output:

The given number is Magic Number.

Now, for the same, we will try in a different way that is shortcut way by using if loop.

```
n = 1234
if (n % 9 == 1):
print("The given number is Magic Number.")
else:
print("The given number is not a Magic Number.")
```

Output:

The given number is Magic Number.

## Python Program to Find All Magic Numbers in the Interval

Here, we find magic numbers between the given interval of numbers, the program takes two inputs from the user and then finds the magic number between that numbers.

```
print("Enter a range")
i1 = int(input("Start: "))
i2 = int(input("Last: "))
print("Magic numbers between ",i1," and ",i2," are: ")
for i in range(i1,i2+1):
if (i % 9 == 1):
print(i)
```

Output:

Enter a range

Start: 1

Last: 100

Magic numbers between 1 and 100 are:

1

10

19

28

37

46

55

64

73

82

91

100

## Python Program to Find Magic Number in List

Now, we find the magic number in a list of elements, that is we iterate and check over all the list elements to find whether it is a magic number or not. The program prints the magic number if it is present in the list.

```
n = [1234, 345, 343]
for i in n:
if (i % 9 == 1):
print(i)
```

Output:

1234

343

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!