Python Forum
Read from a file, get user input in a while loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read from a file, get user input in a while loop
#1
Below is the code i have created for a music quiz game, firstly i need to know how to print the first letter of each song, and fix the while statement :)


--------------------------------------------------------------------
import random
songs = []
f = open("Songs.txt", "r")
wrong = 0
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())
songs.append(f.readline())

counter = 0
while counter <= 9:
    print(random.choice(songs))
    answer = input("Guess the song!")
    if answer == songs[counter]:
        print("Correct")
        counter += 1
    else:
        print("Incorrect")
        wrong +=  1
-----------------------------------------------------------
P.S These are the songs in my external file:
Output:
New_Patek_Lil_Uzi_Vert Despacito_Luis_Fonsi Rap_Devil_MGK Killshot_Eminem Lucky_You_Eminem_&_Joyner_Lucas Maskoff_Future Rockstar_Post_Malone I_Love_It_Kanye_West_&_Lil_Pump Its_Everyday_Bro_Jake_Paul Venom_Eminem
^------- these are correct, please do not change, it just needs to print the first letter, not the whole line :)

Thanks,
Lynden
Reply
#2
To get the first character of a string, you just use an index: text[0].

I think you want your while loop to be while counter + wrong < 9:. If that doesn't work, please clarify what is wrong with the while loop.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I tried your loop and the problem is still the same, I answer the song correctly, for example Maskoff_Future. I type that it for an input and it still comes up as wrong :) p.s im new to this forum so sorry if the tags are wrong.
Reply
#4
The problem is in this if condition if answer == songs[counter]:.
Let's see what will happen when counter = 0 (i.e., first question/answer)
on line 18 you will print a randomly selected song from the list. It could be any song of the list, e.g. let's say it is the third one. Here you want to print just the first letter I guess, but anyway. You also need to save this randomly selected song to a variable in order to be able to check user answer. Instead you compare the user answer with the first song in the list (i.e. the one with index 0). Even if you answered correctly if condition will be False. In next iteration of the loop counter will still be 0 and you will compare user input with the first song in the list. But randomly selected song would be different.

There are other problems in your code and logic
repetitive code when you read line by line from the file
there are better ways to open file, e.g. using with context manager
as it is now it's possible to get same song many times (i.e. ask same question multiple times)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Thanks alot, I'm really new to coding so how do you write this? Thanks for helping
Reply
#6
Two more issues:
when reading song names from the file you will get extra new line character at the end of the string, so you need to strip that '\n' char or your answer and the song name will not match
counter - you use counter to hold number of correct answers. yet it is part of the while condition. Do you really want to loop until you get 9 correct answers?

not tested but something like this
import random

with open("Songs.txt", "r") as f:
    songs = []
    for line in f:
        songs.append(line.strip())
    # you can replace last 3 lines with single line as follows
    #songs = [line.strip() for line in f]
        
random.shuffle(songs) # randomize songs list
correct = 0 
wrong = 0
# you can replace last 2 lines with single line as follows
#correct, wrong = 0, 0
        
while songs:
    song = songs.pop() # get one song and remove it from the list
    answer = input("Guess the song!\n{}\n>> ".format(song[0])
    if answer == song:
        print("Correct")
        correct += 1
    else:
        print("Incorrect. It was {}".format(song))
        wrong += 1
print('correct: {}, wrong: {}'.format(correct, wrong)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Thank you, but it is coming up with a syntax error on line 19 (the bracket) and I've tried to make it better but it keeps coming up as wrong.

Thanks for helping a newbie :)
Reply
#8
(Nov-04-2018, 02:14 PM)lynden Wrote: Thank you, but it is coming up with a syntax error on line 19 (the bracket) and I've tried to make it better but it keeps coming up as wrong.
Sorry, my mistake - there is missing closing parenthesis on line 18
answer = input("Guess the song!\n{}\n>> ".format(song[0]))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#9
import random

with open("Songs.txt", "r") as f:
    songs = []
    for line in f:
        songs.append(line.strip())

         
random.shuffle(songs) 
correct = 0 
wrong = 0

         
while songs:
    song = songs.pop()
    guess = input("Guess the song!\n{}\n>> ".format(song[0]))
    if guess == song:
        print("Correct")
        correct += 1
    else:
        print("Incorrect. It was {}".format(song))
        wrong += 1
print("correct: {}, wrong: {}".format(correct, wrong))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with to check an Input list data with a data read from an external source sacharyya 3 402 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  Recommended way to read/create PDF file? Winfried 3 2,867 Nov-26-2023, 07:51 AM
Last Post: Pedroski55
  python Read each xlsx file and write it into csv with pipe delimiter mg24 4 1,427 Nov-09-2023, 10:56 AM
Last Post: mg24
  WHILE LOOP NOT RETURNING USER INPUT AFTER ZerroDivisionError! HELP! ayodele_martins1 7 1,053 Oct-01-2023, 07:36 PM
Last Post: ayodele_martins1
  read file txt on my pc to telegram bot api Tupa 0 1,105 Jul-06-2023, 01:52 AM
Last Post: Tupa
  parse/read from file seperated by dots giovanne 5 1,105 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Formatting a date time string read from a csv file DosAtPython 5 1,251 Jun-19-2023, 02:12 PM
Last Post: DosAtPython
  How do I read and write a binary file in Python? blackears 6 6,499 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  restrict user input to numerical values MCL169 2 907 Apr-08-2023, 05:40 PM
Last Post: MCL169
  Read csv file with inconsistent delimiter gracenz 2 1,192 Mar-27-2023, 08:59 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020