The post Sum Of Elements In A List In Python appeared first on PythonForBeginners.com.

]]>The first way to find the sum of elements in a list is to iterate through the list and add each element using a for loop. For this, we will first calculate the length of the list using the len() method. After that, we will declare a variable `sumOfElements`

to 0. After that, we will use the range() function to create a sequence of numbers from 0 to `(length of the list-1)`

. Using the numbers in this sequence, we can access the elements of the given list and add them to `sumOfElements`

as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length=len(myList)
sumOfElements=0
for i in range(list_length):
sumOfElements=sumOfElements+myList[i]
print("Sum of all the elements in the list is:", sumOfElements)
```

Output:

```
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
```

Alternatively, we can directly iterate through the list using a for loop. Here, we will access each element in the list directly and add them to `sumOfElements`

as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = 0
for element in myList:
sumOfElements = sumOfElements + element
print("Sum of all the elements in the list is:", sumOfElements)
```

Output:

```
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
```

We can also use a while loop to find the sum of the elements in the list. For that, we will first calculate the length of the list using the len() method. After that, we will initialize variables named count and `sumOfElements`

. We will initialize both the elements to 0.

In the while loop, we will access each element in the list using the count variable and add them to `sumOfElements`

. After that, we will increment the value of the count by 1. We will continue this process until the count becomes equal to the length of the list.

You can write a program to find the sum of elements in a list in python as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
list_length = len(myList)
sumOfElements = 0
count = 0
while count < list_length:
sumOfElements = sumOfElements + myList[count]
count = count + 1
print("Sum of all the elements in the list is:", sumOfElements)
```

Output:

```
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
```

Python also provides us with an inbuilt sum() function to calculate the sum of the elements in any collection object. The sum() function accepts an iterable object such as list, tuple, or set and returns the sum of the elements in the object.

You can find the sum of the elements of a list using the sum() function as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The given list is:")
print(myList)
sumOfElements = sum(myList)
print("Sum of all the elements in the list is:", sumOfElements)
```

Output:

```
The given list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum of all the elements in the list is: 45
```

In this article, we have discussed different ways to find the sum of elements in a list in python. To read more about lists in python, you can read this article on how to compare two lists in python. You might also like this article on list comprehension.

The post Sum Of Elements In A List In Python appeared first on PythonForBeginners.com.

]]>The post Delete All Elements Of A List In Python appeared first on PythonForBeginners.com.

]]>The pop() method is used to delete the last element of a list. When invoked on a list, the pop() method returns the last element of the list and deletes it from the list. We can use the while loop and the pop() method to remove all the elements of the list.

For this, we can keep invoking the pop() method on the list inside the while loop until the list becomes empty. Once the list becomes empty, the while loop will stop its execution and we will get a list that has no elements. You can observe this in the following program.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the pop() method
while myList:
myList.pop()
print("List after deleting all the elements:",myList)
```

Output:

```
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
```

Instead of using the pop() method several times, we can use the clear() method to delete all the elements from a list. The clear() method, when invoked on a list, deletes all the elements of the list.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the clear() method
myList.clear()
print("List after deleting all the elements:",myList)
```

Output:

```
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
```

