Kaun Banega Crorepati (KBC) in Python

Introduction

This Python code creates a fun quiz game inspired by KBC, where you answer multiple-choice questions to win virtual prizes. It shuffles a list of questions and keeps track of your progress. You can answer each question or quit the game at any point.

Prerequisites

This KBC-inspired quiz game requires no specific software installation beyond Python itself. Here’s what you’ll need to get started:

  • Python: The code is written in Python, a free and popular programming language. If you don’t have it already, you can download and install it from https://www.python.org/downloads/.
  • Basic understanding of Python: Familiarity with Python syntax and concepts like variables, functions, and loops will be helpful in understanding the code. If you’re new to Python, there are many free online tutorials and resources available to get you started.
  • Content for your quiz: You’ll need to prepare your own questions, answer choices, and corresponding answers for your quiz. This can be a fun way to test knowledge on a particular subject or create a general knowledge challenge.

Learning Objectives

  • Understanding of lists and tuples: The code uses lists to store questions, answers, and prize money. You’ll see how lists can be manipulated and accessed to manage game data. Tuples are used for options that shouldn’t change, like the answer choices (A, B, C, D).
  • Working with functions: The code is divided into functions for specific tasks like answering questions and running the game loop. This promotes code reusability and organization.
  • Using conditional statements: The code uses if statements to check user input, evaluate answers, and determine game flow based on the player’s choices.
  • Iteration with loops: The game loop uses a while loop to iterate through questions until the player exits or completes the quiz.
  • Basic game structure: By following the code structure, you’ll gain insight into how to design a simple question-and-answer game with user interaction.

Installation Guide

  • This KBC-inspired quiz game utilizes Python, a free and open-source programming language. Here’s how to get started assuming you don’t have Python installed yet:
  • Download Python: Head over to the official Python website at https://www.python.org/downloads/. They offer installers for various operating systems (Windows, macOS, Linux). Choose the appropriate installer for your system and download it.
  • Run the installer: Once downloaded, locate the installer file and double-click it to begin the installation process. During installation, you might be given the option to “Add Python to PATH”. This is recommended, as it allows you to run Python from any directory in your command line or terminal.
  • Verify installation (Optional but recommended): Open your command line or terminal application (e.g., Command Prompt on Windows, Terminal on macOS/Linux). In the command prompt, type python –version and press Enter. If Python is installed correctly, you should see the installed Python version number displayed.
  • That’s it! Now you have Python installed and ready to run the KBC quiz game code.

Project Steps

  1. Prepare Quiz Content
    • Gather your questions and answers. Aim for a variety of difficulty levels to keep the game engaging.
    • Create answer choices (at least four options for each question). Ensure the correct answer is among the choices.
    • You can use a text editor or spreadsheet to organize this information.
  1. Create the Python File
    • Open a text editor and create a new file with a descriptive name like kbc_quiz.py.
  1. Import Libraries
    • Add a line at the beginning to import the random module.
  1. Create the Game Loop
    • Use a while loop to iterate through your questions.
    • Inside the loop, you can display the question, shuffle the answer choices, and prompt the user for their answer.
  1. Get User Input
    • Prompt the user to enter their answer (A, B, C, or D) or “quit” to exit the game.
  1. Evaluate User Input
    • Use conditional statements (if statements) to check the user’s answer against the correct answer.
    • Provide feedback based on whether their answer is correct or incorrect.
  1. Track Prize Money (Optional)
    • You can create a list to store prize money for each question (increasing amounts as difficulty progresses).
    • Update the user’s prize money after each question based on their answer.
  1. Enhance the Game (Optional)
    • Consider adding features like:
      • A timer for each question (increases difficulty)
      • Multiple lifelines with limited uses (e.g., 50/50 or audience poll)
      • Difficulty levels with different question sets
  1. Test and Refine
    • Run the game and test it thoroughly.
    • Refine your code based on how it performs and identify areas for improvement.

Remember to replace the example content in Step 4 with your quiz questions and answers. This approach will guide you through building the core functionality of your KBC-inspired quiz game.

Code

				
					import random

