Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How to Randomize the Lines Read from a TXT file for a Python States Quiz Program? Right now this program simply pulls the first line,

How to Randomize the Lines Read from a TXT file for a Python States Quiz Program?

Right now this program simply pulls the first line, the next line, etc. It always starts with Delaware, then Pennsylvannia, then New Jersey, and so on. I need it to pull random lines based on the user input. So if a user chooses 5 questions to be asked, the program should pick five states at random so the user can answer.

The current code is shown below. It needs to be modified to pull random lines from the text file.

************************

import random

def exit_function(): print("The game will now exit.") exit()

def game_over(): print("Thank you for playing!") exit_function() #Call the exit function

def game(): questions = int(input("Enter the number of questions you want to answer (1-50) : ")) score = 0 #Open the text file in read mode fileRead = open("StateCapitals.txt",'r') #Loop through the text file line by line for i in range(0,questions): print("Question " + str(i+1) +":") line = fileRead.readline() #Read a single line arrayLine = [] #Create an array arrayLine = line.split(",") #Split by the character which separated the state with the capital #Receive answer input answer = input("What is the capital of " +arrayLine[0] + ": ? ") #Compare the two strings by converting to the same case and stripping off whitespace if str(arrayLine[1].strip().lower()) == str(answer.strip().lower()): print("Correct!") score +=1 #Increment score else: print("Incorrect.") print("The correct answer is: "+arrayLine[1].lower()) print("Score = " + str(score) + " out of " +str(questions)) #this would be ratio of score vs questions !!! game() #Call the game function play_again = input("Do you want to play again? (Y/N):" ) #Prompt user to play again if play_again=='Y': game() #Call the game function again else: game_over() #Else game over is called

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Advanced MySQL 8 Discover The Full Potential Of MySQL And Ensure High Performance Of Your Database

Authors: Eric Vanier ,Birju Shah ,Tejaswi Malepati

1st Edition

1788834445, 978-1788834445

More Books

Students also viewed these Databases questions