The del statement is used to delete an object in python. We can also use the del statement to remove the elements of a list. For this, we will create a slice of the list that contains all the elements. After that, we will delete the slice. As the slice contains references to the elements in the original list, all the elements in the original list will be deleted and we will get an empty list. You can do it as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using the del method
del myList[:]
print("List after deleting all the elements:", myList)
```

Output:

```
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
```

This is one of the least used ways to remove elements from a list in Python. You might be knowing that multiplying a list to any number N repeats the elements of the list N times. In the same way, when we multiply a list to 0, all the elements of the list are deleted. So, we can multiply the given list with 0 to remove all of its elements as follows.

```
myList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print("The original list is:")
print(myList)
# deleting elements using *
myList = myList * 0
print("List after deleting all the elements:", myList)
```

Output:

```
The original list is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List after deleting all the elements: []
```

In this article, we have discussed four different ways to delete all the elements of a list in python. To know more about lists in python, you can read this article on list comprehension. You might also like this article on how to get the last element of a list in python.

The post Delete All Elements Of A List In Python appeared first on PythonForBeginners.com.

]]>The post String Indexing in Python appeared first on PythonForBeginners.com.

]]>If we have an ordered sequence or container object such as a string, a list, or a tuple, we can access the elements of the objects using their relative position in the sequence. The relative position of the elements in the ordered sequence is termed as index. With Indexing, we can access any element from an ordered sequence using the indices.

In python, string indexing is zero based. It means that we start the counting from 0 and the first character of the string is assigned the index 0, the second character is assigned the index 1, the third character is assigned the index 2 and so on.

We can understand this using the following example.

Suppose that we have a string “PythonForBeginners”

Here, the index of the letter “P” is 0. The index of the letter “y” is 1. The index of letter ”t” is 2, The index of letter “h” is 3 and so on. The index of the last letter “s” is 17.

In python, we can use positive as well as negative numbers for string indexing. Let us discuss them one by one.

As we have seen above, Strings are indexed using positive numbers from 0 to string length -1. We can access a character at any position between 0 to (length of the string) -1 using positive indices as follows.

```
myString = "PythonForbeginners"
index = 0
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = 17
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
```

Output:

```
Character at index 0 in the string 'PythonForbeginners' is P.
Character at index 1 in the string 'PythonForbeginners' is y.
Character at index 2 in the string 'PythonForbeginners' is t.
Character at index 3 in the string 'PythonForbeginners' is h.
Character at index 17 in the string 'PythonForbeginners' is s.
```

Always remember that an index greater than or equal to the string length will cause an IndexError exception as follows.

```
myString = "PythonForbeginners"
index = 20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
```

Output:

```
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
```

You can either avoid the IndexError exception by checking the value of index before accessing any character in the string. Alternatively, you can use python try except block to handle the exceptions if they occur.

Here, I will suggest you to use the try except blocks. Checking the index every time we access a character may be redundant and costly if we are accessing using indices less than the length of the string. While using try except blocks, the program will not check the value of index each time we access a character from the string. If IndexError occurs, it will be handled by the code in the except block.

We can also use negative indices for accessing characters from a string. In python, the last character of the string is assigned an index -1. The second last character is assigned an index -2. Similarly, the first character of the string is assigned an index -(length of the string).

We can understand this using the following example.

Suppose that we have a string “PythonForBeginners”

Here, the index of the letter “s” is -1. The index of the letter “r” is -2. The index of letter ”n” is -3 , The index of letter “n” is -4 and so on. The index of the first letter “P” is -18.

You can verify this using the following program.

```
myString = "PythonForbeginners"
index = -1
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -2
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -3
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -4
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
index = -18
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
```

Output:

```
Character at index -1 in the string 'PythonForbeginners' is s.
Character at index -2 in the string 'PythonForbeginners' is r.
Character at index -3 in the string 'PythonForbeginners' is e.
Character at index -4 in the string 'PythonForbeginners' is n.
Character at index -18 in the string 'PythonForbeginners' is P.
```

While using negative numbers as indices, Make sure that you do not pass an index less than -(length of the string). Otherwise, your program will run into an IndexError as follows.

```
myString = "PythonForbeginners"
index = -20
character = myString[index]
print("Character at index {} in the string '{}' is {}.".format(index, myString, character))
```

Output:

```
Traceback (most recent call last):
File "/home/aditya1117/PycharmProjects/pythonProject/string12.py", line 3, in <module>
character = myString[index]
IndexError: string index out of range
```

In this article, we have studied string indexing in python. We have seen how we can use negative as well as positive numbers to access characters from a string. To study more about strings in python, you can read this article on string concatenation.

The post String Indexing in Python appeared first on PythonForBeginners.com.

]]>The post Check For Perfect Number In Python appeared first on PythonForBeginners.com.

]]>A number is called a perfect number if it is equal to the sum of all of its factors excluding the number itself. If we consider the number itself in the sum, we can say that the sum of all the factors of a perfect number is double the given number.

For example, consider the number 6. It has four factors i.e. 1,2,3, and 6. As we are excluding the number itself, the sum of other factors i.e. 1, 2, and 3 is 6. Hence, 6 is a perfect number.

Alternatively, the sum of all the factors of 6 is 1+2+3+6 i.e. 12, which is double the number itself. Hence, 6 is a perfect number.

Let us take another number 10. The factors of 10 are 1,2,5, and 10. The sum of all the factors of 10 equals 18, which is not double the given number. Hence, 10 is not a perfect number.

To check for a perfect number, we will first find its factors. After that, we will check if the sum of all the factors is double the given number or not.

To find the factors of the given number N, we will divide the number by all the numbers starting from 1 to N. The numbers that completely divide the given number will be declared as factors of N. We will store these factors in a list as follows.

```
dedef calculate_factors(N):
factors = []
for i in range(1, N + 1):
if N % i == 0:
factors.append(i)
return factors
input_number = 10
output = calculate_factors(input_number)
print("factors of {} are {}".format(input_number, output))
```

Output:

`factors of 10 are [1, 2, 5, 10]`

After finding the factors of the given number, we will find the sum of the factors using the sum() function. After finding the sum, we will check if the sum is double the given number or not. If yes, we will say that the given number is a perfect number. Otherwise not.

We can implement this logic to check for a Perfect number in python as follows.

```
def calculate_factors(N):
factors = []
for i in range(1, N + 1):
if N % i == 0:
factors.append(i)
return factors
def check_perfect_number(N):
factors = calculate_factors(N)
sumOfFactors = sum(factors)
if sumOfFactors // 2 == N:
return True
else:
return False
input_number = 10
output = check_perfect_number(input_number)
print("{} is a perfect number: {}".format(input_number, output))
input_number = 6
output = check_perfect_number(input_number)
print("{} is a perfect number: {}".format(input_number, output))
```

Output:

```
10 is a perfect number: False
6 is a perfect number: True
```

In this article, we have discussed what a perfect number is. We have also implemented a program to check whether a given number is a perfect number or not. To know more about numbers in python, you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.

The post Check For Perfect Number In Python appeared first on PythonForBeginners.com.

]]>The post Find The Sum Of Digits Of An Integer In Python appeared first on PythonForBeginners.com.

]]>To find the sum of digits of a number N, we can extract the digits of a number and add them one by one. For this, we will extract the digits from right to left. For extracting the digits, we will divide the number by 10 and store the remainder during each division operation. We will keep dividing the number by 10 until it becomes 0. In this way, we can extract digits one by one.

For example, If we are given the number 12345, we will calculate the sum of digits as follows.

- First, we will initialize a variable sumOfDigits to zero.
- After that, we will divide 12345 by 10.
- After division, we will add reminder 5 to sumOfDigits and update the number to 1234.
- Then, we will divide 1234 by 10.
- After division, we will add reminder 4 to sumOfDigits and update the number to 123.
- Again, we will divide 123 by 10.
- After division, we will add reminder 3 to sumOfDigits and update the number to 12.
- Again, we will divide 12 by 10.
- After division, we will add reminder 2 to sumOfDigits and update the number to 1.
- Now, we will divide 1 by 10.
- After division, we will add reminder 1 to sumOfDigits and update the number to 0.
- As the number has become 0, we will be having the sum of digits of the number 12345 in the variable sumOfDigits i.e. 15.

As we have seen above, to find the sum of digits of an integer in python, we just have to divide the number by 10 until it becomes 0. At the same time, we have to add the remainder in each division to obtain the sum of digits. We can implement the program to perform this operation as follows.

```
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
input_number = 12345
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
input_number = 126
output = calculate_sum_of_digits(input_number)
print("Sum of digits of {} is {}.".format(input_number, output))
```

Output:

```
Sum of digits of 12345 is 15.
Sum of digits of 126 is 9.
```

In this article, we have discussed and implemented a program to find the sum of digits of an integer in Python. To learn more about numbers in python, you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.

The post Find The Sum Of Digits Of An Integer In Python appeared first on PythonForBeginners.com.

]]>The post Check For Moran Number In Python appeared first on PythonForBeginners.com.

]]>A Moran number is a number, which when divided by the sum of its digits, gives a prime number as the result. In other words, if we take a Moran number, calculate the sum of its digits, and divide the number with the sum of the digits, the result will be a prime number. Moran numbers are a subset of Harshad numbers.

For example, 42 is a Moran number. If you calculate its sum of digits, it is 6. 42 divided by 6 gives the result 7 which is a prime number. Hence, 42 is a Moran number.

On the other hand, if we take 20, its sum of digits is 2. 20 divided by 2 gives the result 10 which is not a prime number. Hence, 20 is not a Moran number.

To check for a Moran number in Python, we will have to perform the following operation.

- Calculate the sum of the digits of the given number.
- Divide the number by the sum of digits.
- Check whether the result of division is a prime number.

Let us discuss how to find the sum of digits of the number first.

To find the sum of digits of the given number, we will divide the number by 10 until the number becomes 0. During each division, we will get the rightmost digit as a remainder. We will use the remainder to calculate the sum of digits by adding the remainders during each division as follows.

```
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
```

After finding the sum of digits, you can divide the given number by the sum of digits to find the result. Now, we have to check if the number is a prime number or not. For this, we will divide the result by all the numbers from 2 to the square root of the result. If the result is divisible by any of the numbers in this range, the number will not be a prime number. The isPrime() function given below performs this operation. It takes a number as an input argument and returns True if the given number is a prime number. Otherwise, it returns False.

```
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
```

After defining functions for calculating the sum of digits and checking for prime numbers, we can write a program to check for a Moran number in Python as follows.

```
def calculate_sum_of_digits(N):
sumOfDigits = 0
while N > 0:
digit = N % 10
sumOfDigits = sumOfDigits + digit
N = N // 10
return sumOfDigits
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
def check_for_moran_number(N):
sumOfDigits = calculate_sum_of_digits(N)
if N % sumOfDigits == 0:
result = N // sumOfDigits
return isPrime(result)
else:
return False
input_number = 42
output = check_for_moran_number(input_number)
print("{} is a Moran Number:{}".format(input_number, output))
input_number = 20
output = check_for_moran_number(input_number)
print("{} is a Moran Number:{}".format(input_number, output))
```

Output:

```
42 is a Moran Number:True
20 is a Moran Number:False
```

In this article, we have discussed what a Moran number is. We also discussed the steps to check for a Moran number and implemented it in Python. To learn more about numbers in python, you can read this article on decimal numbers in python. You might also like this article on complex numbers in python.

The post Check For Moran Number In Python appeared first on PythonForBeginners.com.

]]>The post Detect Cycle in an Undirected Graph appeared first on PythonForBeginners.com.

]]>We say that a cycle is present in a graph if we can reach the same place after starting from a vertex and traversing one or more edges only once. In other words,if we can start from a vertex and reach the same vertex after traversing one or more edges only once, then we say that a cycle is present in the graph.

For example, consider the following graph.

In this graph, we can start from vertex A and reach the same vertex after traversing through the edges E_{2}->E_{5}->E_{4}. So, we will say that there is a cycle present in the graph.

We can also start from vertex B and follow the path E2-E4-E5 to reach vertex B. Hence, we will again find that there is a cycle present in the graph. Here, you can see that we have considered each edge only once while traversing a path.

On the contrary, consider the following graph.

Here, we cannot reach the same vertex after starting from a vertex without repeating any edge. So, we will say that the graph doesn’t contain any cycle.

As we now have an overview of what a cycle is, Let us formulate an algorithm to detect a cycle in an undirected graph. For this, we will start from the source vertex and will traverse the graph using the breadth-first search algorithm. During traversal, if we find a vertex that has already been traversed, we will say that there is a cycle present in the graph.

The algorithm to detect cycles in an undirected graph can be formulated as follows.

- Create an empty Queue Q.
- Create a list visited_vertices to keep track of visited vertices.
- Insert source vertex into Q and visited_vertices.
- If Q is empty, go to 10. Else goto 5.
- Take out a vertex v from Q.
- If any neighbor of v is already present in the visited_vertices, goto 7. Else, goto 8.
- Print that cycle is present in the graph. Goto 11.
- Insert the unvisited neighbors to Q and visited_vertices.
- Go to 5.
- Print that there is no cycle in the graph.
- Stop.

As we have formulated the algorithm to detect cycle in an undirected graph, let us implement it in python and execute it for the graphs given in the images in the previous sections.

Output:

In this article, we have discussed the algorithm to detect cycle in an undirected graph. Here, we have used the breadth-first graph traversal algorithm. To read about binary tree traversal algorithms, you can read the Inorder tree traversal algorithm or level order tree traversal algorithm.

The post Detect Cycle in an Undirected Graph appeared first on PythonForBeginners.com.

]]>The post Create Decorators Using Classes in Python appeared first on PythonForBeginners.com.

]]>Table of Contents

Any object in python that can be called just like functions and methods is called a callable object. In python every callable object has an implementation of the __call__() method in its class definition. We can say that any object that has the ** __call__**() method in its class definition is called a callable object.

To call an object, we need to implement the ** __call__**() method in the class definition of the object.

For example, look at the following source code.

```
class Car:
def __init__(self):
self.brand = "Tesla"
self.speed = "100mph"
def __call__(self, *args, **kwargs):
print("Called me? I am coming at {} speed.".format(self.speed))
```

Here, we have defined a class named ** Car**. Apart from its constructor definition, we have also defined the

```
class Car:
def __init__(self):
self.brand = "Tesla"
self.speed = "100mph"
def __call__(self, *args, **kwargs):
print("Called me? I am coming at {} speed.".format(self.speed))
# create callable object
myCar = Car()
# call myCar
myCar()
```

Output:

```
Called me? I am coming at 100mph speed.
```

We can use any callable object that accepts a function or a callable object as input and returns a callable object or a function to implement python decorators.

We can create decorators using classes by defining callable objects using the __call__() method, which we will discuss in this section.

First, we will define a function ** add**() that takes two numbers as input and prints their sum.

```
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)
```

Output:

`The sum of 10 and 20 is 30.`

Now, we have to define a decorator in such a way that the ** add**() function should also print the product of the numbers along with the sum. For this, we can create a decorator class.

We can implement the ** __call__**() method inside a class to implement the decorators.

First, we will define the constructor of the **decorator_class** that accepts the ** add**() function as an input parameter and assigns it to a class variable

Then we will implement the ** __call__**() method. The code inside the

```
class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
```

Inside the ** __call__**() method, we have implemented the code that prints the product of the numbers that are given as input and then returns the output of the

To create a decorated function, We can pass the ** add**() function as an input argument to the constructor of the decorator class. The

```
class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
decorator_object = decorator_class(add)
decorator_object(10, 20)
```

Output:

```
Product of 10 and 20 is 200
The sum of 10 and 20 is 30.
```

Instead of passing the add function to the class constructor, we can specify ** decorator_class** name with

```
class decorator_class:
def __init__(self, func):
self.func = func
def __call__(self, *args):
product = args[0] * args[1]
print("Product of {} and {} is {} ".format(args[0], args[1], product))
return self.func(args[0], args[1])
@decorator_class
def add(num1, num2):
value = num1 + num2
print("The sum of {} and {} is {}.".format(num1, num2, value))
# execute
add(10, 20)
```

Output:

```
Product of 10 and 20 is 200
The sum of 10 and 20 is 30.
```

In this method, there is a drawback that you cannot use the ** add**() function to just add the numbers while defining decorated functions using @ sign. It will always print the product of the numbers along with their sum. So,If you are using the add() function at any other place in its original form, it will cause an error.

In this article, we have discussed ways to create python decorators using classes in Python. To learn more about python programming, you can read this article on list comprehension. You may also like this article on the linked list in Python.

The post Create Decorators Using Classes in Python appeared first on PythonForBeginners.com.

]]>The post Check For Prime Number in Python appeared first on PythonForBeginners.com.

]]>Prime numbers are those positive integers greater than one that has only two factors. The examples of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc.

Here,

- 2 has only two factors i.e. 1 and 2.
- 3 has only two factors i.e. 1 and 3.
- 5 has only two factors i.e. 1 and 5.

You can observe that all other numbers also have only two factors.

For checking if a number is prime or not, we just have to make sure that all the numbers greater than 1 and less than the number itself should not be a factor of the number. For this, we will define a function isPrime() that takes a number N as input. Then it checks whether any number between 2 and N-1 is a factor of N or not using a for loop. If a factor is present, it returns False stating that the input number N is not a prime number. Otherwise, it returns True.

```
def isPrime(N):
for number in range(2, N):
if N % number == 0:
return False
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
```

Output:

```
23 is a Prime number:True
126 is a Prime number:False
```

In the above example, we have checked every number from 2 to N-1 to see if it is a factor of N or not. We can optimize this process by checking numbers till N/2 instead of N-1. This is so because the only factor of N greater than N/2 is the number N itself. So, we will check for factors in numbers only till N/2. Additionally, we can also check if a number is even or not. If a number greater than 2 is even, it will never be a prime number. We can define an improved isPrime() function using these concepts as given below.

```
def isPrime(N):
for number in range(2, N//2):
if N % number == 0:
return False
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
```

Output:

```
23 is a Prime number:True
126 is a Prime number:False
```

We can again optimize the above program using simple logic. You can observe that factors of a number always occur in pairs. For a number N, the factors can be paired as (1, N), (2, N/2), (3, N/3), (4, N/4) till (N1/2, N^{1/2}). So, for checking for factors, we can check only till N^{1/2} instead of N/2.

For example, if we are given a number 100, all the factors can be paired as (1,100), (2,50),(4,25), (5,20), and (10,10). Here, if 100 is divisible by 2, it must be divisible by 50, if 100 is divisible by 4, it must be divisible by 25. We don’t need to explicitly check both the numbers in a pair to check if a number is a factor or not. So, To check for prime number, We can simply check for a factor till N^{1/2} instead of N/2 using a while loop. If a factor is not present between 2 and N^{1/2}, the number must be a prime number. Using this logic, we can modify the isPrime() function used in the above example as follows.

```
def isPrime(N):
count = 2
while count ** 2 <= N:
if N % count == 0:
return False
count = count + 1
return True
input_number = 23
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
input_number = 126
output = isPrime(input_number)
print("{} is a Prime number:{}".format(input_number, output))
```

Output:

```
23 is a Prime number:True
126 is a Prime number:False
```

In this article, we have discussed three ways to check for a prime number in python. To learn more about numbers, you can read this article on complex numbers in python. You might also like this article on decimal numbers in Python.

The post Check For Prime Number in Python appeared first on PythonForBeginners.com.

]]>The post Recursion In Python appeared first on PythonForBeginners.com.

]]>Recursion is a mathematical concept in which we define something in terms of itself.

For instance, we can define the sum of the first ten natural numbers as the sum of the first nine natural numbers added to the tenth number.

Similarly, we can define the sum of the first nine natural numbers as the sum of the first eight natural numbers added to the ninth natural number.

Here, you can see that we are breaking the problem of the first ten natural numbers into smaller problems like finding the sum of the first 9 numbers, then finding the sum of the first 8 numbers, and so on. In this way, we will come to a position where we have to find the sum of the first natural number i.e. 1 itself. After that, we will have to perform only the atomic addition instead of worrying about the count of natural numbers we are finding the sum of.

As seen above, we can use recursion whenever we can break a problem into a similar but smaller problem. The most common problems where we use recursion are:

- Binary tree traversal problems
- Finding the factorial of a number
- Tower of Hanoi problem
- Finding Fibonacci series

In programming, if a function calls itself, we say that it is a recursive function i.e. it works on the concept of recursion. You can use recursion in python to implement the solution for any problem that can be reduced to a similar but smaller problem.

For instance, let us try to find the sum of the first 10 natural numbers. For that, let us define a function sumOfNumbers() that receives an input number N and returns the sum of numbers from 1 to N.

- To calculate the sum of first 10 natural numbers i.e. sumOfNumbers(10), we will find the sum of the first 9 natural numbers i.e. sumOfNumbers(9) and will add 10 to it.
- Similarly, to find the sum of first 9 natural numbers i.e. sumOfNumbers(9), we will find the sum of the first 8 natural numbers i.e. sumOfNumbers(8) and will add 9 to it.
- Again, to find the sum of the first 8 natural numbers i.e. sumOfNumbers(8), we will find the sum of the first 7 natural numbers i.e. sumOfNumbers(7) and will add 8 to it.
- After that, to find the sum of the first 7 natural numbers i.e. sumOfNumbers(7), we will find the sum of the first 6 natural numbers i.e. sumOfNumbers(6) and will add 7 to it.
- In this way, we will reach a position when we will have to calculate the sum of the first natural number i.e. sumOfNumbers(1). Here, we can simply return 1. This is also called the base case of the recursion as the problem cannot be reduced further into smaller problems.

We can implement the above algorithm as follows.

```
def sumOfNumbers(N):
if N == 1:
return N
else:
return N + sumOfNumbers(N - 1)
input_number = 10
output = sumOfNumbers(input_number)
print("Sum of first {} natural numbers is {}".format(input_number, output))
input_number = 20
output = sumOfNumbers(input_number)
print("Sum of first {} natural numbers is {}".format(input_number, output))
```

Output:

```
Sum of first 10 natural numbers is 55
Sum of first 20 natural numbers is 210
```

While using recursion, we must specify the base case. Otherwise, the program will continue its execution continuously and run into RecursionError. This is due to the fact that the maximum number of recursive calls a function can make is capped at 1000 in Python. If any function makes more than 1000 recursive calls, a RecursionError exception will occur.

In this article, we have discussed recursion in python. We have also implemented a program to find the sum of the first 10 natural numbers in Python. To learn more about functions, you can read this article on closures in python.

The post Recursion In Python appeared first on PythonForBeginners.com.

]]>