I'm Having Trouble checking two values are equal in python - python

finishgame = "n"
counter = 0
#the song randomizer
num = random.randint(0,50)
f = open("songs.txt","r")
lines = f.readlines()
#first letter only system
song = str(lines[num])
firstl = song[0]
print(firstl)
#the artist generator
g = open("artists.txt","r")
line = g.readlines()
print(line[num])
#guess system
while finishgame == "n":
guess = str(input("Enter your guess"))
if guess == song:
counter = counter+5
print("Correct!")
finishgame = "y"
elif counter == 2:
print("Out of guesses, sorry :(")
print("The Correct Answer was:",song)
finishgame = "y"
else:
counter = counter+1
print("Try Again")
First time asking so apologizes for any errors. I have create a song guessing game where it takes a song from an external file, and displays the first letter of the title. It then takes the artist from a separate file (where it is in the same line as the song in the other file) and displays that too. Then you should guess the song. However, my code is having trouble recognizing when a 'guess' is correct, please can anyone tell me why? I've tried using different methods of identification such as the id() function but so far have not got any results. I'm probably missing something simple but any help would be much appreciated.

Related

Hello. I am coding a music quiz game in Python. Correct answers are not authenticated, and I have no idea why

My music quiz game takes a list of songs from an external file named 'Songs.txt' and takes the first letter of each word in one song (out of 7, picked randomly) and then displays the artist of that song. The user then has two guesses, and the appropriate points are then awarded:
# MUSIC QUIZ GAME
import random
# Import the 'random' function in order to select a random number and get a random song.
import time
# Importing the ability to 'pause' to give the program a more professional feel.
import sys
# Import the ability to close the program.
import linecache
# Import the ability to get a specific line from a file.
userscore = 0
# The userscore is automatically zero, because they have just started playing.
random_picker = random.randint(1,7)
# Using the random operator, we pick a random number from 1 to 5, because there are 5 songs. We will use this to select the same random line from two files.
# ----- Accessing the Songs database ----- #
# Open the file.
file = open("Songs.txt", "r")
# Get the line from file. The line number is determined by the 'random_picker' used earlier.
song = linecache.getline(r"Songs.txt", random_picker).upper()
# Split the line into individual words.
song_prompt = song.split()
# ----- Accessing the Artists database ----- #
file = open("Artists.txt", "r")
artist = linecache.getline(r"Artists.txt", random_picker)
# -----Giving the user the prompt ----- #
print("\nYour prompt is: ")
# Get only the first letter of each word in the prompt, then output them.
for word in song_prompt:
print(word[0])
print("by " + artist)
guess1 = input("Enter your song name guess:\n")
if guess1 == song:
print("Well done!")
userscore = userscore + 3
print("Your score is " + str(userscore) + ".")
elif guess1 != song:
print("Wrong guess.")
guess2 = input("What is your second guess for the song name?\n")
if guess2 == song:
print("Well done.")
userscore = userscore + 1
print("Your score is " + str(userscore) + ".")
else:
print("You have gotten both guesses wrong.")
sys.exit()
However, on both guesses, with the right song, uppercase, lowercase, capitilised titles, etc, the software always deems the answer wrong. Is it to do with the way the file is read? I'm not quite sure. If anyone could help me with this issue, that would be much appreciated.
The 'Songs.txt' file contains this list:
Let It Happen
New Gold
Shotgun
Metamodernity
Bad Guy
Blank Space
Bohemian Rhapsody
The 'Artists.txt' file contains this list:
Tame Impala
Gorillaz
George Ezra
Vansire
Billie Eillish
Taylor Swift
Queen
For example, the quiz says:
Your prompt is:
N
G
by Gorillaz
Enter your song name guess:
New Gold
Wrong guess.
What is your second guess for the song name?
NEW GOLD
You have gotten both guesses wrong.
I am expecting to get the correct answer.
I think you might also have an issue with the way you read the .txt files.
When you run the following line: song = linecache.getline(r"Songs.txt", random_picker).upper()
The value assigned to song will be something like 'LET IT HAPPEN\n'
In order to avoid this you can use the .rstrip() method:
song = linecache.getline(r"Songs.txt", random_picker).upper().rstrip('\n')

