Data Science and Artificial Intelligence

Python Basics for Data Science with Hangman Game

Python designed by “Guido Van Rossumis” is one of the most growing programming languages today, which is mainly known for its code readability and its simple syntaxes that allows programmers to write codes in fewer lines.

Python is used in or to develop many applications. Few are listed below:

Free Step-by-step Guide To Become A Data Scientist

Subscribe and get this detailed guide absolutely FREE

  • Web and Internet Development
  • Desktop GUI Applications
  • Software Development Applications
  • Database Access
  • Network Programming
  • Games and 3D Graphics

And many more.

Python is the most preferable language for Data Science and in other fields too because of its vast in-built libraries that are useful in carrying out numerical and scientific computations.

Before moving ahead you can go through the below link blogs to gain more knowledge on Data Science.

Everything_You_need_to_know_Data_Science

Data_Science_Deep_Learning

Top_10_Python_Libraries_for_DataScience

In this blog we will learn Python for Data Science, which will cover with its basic programming concepts with the help of a mini project of Hangman game

The recent version of Python is Python 3. We can write Python code in a text editor, however in this blog we have used an IDE Jupyter Notebook.

If you don’t have Jupyter Notebook installed, refer to our blog on Python installation:

Let us now dive into the concepts of Python and understand it from scratch.

SYNTAX

Let us understand the syntax of Python by a simple program.

print("Hello World!")

In the above program, we can see a statement is printed using a single command ‘print’.

INDENTATION: Many of us must have often heard the term Indentation when it comes to Python programming. The space between the page border and the start of the text is what we call Indentation. In other programming language the indentation in code is for readability purpose only, but in Python indentation is very important.

Python uses indentation to indicate a block of code.

Now we will understand, what difference can indentation make in a program.

if 10 > 5:
  print("Ten is greater than five!") #line of code with indentation
if 10 > 5:
print("Ten is greater than five!") #line of code without indentation

As we can see in the above programs, the first program works fine but the second program throws error. This is because in the first program, providing indentation in the second line of code, made it inside of the ‘if’ block. Whereas in the second program indentation is missing.

COMMENT

Comment in a program is regular english sentences. Comments are non-executable part in a program. In Python, comment start with a ‘#’ symbol.

For eg:

VARIABLE

Variables are used to store data values. Python doesn’t have any command to declare variables. We just assign a value to a variable and it is created. It does not need any particular type to be declared and its type can even we changed after it has been already set.

For eg:

x = 5.2 #this is of the type float
age = 16 
a = ‘John’ #this is of the type string that can be declared either by using single or double quotes

Note: variable names are case sensitive.

OUTPUT VARIABLE

To get the output we either use the ‘print’ command or simply mention the variable name that we want to print.

a = 10
b = "Ram"

print(a)
b

We can get to know the type of the data through the below command:

print("Data Type of variable a",type(a))
print("Data Type of variable b",type(b))

Then we will get the output something like this:

TAKING INPUT

If we want to take input from users, we use the input() function.

x = input('Enter a programming language:')
print(x)

PYTHON COLLECTIONS

Coming to the main topic in Python we will now discuss about the four collection data types in Python. That are:

  • List
  • Set
  • Tuple
  • Dictionary

These collection data types are in one way useful for storing heterogeneous data.

LIST : Lists are similar to array. List is a collection of data, which is ordered. The items present in a list are separated by commas and enclosed within [ ].

Lists are mutable that means values of list can be altered.

For Eg:

list_int = [34, 6, 73, 22, 15]

list_str = [“Red”, “Yellow”, “Orange”]

A number of operations can be performed on lists like accessing items from list, changing item value, adding items, deleting items which we will see in our upcoming blog.

TUPLE : Tuples are ordered sequence of items same as lists. The items present in a list are separated by commas and enclosed within ( ).

Tuples are immutable that means tuple once created can’t be modified.

For eg:

tuple_fruit = (“Apple”, “Banana”, “ Orange”, “Mango”)

We can perform the same operations as in lists, however, we can change the value of the items present in a tuple.

SET : Set is a collection of unique values which is unordered that means the items will appear in a random order and since it is unordered its indexing can’t be done and hence it is unindexed.

The items present in a list are separated by commas and enclosed within { }.

Once a set is created we cannot change the value of the items but we can add new items.

For eg:

set_cars = {“BMW” , “Audi”, “Jaguar”, “Mercedes”}

DICTIONARY : A dictionary is a collection of words,with each item being a pair in the form key:value. Dictionary is unordered but indexed, as we can access the items of a dictionary by referring to its key name.

The items in a dictionary is enclosed with { }.

For eg:

Dict_cap = { “India”: ”New Delhi”, “Bangladesh”: “Dhaka”, “Sri Lanka”: “Colombo”, “Singapore”: “Singapore”}

ARRAYS

Python doesn’t have built-in support for Arrays, but Python lists can be used instead. Arrays are used to store multiple data of same type in a single variable.