questions=['Which god is also known as ‘Gauri Nandan’?',
           'What does not grow on tree according to a popular Hindi saying?',
           'Which city is known as Pink City in India?',
           "Who wrote India's National Anthem?",
           'How many major religions are there in India?',
           'When is the National Hindi Diwas celebrated?',
           'What is the name of the game developer ?',
           'How many states are there in India?',
           'Where in India Gate located?',
           'Who wrote Vande Mataram?',
           'Which one of the following places is famous for the Great Vishnu Temple?',
           'Which Indian monument was originally built as a victory tower to commemorate the defeat of the Khan of Khambhat?',
           "Who among the following was killed during 'Operation Bluestar' of 1984?",
           'Which former Indian President died as a result of a road accident?',
           'Who is the founder of the political party Dravida Munnetra Kazhagam (DMK)?',
           'Who was the first Indian woman to win a medal in the Olympics?']
options=[['A.Agni','B.Indra','C.Hanuman','D.Ganesha'],
         ['A.Money','B.Flowers','C.Leaves','D.Fruits'],
         ['A.Banglore','B.Maysore','C.Jaipur','D.Kochi'],
         ['A.Rabindranath Tagore','B.Lal Bahadur Shastri','C.Chetan Bhagat','D.RK Narayan'],
         ['A.6','B.7','C.8','D.9'],
         ['A.13 September','B.14 September','C.14 July','D.15 August'],
         ['A.Adarsh','B.Aakarsh','C.Aakash','D.Akash'],
         ['A.28','B.29','C.31','D.31'],
         ['A.Agra','B.Punjab','C.Mumbai','D.New Delhi'],
         ['A.Sarat Chandra Chattopadhyay','B.Rabindranath Tagore','C.Bankim Chandra Chatterjee','D.Ishwar Chandra Vidyasagar'],
         ['A.Bordubar, Indonesia','B.Bamiyan, Afghanistan','C.Panja Sahib, Pakistan','D.Ankorvat, Cambodia'],
         ['A.Qutub Minar','B.India Gate','C.Charminar','D.Vijay Stambha'],
         ['A.Baba Santa Singh','B.Haji Mastan','C.Jarnail Singh Bhindrawale','D.Homi Jehangir Bhabha'],
         ['A.Rajendra Prasad','B.Faqruddin Ali Ahmed','C.Giani Zail Singh','D.R.Venkatraman'],
         ['A.C.N. Annadurai','B.M. Karunanidhi','C.M.G. Ramachandran','D.Jayalalitha'],
         ['A.P.T. Usha','B.Kunjarani Devi','C.Bachendri Pal','D.Karnam Maleshwari']]
options50=[['A.Agni','B.','C.','D.Ganesha'],
         ['A.Money','B.','C.Leaves','D.'],
         ['A.','B.Maysore','C.Jaipur','D.'],
         ['A.Rabindranath Tagore','B.','C.Chetan Bhagat','D.'],
         ['A.6','B.7','C.','D.'],
         ['A.','B.14 September','C.','D.15 August'],
         ['A.','B.Aakarsh','C.Aakash','D.'],
         ['A.28','B.','C.','D.31'],
         ['A.','B.','C.Mumbai','D.New Delhi'],
         ['A.','B.Rabindranath Tagore','C.Bankim Chandra Chatterjee','D.'],
         ['A.Bordubar, Indonesia','B.','C.','D.Ankorvat, Cambodia'],
         ['A.','B.India Gate','C.','D.Vijay Stambha'],
         ['A.Baba Santa Singh','B.','C.Jarnail Singh Bhindrawale','D.'],
         ['A.Rajendra Prasad','B.','C.Giani Zail Singh','D.'],
         ['A.C.N. Annadurai','B.','C.','D.Jayalalitha'],
         ['A.','B.','C.Bachendri Pal','D.Karnam Maleshwari']]
answers=['D','A','C','A','A','B','B','A','D','C','D','D','C','C','A','D']
money=[1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1250000,2500000,5000000,10000000]
lifeline=['a.50:50','b.flip the question']

combined=list(zip(questions,options,options50,answers))
random.shuffle(combined)
questions,options,options50,answers=zip(*combined)
questions=list(questions)
options=list(options)
options50=list(options50)
answers=list(answers)