Python code randomly stops, why? (This is for a quiz game)

The following code randomly stops where mentioned in the code.
def playSaved(choiceSaved):
y = open(choiceSaved,'r')
for line in y.readlines():
qna = line.split(" : ")
randQues.append(qna[0])
randAns.append(qna[1])
print("Processing game.....")
time.sleep(2)
savedChoice = input("\nOk! Are you ready to play? (Y/N) ")
# the code stops here, after getting the input
if savedChoice.lower() == 'y':
for num in range(len(y.readlines())):
count = 1
if "?" in randQues[num]:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
else:
ansForSaved = input(f"Question {count}:\n{randQues[num]}\n> ")
if ansForSaved == randAns[num]:
print("Correct!")
else:
print("Wrong!")
I tried looking online, but didn't find anything. I figured i could ask here
it reads the line from a text file and the first part is a question the second part is the answer i want to check if the answer input by user matches the answer based on the txt file
some sample data:
name : jd
country : finland
age : 23
colour: red
The for loop:
for num in range(len(y.readlines()))
...will never be entered because the file contents have already been consumed.
Change to:
for num in range(len(randQues))

why does my hangman code keep coming back with an error saying " IndexError: list index out of range"

here is my code
my assignment is to create a hangman game that picks word from an outside text file, pick a word, close the file, then start the game. I think the problem is with opening the text file. I'm not sure if I'm saving it in the right spot or whatever. pls help.
import random
#extract a random word from a text file
def word_selected(fname):
word_file = open('hangman list.txt','r+')
secret_word = random.choice(word_file.read().split())
word_file.close()
return secret_word
secret_word = word_selected('hangman list.txt')
print(secret_word)
#Display randomly chosen word in dash:
def word_selected_dashed():
word_selected_dashed = []
for i in range(len(secret_word)):
word_selected_dashed.append('_')
return ''.join(word_selected_dashed)
word_selected_dashed = word_selected_dashed()
print(word_selected_dashed)
trials = 5
gussed_word = list(word_selected_dashed)
while trials > 0:
if ''.join(gussed_word) == secret_word:
print("Congraluation, you have gussed the correct word")
break
print('you have got '+ str(trials)+ ' wrong tries ')
user_guseed_letter = input('Guess a letter >>>>> \n')
if user_guseed_letter in secret_word:
print('Correct!')
for i in range(len(secret_word)):
if list(secret_word)[i] == user_guseed_letter:
gussed_word[i] = user_guseed_letter
print(''.join(gussed_word))
elif user_guseed_letter not in secret_word:
print('wrong!')
trials -= 1
hang = display_hangman(tries=(5-trials))
print(hang)
if trials == 0 :
print('you have ran out of trials')
One issue I notice is in the word_selected function, you have an input of fname, then use a specific file name within the function. Instead of writing out the actual file name, use the variable you used in the function name (ie fname).
Also, make sure the file is in the same directory (folder) of your Python file. If its in a different directory, you can also specify the whole file path as the file name.

I get very strange error while im trying to finish my project