fruits  =  ["Apple", "Banana", "Grapes", "Orange"]
print(fruits)

We can access items from an array with the help of the index of each item. Indexing starts from 0. Therefore, to access the second fruit banana we will write code as below:

x = fruits[1] #the fruit banana is present at index 1
x

STRINGS

String is a data type in python which is created using single, double or sometimes triple quotes.

Python doesn’t have a character data type, a single character is considered as a string of length 1.

We have already seen examples on how to create a string.

Now let us start with performing some operations on a string that has been explained with comments at each line of code.

string1 = "Python is an easy programming language"
print(string1)
#string indexing is done same as arrays
print("First character of the string",string1[0]) 

#last character indexing starts from -1
print("Last character of the string",string1[-1])

#length function is used to return the length of the string
print("Length of the string:", len(string1)) 

#upper function is used to convert the string to uppercase
print("Upper casing the string: ", (string1.upper())) 

# lower function is used to convert the string to lowercase
print("Lower casing the string: ",(string1.lower())) 

#split method splits the string into substrings based on the parameter passed
print("Splitting the string: ", (string1.split(","))) 

CONDITIONAL AND LOOPING STATEMENTS

IF_ELSE

The if else statement in Python is used for decision making.

We can use ‘elif’ in place of if else statement that means if the previous conditions were not true then try the else statement.

Eg:

a = 50
b = 50
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")

WHILE STATEMENT

With the while loop a set of statements can be executed as long as a statement is true.

i = 1
while i < 10:
  print(i)
  i += 1

BREAK AND CONTINUE STATEMENT 

The break statement can stop the loop even if the while condition is true and it won’t execute further and the continue statement can stop the current iteration, and continue with the next one.

i = 1
while i < 10:
  print(i)
  if i == 3:
    break
  i += 1
i = 0
while i < 10:
  i += 1 
  if i == 3:
    continue
  print(i)

 FOR LOOP

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

fruits = ["Red", "Blue", "Green"]
for x in fruits:
  print(x)

THE RANGE() FUNCTION

The range() function includes some range range of number through which looping would be done till that specified number of times.

It can take upto 3 parameters.

For 1 parameter:

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), goes up to the given range excluding that particular value.

for x in range(6):
  print(x)

For 2 parameters:

The range will return values starting from the first parameter(included) and goes up till the second parameter(excluded)

for x in range(2,6):
  print(x)

For 3 parameters:

The range will return values starting from the first parameter(included), goes up till the second parameter(excluded) and the 3rd parameter is the difference between each number in the sequence.

for x in range(1, 10, 2):
  print(x)

FUNCTIONS

A function in Python is a block of code that takes some input, do some specific computation and produces output. Function avoids the code reusability as we can call the function again and again when needed.

CREATING AND CALLING A FUNCTION

To create a function we use the keyword def.

def my_function():
  print("This is my function")

my_function()

We can also pass as many parameters to the function separated by a comma.

def my_function(fname):
  print(fname + " India")

my_function("Great")
my_function("Incredible")

LAMBDA FUNCTION

Anonymous function is a function that is defined without a name. We have read that in python a normal function is defined by def keyword and the lambda keyword is used to define anonymous function.

It has the following syntax:

lambda arguments : expression

Lambda function can take any number of arguments.

Let’s see this with the help of an example:

def square(y):
    return y*y;
  
g = lambda x: x*x
print(g(7))
  
print(square(5))

The above code is to illustrate the square of a number and has been shown with the usage of both def and lambda.

Therefore the output would be:

Lambda functions can be used along with built-in functions like filter(), map() and reduce().

filter() : The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function returns True.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)

In the above program we have a list of numbers stored in variable ‘li’ and the lambda function is used to filter out all the even numbers from the list and returns the odd numbers.

map() : The function map(function, list) is called with a lambda function and a list and returns a new list which contains all the lambda modified items returned by that function for each item.

li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)

In the above program map() function is used which returns the double of the given list.

reduce() : The function reduce(function, list) takes a list of values and returns a new reduced result with a single value. This performs a repetitive operation over the pairs of the list, which is imported from the functools library.

from functools import reduce
li = [6, 22, 17, 88, 5, 11]
sum = reduce((lambda x, y: x + y), li)
print (sum)

The above program takes a list of values and uses the reduce() function to return the sum of all the values present in the list.

OBJECTS AND CLASSES

Python is an object oriented programming language. Everything in python is Object which is a collection of data(variables) and methods(functions).

A class is a “blueprint” for creating objects.

CREATING CLASS

In python we create a class by using the keyword class.

class MyClass:
	x = 10

CREATING OBJECT

Now we will create object using the class name.

p1 = MyClass()
print(p1.x)

THE init() FUNCTION

The _init_() function is an in-built function.

All classes have a function called __init__(), which is always executed when the class is being initiated.

Let us see an example to understand this in a better way.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age  = age

p1 = Person("Ram", 45)

print(p1.name)
print(p1.age)

In the above program we created a class named Person and used the _init_() function to assign values for name and age.

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class.