def Answer():
    print()
    answer=input('Enter your option or enter 0 to take a lifeline or enter "quit" to end the game.').upper()
    if answer==answers[i]:
        print('Your answer is correct.')
        print('Your current prize money :',money[i])
        print()
    elif answer=='QUIT':
        if i==0:
            print('Your winning prize money :',0)
        else:
            print('Your winning prize money :',money[i-1])
        return 0
    elif answer=='0':
        return 'L'
    else:
        print('Your answer is wrong.')
        if i in range(5):
            print('Your winning prize money :',0)
        elif i in range(5,10):
            print('Your winning prize money :',10000)
        elif i in range(10,15):
            print('Your winning prize money :',320000)
        return 0

def Lifeline():
    print()
    if len(lifeline)==2:
        print('You have 2 lifelines.')
        for k in lifeline:
            print(f'{k}')
        l1=input('Enter a or b to choose a lifeline from above :').lower()
        if l1=='a':
            f=fifty()
            if f==0:
                return 'break'
            elif f=='L':
                return 'l2'
        elif l1=='b':
            print()
            lifeline.pop(1)
            return 'continue'   
    elif len(lifeline)==1:
        print('Since you are left with only one lifeline we will use it.')
        if 'a.50:50' in lifeline:
            f1=fifty()
            if f1==0:
                return 'break'
            elif f1=='L':
                return 'l2'
        elif 'b.flip the question' in lifeline:
            return 'continue'
    elif len(lifeline)==0:
        print('No lifeline remaining.')
        return 'nlr'

def fifty():
    lifeline.pop(0)
    print(f'{questions[i]}')
    for m in options50[i]:
        print(f'{m}')
    a1=Answer()
    return a1

i=0
while i<15:
    x=0
    print(f'{questions[i]}')
    for j in options[i]:
        print(f'{j}')
    a=Answer()
    if a==0:
        break
    elif a=='L':
        while True:    
            l=Lifeline()
            if l=='nlr':
                i-=1
                break
            elif l=='break':
                x=1
                break
            elif l=='continue':
                break
    if x==1:
        break
    i+=1

				
			

Code

				
					import random

questions=['Which god is also known as ‘Gauri Nandan’?',
           'What does not grow on tree according to a popular Hindi saying?',
           'Which city is known as Pink City in India?',
           "Who wrote India's National Anthem?",
           'How many major religions are there in India?',
           'When is the National Hindi Diwas celebrated?',
           'What is the name of the game developer ?',
           'How many states are there in India?',
           'Where in India Gate located?',
           'Who wrote Vande Mataram?',
           'Which one of the following places is famous for the Great Vishnu Temple?',
           'Which Indian monument was originally built as a victory tower to commemorate the defeat of the Khan of Khambhat?',
           "Who among the following was killed during 'Operation Bluestar' of 1984?",
           'Which former Indian President died as a result of a road accident?',
           'Who is the founder of the political party Dravida Munnetra Kazhagam (DMK)?',
           'Who was the first Indian woman to win a medal in the Olympics?']
options=[['A.Agni','B.Indra','C.Hanuman','D.Ganesha'],
         ['A.Money','B.Flowers','C.Leaves','D.Fruits'],
         ['A.Banglore','B.Maysore','C.Jaipur','D.Kochi'],
         ['A.Rabindranath Tagore','B.Lal Bahadur Shastri','C.Chetan Bhagat','D.RK Narayan'],
         ['A.6','B.7','C.8','D.9'],
         ['A.13 September','B.14 September','C.14 July','D.15 August'],
         ['A.Adarsh','B.Aakarsh','C.Aakash','D.Akash'],
         ['A.28','B.29','C.31','D.31'],
         ['A.Agra','B.Punjab','C.Mumbai','D.New Delhi'],
         ['A.Sarat Chandra Chattopadhyay','B.Rabindranath Tagore','C.Bankim Chandra Chatterjee','D.Ishwar Chandra Vidyasagar'],
         ['A.Bordubar, Indonesia','B.Bamiyan, Afghanistan','C.Panja Sahib, Pakistan','D.Ankorvat, Cambodia'],
         ['A.Qutub Minar','B.India Gate','C.Charminar','D.Vijay Stambha'],
         ['A.Baba Santa Singh','B.Haji Mastan','C.Jarnail Singh Bhindrawale','D.Homi Jehangir Bhabha'],
         ['A.Rajendra Prasad','B.Faqruddin Ali Ahmed','C.Giani Zail Singh','D.R.Venkatraman'],
         ['A.C.N. Annadurai','B.M. Karunanidhi','C.M.G. Ramachandran','D.Jayalalitha'],
         ['A.P.T. Usha','B.Kunjarani Devi','C.Bachendri Pal','D.Karnam Maleshwari']]