This code is meant to pick an artist from internal file (text file), read it and pick randomly from the internal file the artist (that are in the text file in array style, e.g., "carrot apple banana"), therefore I added .txt to the chosen artist so the program will open artist's file with songs and pick a random song.
import random
loop = False
counter = 0
points = 0
max_level = 10
while loop == False:
for lines in open("pick.txt").readlines():
art = lines.split()
artist = random.choice(art)
for i in open((artist) + ".txt"):
song = i.split()
song_name = random.choice(song)
print("the song begins with :" , song_name , "this song is by :" , artist)
answer = input("Enter full name of the song : ")
if answer == song_name:
points = points +3
print("correct")
counter = counter +1
print(counter)
elif answer != song_name:
print("WRONG !!! \n try again")
dec = input("Please enter the full name of the song :")
if dec == song_name:
points = points +2
print("correct")
counter = counter +1
print(counter)
elif dec != song_name:
print("smh \n WRONG")
counter = counter +1
print(counter)
elif counter >= max_level:
print("The End")
quit()
else:
print("error")
input()
Afterwards when I run the code in python shell, there is a random chance that I get this error, either straight away or later on:
raise IndexError('Cannot choose from an empty sequence') from None
IndexError: Cannot choose from an empty sequence
That error is from the random module by the looks of it. This is probably when you’re reading the file and there is a line that is blank.
A cause is usually the last line of the file which is often a blank newline/EOF.
Just add a check when reading your file(s):
for line in open(artist + '.txt', 'r'):
if line.strip():
song = line.strip().split()
song_name = random.choice(song)
An empty line will have a ‘truthiness’ value of 0 or False so a line with content returnsTrue.
Your error probably arises from an empty line in one of your text-files.
I was able to duplicate your error with your exact code and the following text-files:
pick.txt with only the word adele,
and adele.txt with hello-from-the-other-side and two new lines.
You can test this in prelude:
>>> for i in open("adele.txt"):
... song = i.split()
...
>>> song
[]
On another note, you seem to be iterating throughout the lines in a textfile before you do anything with the data in the lines. That can't possibly make sense. I would advice you to add things in a list as you go, and then select from this list instead.

Python - Word Scramble Game