EXCEPTION HANDLING

An event that disrupts the normal flow of the program is called exception. Therefore the runtime error that occurs in our program is what we call an exception.

Whenever an exception occurs it halts the execution of the code and gives an error message.

These exception needs to be handled in order to maintain the normal flow of the program and that is where we have the concept of Exception Handling.

We do Exception Handling via try-except-finally blocks.

Let us understand these terms in brief.

If we are not sure whether our program may throw some exception,we must place our code in the try block.

try : this block lets us test a block of code for errors.

except : if we find any occurrence of exception in the above block, this block lets us handle the error. Therefore this block will only get executed if we find any exception in try block.

finally :  this is the block that would execute the code regardless of whether an exception occurs or not.

try:
  print(a)
except:
  print("We can see the variable a is not defined")
finally:
  print("Finally block executed")

In the above program we can see,we are trying to print a variable ‘a’,( in the try block) which is not defined. Hence we would get an exception. In order to handle this exception we run the except block that would be execute the block of code since an exception occur.

The finally block will be executed regardless of the exception occuring or not.

Therefore the output would be:

Now we are almost done with the basics of Python programming, let us understand these concepts with the help of a mini project that is a Hangman game.

Hangman is a word guessing where we have guess a word by entering random letters one at a time. If for a given number of attempts we could guess it right then we win otherwise we lose.

Let us do the scripting for the same.

The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.

Then we have imported the sys module. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. sys.exit will exit the process when called from the main thread.

Then a random word is picked up from our collection ‘wordList’ and the player gets limited chances to win the game(here we have kept 10 attempts).

When a letter in that secretWord is guessed correctly, that letter position in the word is made visible replacing the ‘-’ symbol and for incorrect input player will get a message.  In this way, all the letters of the word are to be guessed before all the chances are over.

So the code would go like this:

import random
import sys


# we have made a list of some words of animal’s name
wordList =["lion", "cat", "dog", "owl", "goat", "elephant", "zebra", "tiger",
 "leopard", "giraffe", "horse", "rabbit", "camel", "bear", "donkey"]

#created an array of chosen_word where the correct word guessed by the player would be stored
chosen_word = []  
# we randomize single word from the list that would be randomly given to the player to guess
secretWord = random.choice(wordList) 

#length of the secretWord would be stored in variable length_word
length_word = len(secretWord) 

#these would be the only letters player can enter
letters = "abcdefghijklmnopqrstuvwxyz" 
#the above entered letter would be stored in an array called letter_storage
letter_storage = [] 

# created a function that would ask the players whether they are interested in playing the game they can answer in yes/y or no/n
def start():
    print("Let us play the Hangman game\n")

    while True:
        gameChoice = input("Are you interested?\n").upper()

        if gameChoice == "YES" or gameChoice == "Y":
            break
        elif gameChoice == "NO" or gameChoice == "N":
            sys.exit("Until next time!")
        else:
            print("Please Answer only Yes or No")
            continue

start()


#function that would describe some detail about the secret word that would be guessed by the player
def info():

    for character in secretWord: # printing blanks for each letter in secret word by displaying '-' symbol
        chosen_word.append("-")

    print("The word you need to guess has", length_word, "characters")

    print("Make sure to enter 1 letter from a-z at a time\n\n")

    print(chosen_word)


#function that would take input from user, maximum attempt is 10 times, check for the entered letter
def guessGame():
    guess_taken = 1

    while guess_taken < 10: #while the attempts are less than 10 the below execution would be done


        guess = input("Enter a letter\n").lower()

        if not guess in letters: #checking input if other than what is stored in variable letters
            print("Enter a letter from a-z alphabet")
        elif guess in letter_storage: #checking if letter has been already entered
            print("You have already entered that letter!")
        else: 
            #if the entered letter exists in the secretWord it will append every time it is correctly entered and will display a message
            letter_storage.append(guess)
            if guess in secretWord:
                print("Correct choice!")
                for x in range(0, length_word): 
                    if secretWord[x] == guess: 
                        chosen_word[x] = guess #if the guessed word is same as the secretWord then it will store in the chosen_word
                        print(chosen_word)

                if not '-' in chosen_word: #when no blank is left, player wins
                    print("You won!")
                    break
            else:
                print("The letter is not in the word. Try Again!")
                guess_taken += 1
                if guess_taken == 10: #when attempts exceeds 10 times player loses
                    print("You Lost")
                    print("You have no more attempts left, the word was",   secretWord)


info()
guessGame()

print("Game Over!")

The output of the code would be something like taking the scenario that a player would win the game.

The explanation of the code is given with the comments. We urge our readers to practice the above code to have a better understanding.

Let us look at one more scenario where the player fails to guess the word.

Hope this blog helped you to understand python data science programming basics with Hangman Game.

If you have any queries do mention it in the comment section below.

For more Data Science and Big Data visit our website regularly.

You can refer to other Data Science related blogs for beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Close
Close