Palindrome String check using recursion in Python

Palindrome String check using recursion in Python

Recursion of function is one of the interesting feature of any function of recursive nature. Benefit of using recursion is 1. Less line of code for implementation. 2. No need to write iterative statement multiple time. and easy to learn. In case of recursion the function use to call itself again and again till it reaches at bottom and returns to its caller(self) with calculated value. The self will again calculate next level of value and return to its caller. It goes to continue till it comes out from the very fist call of function. Here We have implemented Palindrome String check using Recursion function.

'''
Created on Jan 8, 2020
@author: admin@pythonport.com
'''
word = input("Enter word to check palindrom string - ")
def palindromCheck(word):
    length = len(word)
    if length == 0 or length == 1:
        return "Palindrom String"
    elif word[0] == word[length - 1] :        
        return palindromCheck(word[1:length - 1])        
    else :
        return "Not Palindrom String"

status = palindromCheck(word)    
print("{0} is {1}".format(word, status))

Here function palindromCheck() is a recursive function which is called from main once by passing the word to check palindrome. Now this function is called again and again by passing current words first position and last-1 position data. If every thing goes well it will return palindrome string else it will return not a palindrome string. Check your self for the output. Hope it helps.

Please comment if you want your valuable feedback or code improvement advice to be added by me.

Sample code to connect python with database

Connect Python with MySql

Python having feature to connect any of the database with the help of different database connection packages. Like to connect Python with MySql we can use mysql.connector package. Which can be downloaded from pip package of Python very easly. Here is the example of Python connection with MySQL.

import mysql.connector
mydb = mysql.connector.connect(
host=”localhost”,
user=”root”,
passwd=”bokaro”,
database=”jnvbokaro”
)

mycursor = mydb.cursor()
sql = “SELECT * FROM student”
mycursor.execute(sql)
myresult = mycursor.fetchall()

for x in myresult:
print(x)

Here you need to import mysql.connector if already installed in your machine else you need to download and install using pip command. You can google it for installation process using pip. Once imported connector then you need to create connection using connect function by passing host, user, passwd and database name. Once the connection is ready you can call cursor and execute query on cursor. Once the function fetchall() called the result need to store in variable and at last iterate the result and get desire output. That’s it. You are done.