While this assignment is past due (I joined the class late unfortunately) I still need to figure it out. I have the following list of words:
abhor:hate
bigot:narrow-minded, prejudiced person
counterfeit:fake; false
enfranchise:give voting rights
hamper:hinder; obstruct
kindle:to start a fire
noxious:harmful; poisonous; lethal
placid:calm; peaceful
remuneration:payment for work done
talisman:lucky charm
abrasive:rough; coarse; harsh
bilk:cheat; defraud
I need to read this file into a dictionary, pick a random key, scramble it, then ask the user to solve it. Unlike other solutions on here, it does not iterate three times, but runs until the user enters 'n'. The code will ask the user after each round if the user wants to continue the game. The user can also type 'hint' to get the definition of the word.
There is a similar question here: (http://www.dreamincode.net/forums/topic/302146-python-school-project-write-a-word-scramble-game-status-complete/) or rather the result of a question, but I am not knowledgeable enough to bridge the gaps and make it work for my purposes. None of the variation on this that I have seen on stack overflow come close enough for me to bridge the gap either, likely because I just don't know enough yet. Before we even start, this code does not yet work at all really, I am pretty lost at this point, so please be gentle. My code so far is below:
import random
from random import shuffle
#Reads the words.txt file into a dictionary with keys and definitions
myfile = open("words.txt", "r")
wordDict = dict([(line[:line.index(":")], line[line.index(":") +1 : -1])
for line in myfile.readlines()])
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = random.choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
hint = wordDict[wordKey]
return hint
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter your first guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
def scramble():
theList = list(shuffle_word())
random.shuffle(theList)
return(''.join(theList))
#Main Program
if keepPlaying() == 'y':
intro()
shuffle_word()
randomW = shuffle_word()
#scramKey = list(randomW)
thisWord = scramble()
print ("\nThe scrambled word is " +thisWord)
solution = getAnswer()
if solution == thisWord:
print("\nCongratulations")
if solution == 'Hint' or solution == 'hint':
myHint = giveHint(wordKey)
print(myHint)
else:
print("\nThanks for playing")
I have edited this post to ask for new information, though I am not sure if that ishow its properly done. Thanks to the help of those below, I have made progress, but am stuck not on a specific piece.
I have two questions. 1: How can I get the giveHint() function to return the definition of the random key selected by the shuffle_wprd() function. I know what I have above will not work because it is simply returning a string, but it seems like just using a dict.get() function would not get the correct definition for the random word chosen.
2: How can I get the program not to ask the user to continue on the first pass, but to then ask from then on. I thought about using a while loop and redefining the variable during the iteration, but I don't know enough to get it to work properly.
regardless, thank you to those people who have already helped me.
This should help you out a bit, the length seems to be of no benefit as a hint as you can see the length of the scrambled word so I used the definition as the hint,I think you also want to ask the user to guess the word not individual letters:
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
word_dict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
word_dict[word] = hint
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
#Picks a random key from the dictionary b
def pick_word():
word = choice(list(word_dict.keys()))
return word
#Gives a hint to the user
def give_hint(word):
# return the definition of the word
descrip = word_dict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def get_answer():
while True:
answer = input('Please enter a guess: ')
if answer.isalpha():
return answer
else:
print("Only letters in the word")
def main():
intro()
word = pick_word()
# give user lives/tries
tries = 3
shffled_word = list(word)
# shuffle the word
shuffle(shffled_word)
# rejoin shuffled word
shffled_word = "".join(shffled_word)
# keep going for three tries as most
while tries > 0:
inp = input("Your scrambled word is {}\nEnter h if you want to see your hint or any key to continue".format(shffled_word))
if inp == "h":
print("The word definition is {}".format(give_hint(word)))
ans = get_answer()
if ans == word:
print("Congratulations you win!")
break
tries -= 1
# ask user if they want to play again, restarting main if they do
play_again = input("Press 'y' to play again or any key to exit")
if play_again == "y":
main()
# else the user did not press y so say goodbye
print("Goodbye")
main()
There are a few more bits to be added but I will leave that up to you.
Thank you to all those who helped. For any who come along later, the final product is here. Similar to what Padraic Cunningham put, but without the three answer limit, and without his more elegant solution of wrapping the main program into a called function.
import random
from random import shuffle, choice
#Reads the words.txt file into a dictionary with keys and definitions
with open("words.txt") as f:
wordDict = {}
for line in f:
# split into two parts, word and description
word, hint = line.split(":")
wordDict[word] = hint
#print (b)
def intro():
print('Welcome to the scramble game\n')
print('I will show you a scrambled word, and you will have to guess the word\n')
print('If you need a hint, type "Hint"\n')
#Picks a random key from the dictionary b
def shuffle_word():
wordKey = choice(list(wordDict.keys()))
return wordKey
#Gives a hint to the user
def giveHint(wordKey):
descrip = wordDict[word]
return descrip
#Below - Retrieves answer from user, rejects it if the answer is not alpha
def getAnswer():
answer = input('\nEnter a guess: ')
while True:
if answer.isalpha():
return answer
else:
answer = input('\nPlease enter a letter: ')
def getAnswer2():
answer2 = input('\nEnter another guess: ')
while True:
if answer2.isalpha():
return answer2
else:
answer2 = input('\nPlease enter a letter: ')
def keepPlaying():
iContinue = input("\nWould you like to continue? ")
return iContinue
#def scramble():
# theList = list(shuffle_word())
# random.shuffle(theList)
# return(''.join(theList))
#Main Program
while keepPlaying() == 'y':
intro()
#shuffle_word()
randomW = shuffle_word()
cheatCode = giveHint(randomW)
#scramKey = list(randomW)
thisWord = list(randomW)
print(thisWord)
random.shuffle(thisWord)
print(thisWord)
thisRWord = ''.join(thisWord)
print ("\nThe scrambled word is " +thisRWord)
solution = getAnswer()
loopMe = False
while loopMe == False:
if solution == randomW:
print("\nCongratulations")
loopMe = True
if solution == 'Hint' or solution == 'hint':
print(cheatCode)
if solution != randomW:
loopMe = False
solution = getAnswer2()

Categories

Resources