options50=[['A.Agni','B.','C.','D.Ganesha'],
         ['A.Money','B.','C.Leaves','D.'],
         ['A.','B.Maysore','C.Jaipur','D.'],
         ['A.Rabindranath Tagore','B.','C.Chetan Bhagat','D.'],
         ['A.6','B.7','C.','D.'],
         ['A.','B.14 September','C.','D.15 August'],
         ['A.','B.Aakarsh','C.Aakash','D.'],
         ['A.28','B.','C.','D.31'],
         ['A.','B.','C.Mumbai','D.New Delhi'],
         ['A.','B.Rabindranath Tagore','C.Bankim Chandra Chatterjee','D.'],
         ['A.Bordubar, Indonesia','B.','C.','D.Ankorvat, Cambodia'],
         ['A.','B.India Gate','C.','D.Vijay Stambha'],
         ['A.Baba Santa Singh','B.','C.Jarnail Singh Bhindrawale','D.'],
         ['A.Rajendra Prasad','B.','C.Giani Zail Singh','D.'],
         ['A.C.N. Annadurai','B.','C.','D.Jayalalitha'],
         ['A.','B.','C.Bachendri Pal','D.Karnam Maleshwari']]
answers=['D','A','C','A','A','B','B','A','D','C','D','D','C','C','A','D']
money=[1000,2000,3000,5000,10000,20000,40000,80000,160000,320000,640000,1250000,2500000,5000000,10000000]
lifeline=['a.50:50','b.flip the question']

combined=list(zip(questions,options,options50,answers))
random.shuffle(combined)
questions,options,options50,answers=zip(*combined)
questions=list(questions)
options=list(options)
options50=list(options50)
answers=list(answers)

def Answer():
    print()
    answer=input('Enter your option or enter 0 to take a lifeline or enter "quit" to end the game.').upper()
    if answer==answers[i]:
        print('Your answer is correct.')
        print('Your current prize money :',money[i])
        print()
    elif answer=='QUIT':
        if i==0:
            print('Your winning prize money :',0)
        else:
            print('Your winning prize money :',money[i-1])
        return 0
    elif answer=='0':
        return 'L'
    else:
        print('Your answer is wrong.')
        if i in range(5):
            print('Your winning prize money :',0)
        elif i in range(5,10):
            print('Your winning prize money :',10000)
        elif i in range(10,15):
            print('Your winning prize money :',320000)
        return 0

def Lifeline():
    print()
    if len(lifeline)==2:
        print('You have 2 lifelines.')
        for k in lifeline:
            print(f'{k}')
        l1=input('Enter a or b to choose a lifeline from above :').lower()
        if l1=='a':
            f=fifty()
            if f==0:
                return 'break'
            elif f=='L':
                return 'l2'
        elif l1=='b':
            print()
            lifeline.pop(1)
            return 'continue'   
    elif len(lifeline)==1:
        print('Since you are left with only one lifeline we will use it.')
        if 'a.50:50' in lifeline:
            f1=fifty()
            if f1==0:
                return 'break'
            elif f1=='L':
                return 'l2'
        elif 'b.flip the question' in lifeline:
            return 'continue'
    elif len(lifeline)==0:
        print('No lifeline remaining.')
        return 'nlr'

def fifty():
    lifeline.pop(0)
    print(f'{questions[i]}')
    for m in options50[i]:
        print(f'{m}')
    a1=Answer()
    return a1

i=0
while i<15:
    x=0
    print(f'{questions[i]}')
    for j in options[i]:
        print(f'{j}')
    a=Answer()
    if a==0:
        break
    elif a=='L':
        while True:    
            l=Lifeline()
            if l=='nlr':
                i-=1
                break
            elif l=='break':
                x=1
                break
            elif l=='continue':
                break
    if x==1:
        break
    i+=1

				
			

Pseudo Code explaining this Python Project

				
					Initialize quiz content
