Question

Hello I need help with python programming here is my code # Trivia Challenge # Trivia...

Hello I need help with python programming here is my code

# Trivia Challenge
# Trivia game that reads a plain text file

import sys


def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file


def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line


def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)

question = next_line(the_file)

answers = []
for i in range(4):
answers.append(next_line(the_file))

correct = next_line(the_file)
if correct:
correct = correct[0]

explanation = next_line(the_file)

return category, question, answers, correct, explanation


def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")


def main():
trivia_file = open_file("D:/trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
question_marks = 1

# get first block
category, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])

# get answer
answer = input("What's your answer?: ")

# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(trivia_file)

trivia_file.close()

print("That was the last question!")
print("You're final score is", score)


main()
input("\n\nPress the enter key to exit.")

Text file

An Episode You Can't Refuse
On the Run With a Mammal
Let's say you turn state's evidence and need to "get on the lamb." If you wait /too long, what will happen?
You'll end up on the sheep
You'll end up on the cow
You'll end up on the goat
You'll end up on the emu
1
A lamb is just a young sheep.
The Godfather Will Get Down With You Now
Let's say you have an audience with the Godfather of Soul. How would it be /smart to address him?
Mr. Richard
Mr. Domino
Mr. Brown
Mr. Checker
3
James Brown is the Godfather of Soul.

The code is to display welcome to Trivia challenge

An episode you can't refuse

let's say you turn state's evidence and need to get to the lamb. If you wait too long what will happen?

1 you'll end up on the sheep

2 you'll end up on the cow

3 you'll end up on the goat

4 you'll end up on the emu

what's your answer

The answer is supposed to be the first one you'll end up on the sheep

0 0
Add a comment Improve this question Transcribed image text
Answer #1

<<<<<<<<<<<<<<<<<<<<keep track of identation>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<identaed code screenshot>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>sample o/p<<<<<<<<<<<<<<<

sample output 2:

<<<<<<<<<<<<<<<<<<<<<<<<<<python code>>>>>>>>>>>>>>>>>>>>>

def open_file(file_name, mode):

    """Open a file."""

    import sys

    try:

        the_file = open(file_name, mode)

    except IOError as e:

        print("Unable to open the file", file_name, "Ending program.\n", e)

        input("\n\nPress the enter key to exit.")

        sys.exit()

    else:

        return the_file

def next_line(the_file):

    """Return next line from the trivia file, formatted."""

    line = the_file.readline()

    line = line.replace("/", "\n")

    return line

def next_block(the_file):

    """Return the next block of data from the trivia file."""

    category = next_line(the_file)

    question = next_line(the_file)

    answers = []

    for i in range(4):

        answers.append(next_line(the_file))

    correct = next_line(the_file)

    if correct:

        correct = correct[0]

    explanation = next_line(the_file)

    return category, question, answers, correct, explanation

def welcome(title):

    """Welcome the player and get his/her name."""

    print("\t\tWelcome to Trivia Challenge!\n")

    print("\t\t", title, "\n")

def main():

    trivia_file = open_file("trivia.txt", "r")

    title = next_line(trivia_file)

    welcome(title)

    score = 0

    question_marks = 1

    # get first block

    category, question, answers, correct, explanation = next_block(trivia_file)

    while category:

        # ask a question

        print(category)

        print(question)

        for i in range(4):

            print("\t", i + 1, "-", answers[i])

        # get answer

        answer = input("What's your answer?: ")

        # check answer

        if answer == correct:

            print("\nRight!", end=" ")

            score += 1

        else:

            print("\nWrong.", end=" ")

            print(explanation)

            print("Score:", score, "\n\n")

            # get next block

        category, question, answers, correct, explanation = next_block(trivia_file)

    trivia_file.close()

    print("That was the last question!")

    print("You're final score is", score)

main()

input("\n\nPress the enter key to exit.")

<<<<<<<<<<<<<<<<<<<<keep track of identation>>>>>>>>>>>>>>>>>>>>>>>>>

text file structure