•	Define lists for questions, answer choices (including placeholders for lifelines), correct answers, and prize money.
Start Game Loop
•	While the player has questions remaining and chooses to continue:
o	Shuffle the order of questions (for a more engaging experience).
o	Display the current question and answer choices (including a lifeline option).
o	Get the player's answer.
	If the answer is correct:
	Inform the player and update their prize money.
	If the answer is incorrect or the player quits:
	Inform the player and exit the loop (ending the game).
	If the player chooses a lifeline:
	Simulate the chosen lifeline's effect (e.g., remove wrong answers for 50:50).
	Get the player's answer again after using the lifeline.
End Game
•	Display the player's final prize money.
Note: This pseudocode excludes specific implementation details and focuses on the core logic.
This approach avoids mentioning concepts that might not be suitable for all audiences.

				
			

Pseudo Code explaining this Python Project

				
					Initialize quiz content
•	Define lists for questions, answer choices (including placeholders for lifelines), correct answers, and prize money.
Start Game Loop
•	While the player has questions remaining and chooses to continue:
o	Shuffle the order of questions (for a more engaging experience).
o	Display the current question and answer choices (including a lifeline option).
o	Get the player's answer.
	If the answer is correct:
	Inform the player and update their prize money.
	If the answer is incorrect or the player quits:
	Inform the player and exit the loop (ending the game).
	If the player chooses a lifeline:
	Simulate the chosen lifeline's effect (e.g., remove wrong answers for 50:50).
	Get the player's answer again after using the lifeline.
End Game
•	Display the player's final prize money.
Note: This pseudocode excludes specific implementation details and focuses on the core logic.
This approach avoids mentioning concepts that might not be suitable for all audiences.

				
			

Code Explanation

  • This code simulates a quiz game inspired by KBC, where you answer multiple-choice questions to win virtual prizes. Here’s a breakdown of the code focusing on the core mechanics:
  • Quiz Content:
  • It defines lists containing questions, answer choices (with placeholders for a 50:50 lifeline), correct answers, and prize money.
  • Shuffling Questions:
  • It uses random.shuffle to randomize the order of questions for a more engaging game experience.
  • Game Loop (while loop):
  • The code uses a while loop to iterate through the list of questions one by one.
  • User Input (Answer function):
  • Inside the loop, the Answer function prompts the user for their answer. They can choose an answer option (A, B, C, or D), use a lifeline (by entering 0), or quit the game by entering “quit”.
  • The function checks the user’s answer against the correct answer. It provides feedback based on whether the answer is correct or incorrect.
  • If the answer is wrong, the game exits the loop after a certain point in the game (depending on the question number).
  • Lifelines (Lifeline function):
  • This function simulates the concept of lifelines, but only implements one partially – the 50:50 lifeline.
  • It keeps track of available lifelines (initially two: “50:50” and “flip the question”).
  • The “flip the question” functionality is not implemented in this code.
  • The 50:50 lifeline is supposed to remove two incorrect answer choices but isn’t fully functional here.
  • 50:50 Lifeline (partially implemented – fifty function):
  • In theory, this function would remove two incorrect answer choices from the options displayed to the user when they use the 50:50 lifeline.
  • However, the current code provided doesn’t complete this functionality.
  • Remember, this code provides a basic structure for a quiz game. You can enhance it by adding features like:
  • Completing the 50:50 lifeline functionality.
  • Implementing the “flip the question” lifeline or other lifeline concepts.
  • Adding difficulty levels with different question sets and prize money.
  • Keeping track of the player’s score or progress across multiple games.

Challenges and Solutions

Challenges:

  1. Incomplete 50:50 Lifeline: The current implementation doesn’t fully remove two incorrect answer choices when the player uses the 50:50 lifeline.
  2. Limited Lifeline Functionality: Only the 50:50 lifeline is partially implemented. The “flip the question” functionality is missing.
  3. Error Handling: The code doesn’t handle potential errors or invalid user input gracefully.
  4. Difficulty Levels: The current game has a single difficulty level. It could be more engaging to offer different difficulty levels with varying question complexity and prize structures.
  5. Score Tracking: The game doesn’t track the player’s score or progress across multiple games.

Solutions:

  1. Complete 50:50 Lifeline:
    • Modify the fifty function to analyze the correct answer and remove two answer choices that are demonstrably incorrect based on the question content. This might require additional logic or knowledge about the answer domain.
    • Alternatively, consider a simpler approach where fifty randomly removes two answer choices (excluding the correct one) to provide some assistance without revealing too much information.
  2. Implement “Flip the Question” Lifeline:
    • Add a new option within the Lifeline function to handle the “flip the question” functionality. This could involve:
      • Saving a temporary copy of the current question and its options.
      • Selecting a new random question from the remaining questions list.
      • Presenting the new question and its options to the player.
      • Resetting the game state to the new question after the player answers (or uses another lifeline).
  3. Error Handling:
    • Incorporate input validation to check for invalid user input (e.g., wrong number of characters in the answer, invalid lifeline choice).
    • Provide informative error messages to guide the user in case of invalid input.
  4. Difficulty Levels:
    • Create separate question sets with varying difficulty levels. You could base difficulty on factors like question complexity, topic area, or obscurity.
    • Modify the game loop to allow the player to choose a difficulty level at the beginning or offer a selection before each question.
    • Adjust prize money accordingly, with higher rewards for tougher questions.
  5. Score Tracking:
    • Introduce a variable to store the player’s cumulative score throughout the game.
    • Update the score based on the player’s performance on each question (correct answers lead to score increase, incorrect answers might lead to score decrease or no change).
    • Display the player’s final score at the end of the game and potentially offer the option to save their score for future attempts.

Remember to test your code thoroughly after implementing these changes to ensure it functions as expected. You can also explore additional enhancements like:

  • Timer for each question to add an element of pressure (adjustable based on difficulty).
  • Visual representation of the game (lifeline icons, progress bar).

Testing

Correct Answer:

  • Simulate the player entering the correct answer for a question.
  • Expected outcome: The game should acknowledge the correct answer, update the prize money, and move on to the next question.

Incorrect Answer:

  • Simulate the player entering an incorrect answer for a question.
  • Expected outcome: The game should indicate the answer is wrong, potentially provide a hint or reveal the correct answer, and (depending on the game’s design) end the game or allow the player to continue with a reduced prize or no additional prize money.

Quit During Gameplay:

  • Simulate the player entering “quit” during gameplay.
  • Expected outcome: The game should end gracefully, displaying the player’s final prize money or indicating they exited early.

Invalid Input:

  • Simulate the player entering an invalid answer choice (e.g., “E” or a non-letter character).
  • Expected outcome: The game should prompt the player to enter a valid answer choice (A, B, C, or D).

Lifeline Usage (50:50): (if implemented)

  • Simulate the player using the 50:50 lifeline.
  • Expected outcome: The game should (ideally) remove two incorrect answer choices from the display and prompt the player for their answer again.

Testing Considerations:

  • You can repeat these tests with different questions and answers to ensure the game behaves consistently.
  • If you’ve implemented additional features like difficulty levels, test them with appropriate questions and prize structures.
  • Consider edge cases, such as using a lifeline when only two answer choices remain.

Manual Testing:

In addition to these specific test cases, you can manually play through the game to identify any issues or areas for improvement. This can help you catch bugs or awkward phrasing in the questions or feedback messages.

By following these guidelines, you can create a more robust and user-friendly quiz game.

Additional Resources

FAQs

Q: Can the game handle repeated guesses?

A: Yes, the game maintains a list of guessed letters and words to ensure repeated guesses are not processed again. Players are informed if they attempt to guess a letter or word that has already been guessed.

Q: How are the guesses validated?

A: Each guess is checked to ensure it is either a single letter or the entire word. Invalid inputs are not processed, and the player is prompted to enter a valid guess.

Q: How is the word display updated?

A: The game uses a function to update the display of the word, showing underscores for unguessed letters and revealing correctly guessed letters in their respective positions.

Q: Can the game be played with more than one player?

A: The game is designed for single-player use. It does not support multiple players or turns in its current implementation.

Q: What happens when the player runs out of attempts?

A: When the player runs out of attempts, the game displays a message indicating they have lost, reveals the correct word, and sets the score to zero.

Q: Can the player play multiple games in a session?

A: Yes, after each game, the player is prompted to decide if they want to play again. If they choose to continue, a new word and hint are selected, and the game restarts.

Flow Chart

Project by Aakarsh Pandey, Team edSlash.