Add a comment
Know the answer?
Add Answer to:
Hello I need help with python programming here is my code # Trivia Challenge # Trivia...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Starting out with Python 4th edition I need help I followed a tutorial and have messed...

    Starting out with Python 4th edition I need help I followed a tutorial and have messed up also how does one include IOError and IndexError exception handling? I'm getting errors: Traceback (most recent call last): File, line 42, in <module> main() File , line 37, in main winning_times = years_won(user_winning_team_name, winning_teams_list) File , line 17, in years_won for winning_team_Index in range(len(list_of_teams)): TypeError: object of type '_io.TextIOWrapper' has no len() Write program champions.py to solve problem 7.10. Include IOError and IndexError...

  • Python Problem Hello i am trying to finish this code it does not save guesses or...

    Python Problem Hello i am trying to finish this code it does not save guesses or count wrong guesses. When printing hman it needs to only show _ and letters together. For example if the word is amazing and guess=a it must print a_a_ _ _ _ not a_ _ _ _ and _a_ _ _ separately or with spaces. The guess has a maximum of 8 wrong guesses so for every wrong guess the game must count it if...

  • I need help in Python. This is a two step problem So I have the code...

    I need help in Python. This is a two step problem So I have the code down, but I am missing some requirements that I am stuck on. Also, I need help verifying the problem is correct.:) 7. Random Number File Writer Write a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 500. The application should let the user specify how many random numbers the file...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • Python, given a code in class i just need help with the third bullet point ; using a and n (defin...

    Python, given a code in class i just need help with the third bullet point ; using a and n (defined in the second picture of python code) find the first digit for k! for k =1,...,n. you dont have to type in all this code just help me write the code in the first picture where it says: def benford(a): b = [0 for d in range(1,10)] #Do everthything in here return b 2.2 Generating data In this assignment...

  • Hello Ive been tryting to add the CDN of jquery to my html code and I...

    Hello Ive been tryting to add the CDN of jquery to my html code and I keep getting an error Need help with this : ​​ Navigate to www.code.jquery.com in your Chrome browser. On this page, you'll find different stable versions of jQuery. Select uncompressed for jQuery Core 3.3.1. Copy the <script> tag that is given to you. In store_hours.html, paste that tag directly above your body's closing tag. This is the jQuery CDN. After you paste this code into...

  • Python Programming (Just need the Code) Index.py #Python 3.0 import re import os import collections import...

    Python Programming (Just need the Code) Index.py #Python 3.0 import re import os import collections import time #import other modules as needed class index:    def __init__(self,path):    def buildIndex(self):        #function to read documents from collection, tokenize and build the index with tokens        # implement additional functionality to support methods 1 - 4        #use unique document integer IDs    def exact_query(self, query_terms, k):    #function for exact top K retrieval (method 1)    #Returns...

  • Could anyone help add to my python code? I now need to calculate the mean and...

    Could anyone help add to my python code? I now need to calculate the mean and median. In this programming assignment you are to extend the program you wrote for Number Stats to determine the median and mode of the numbers read from the file. You are to create a program called numstat2.py that reads a series of integer numbers from a file and determines and displays the following: The name of the file. The sum of the numbers. The...

  • *PYTHON * Help, it say's indention error, what should the fixed indention in the code look...

    *PYTHON * Help, it say's indention error, what should the fixed indention in the code look like? main.py saved import random 2 import time Python 3.6.8 (default, Jun 11 2019, 01:21:42) [GCC 6.3.0 20170516] on linux File "main.py", line 42 scene10 IndentationError: expected an indented block def scene1(): print("It's 1 am, you're laying in bed drifting off to sleep when you notice your lamp went out") time. sleep (5) print("You get up to investigate, as you know that light bulb...

  • PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything...

    PYTHON 3 Object Oriented Programming ***a9q3.py file below*** class GradeItem(object): # A Grade Item is anything a course uses in a grading scheme, # like a test or an assignment. It has a score, which is assessed by # an instructor, and a maximum value, set by the instructor, and a weight, # which defines how much the item counts towards a final grade. def __init__(self, weight, scored=None, out_of=None): """ Purpose: Initialize the GradeItem object. Preconditions: :param weight: the weight...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT