I am doing a project in school which is asking me to make a music quiz in python that reads a file, displays the first letters of each word of the song and the artist (e.g Dave F F). In my file I have a list of 10 song names where python fetches a random line and does the displaying. It must be from a file (mine is notepad) The user must have 2 chances to guess the name of the song, and if they don't then the game ends. The problem that I have is I cannot get my code to ask another question, and store the last one asked so that it doesn't ask it again (e.g if the first question is Dave and F F, I want it to not come again). I would also appreciate it if I was shown how to get python to display a leaderboard. Could answers please be the full code with improvements as i'm not good with indents and putting code In the right place.
I have already gave the user 2 chances to get the song right, and If they dont then the program ends, but doesn't loop to the start.
import random
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1
finished = False
while not finished:
answer_found = (guess == random_song)
if not answer_found:
guess = input("Nope! Try again! ")
nb_tries_left -= 1
elif answer_found:
print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)
finished = (answer_found or nb_tries_left <= 0)
if answer_found:
The songs' initials are LT and the name of the artist is Fredo
Guess the name of the song! Like That
The songs' initials are LT and the name of the artist is Fredo
Well done!
Python then doesn't ask another question, and I don't know If it will be that one again.
getting it wrong on purpose outputs this:
The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>>
First You want to get 2 unique songs. To do that you could use random.sample. For your use case, It is
indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]
Additionally, I recommend you to put your code to the function and use it with each selected song.
In order to ask more than one question every game you have to do something like this:
with open("songlist.txt", "r") as songs_file:
with open("artistlist.txt", "r") as artists_file:
songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
for (song, artist) in zip(songs_file, artists_file)]
def getSongAndArtist():
randomIndex = random.randrange(0, len(songs_and_artists))
return songs_and_artists.pop(randomIndex)
while(len(songs_and_artists) > 0):
random_song, random_artist = getSongAndArtist()
#play game with the song
You save the list of songs in a python list and pop a random one out each round as long as you have more songs to play with.
For the leaderboard you have to ask for a user name before you start the game and save a list of usernames and their score and then pick the top ones. you should also figure out how to score the users
Related
I'm creating a quiz for my GCSE where a person is given the musical and the first letters of the song, they then must guess the entire song. The part I'm having trouble with is that even though I get the question right, it is telling me I am wrong. I'm also using a CSV file to store the questions and answers.
I have tried changing the variable many, many times and I'm really not sure what else to do. Currently the loop is still open, but the code is not finished yet and I cannot move on until I've done this.
while fail!= True:
randomN = random.randint(0, totalQu - 1)
musical = questions[randomN][0]
title = questions[randomN][1]
title_split = title.split()
new = []
for title in title_split:
letter=title[0].upper()
new.append(letter)
ans=" ".join(new)
print(musical+",",ans)
answer = input()
if answer == title:
print("That is CORRECT")
score = score + 3
elif answer != title:
print("That is INCORRECT. Try again")
If the question is "Dear Evan Hansen, F F" then the answer is "For Forever" but if I input this it tells me I am wrong. The variable 'title' is for some reason, only the first word? For example, in this case it would be "Forever".
I was wondering if someone can point me in the right direction of a basic script.
This is for a game I created and wanted to create a countdown script to go along with it.
I want be able to have 4 users in which the program will first will ask for their name. After that each user will take turns entering their score starting at 100 and decreasing based on their input. Once they hit zero they win. Once the first person hits 0 the others will have a chance to as well until the end of the round. Each 4 inputs will be considered 1 round.
There will be a lot more to the game but I just need the start. I am new to Python but the easiest way for me to learn is to start off on a working script
Thanks!
Are you looking for something like this?
import cmd
number_users = 4
number_rounds = 10 # or whatever
user_names = [None]*number_users
user_scores = [None]*number_users
for i in range(number_users):
print("Enter name for user #{}: ".format(i+1))
user_names[i] = input()
user_scores[i] = 100
for round_number in range(number_rounds):
print(" --- ROUND {} ---".format(round_number+1))
for i in range(number_users):
print("{}, Enter your score: ".format(user_names[i]))
user_scores[i] = input()
print("--- Scores for Round {} ---".format(round_number+1))
for i in range(number_users):
print("{} : {}".format(user_names[i], user_scores[i]))
print("Done")
-------Answered, turns out I was doing the right thing, but had a different error that made me think it was the wrong thing to do------------------
Alright, so I know this is super simple but I am really confused as to how to take a user input as a number and use that number to index from a list with that number.
So what I am trying to do is this:
Enter your choice: (User enters a 1)
You choose 1.
Which sentence? (User enters a 0 or whatever number they want within the bounds of how many sentences they enter)
I then just want to use their inputted number and index that from the list.
So if they entered these two sentences for their list:
good
bad
Then when they ask which sentence, and say 1, I want to index sentenceList[1] and print it back to them.
But this needs to be scale-able to any number, so sentenceList[variable],
but I do not know how to properly do this.
Thanks, I know this might be confusing.
#declare variable
TOTAL_SENTENCES = 5
def main():
#print greeting
print ('This program will demonstrate lists')
#establish array sentences
sentenceList = list()
#prompt user for how many sentences to store (assume integer, but if
negative, set to 5)
TOTAL_SENTENCES = int(input('How many sentences? '))
if TOTAL_SENTENCES < 0:
TOTAL_SENTENCES = 5
else:
pass
#store in a list in all lower case letters (assume no period at the end)
while len(sentenceList) < TOTAL_SENTENCES:
userSentence = input('Enter a sentence: ')
sentenceList.append(userSentence.lower())
#print 5 options for the user to choose from (looping this for the total
number of sentences)
for i in range(TOTAL_SENTENCES):
print ('Enter 1 to see a sentence\n' 'Enter 2 to see the whole list\n'
'Enter 3 to change a sentence\n' 'Enter 4 to switch words\n'
'Enter 5 to count letters')
#prompt user for their choice
userChoice = int(input('Enter your choice: '))
#print their choice back to them
print ('You selected choice' ,userChoice)
#prompt for which sentence
#CHOICE-1 (pull from the list and print the sentence)
Now, in the last line of your code, if you want to pull up a sentence from the list sentenceList, you can just write:
print(sentenceList[userChoice-1])
Note that I wrote userChoice-1. This is because people usually are going to number the sentences from 1 to N. But Python's internal list numbering is from 0 to N-1.
I hope this answers your question!
I need a program that would let a person enter a person's name and his birth year (5 people only).
The information is written into two lists - one with names and the other with years.
Then the program needs to remove the youngest person (or youngest people).
The final result needs to be printed out in a .txt file.
This is what I have so far:
names = []
ages = []
def names_ages():
while True:
name_age = input("Enter your name and birth year: ")
name_age.split()
print(name_age)
I don't know if I'm going into the right direction or not, could somebody suggest something?
I am going to assume that you are expecting first name and the year to be separated by a space like so.
"andrew 1996"
if so, you are going to want to split the input on space (to have the first entry correspond to "andrew" and the second to correspond to "1996"
response = name_age.split(" ")
Now you can add these values to the arrays that you defined up above (or you could use a python dictionary which I think would be better suited for this problem) https://docs.python.org/2/tutorial/datastructures.html#dictionaries
names.append(response[0])
ages.append(int(response[1]))
You are going to have to decide when to stop accepting names, which you would put in your while loop condition(right now it is running forever) Perhaps wait until the user input is "stop" or something of that nature.
That should get you in the correct direction, comment if you have any questions
name = []
year = []
x=0
while x <3:
x += 1
user = name.append(raw_input("enter name"))
user_year = year.append(raw_input("enter DOB"))
o = []
for i in zip(year,name):
o.append(i)
o.sort()
o.remove(o[0])
print o
This might one from of the solutions from many possible.
I am trying to write a Python program that computes and prints the following :
the average score from a list of scores
the highest score from a list of scores
the name of the student who got the highest score.
The program starts by asking the user to enter the number of cases. For EACH case, the program should ask the user to enter the number of students. For each student the program asks the user to enter the student's name and marks. For EACH case the program reports the average marks, the highest marks and the name of the student who got the highest marks.
Also
If there are more than one person with the highest score in a CASE, the program should report the first occurrence only.
The average score and the highest score should have exactly 2 decimal places.
The output should be as in the sample program output.
What I have been trying so far is the following:
grade=[]
name_list=[]
cases=int(input('Enter number of cases: '))
for case in range(1,cases+1):
print('case',case)
number=int(input('Enter number of students: '))
for number in range (1,number+1):
name=str(input('Enter name of student: '))
name_list.append(name)
mark=float(input('Enter mark of student:'))
grade.append(mark)
highest= max (grade)
average=(sum(grade)/number)
high_name=grade.index(max(grade))
print('average',average)
print('Highest',highest)
print (high_name)
This is what i have deciphered so far. my biggest problem now is getting the name of the individual with the high score. Any thoughts and feedback is much appreciated. As with respect to the answer posted below, i am afraid the only thing i do not understand is the dictionary function but otherwise the rest does make sense to me.
This resembles an assignment, it is too specific on details.
Anyways, the official docs are a great place to get started learning Python.
They are quite legible and there's a whole bunch of helpful information, e.g.
range(start, end): If the start argument is omitted, it defaults to0
The section about lists should give you a head start.
numcases = int(input("How many cases are there? "))
cases = list()
for _ in range(numcases):
# the _ is used to signify we don't care about the number we're on
# and range(3) == [0,1,2] so we'll get the same number of items we put in
case = dict() # instantiate a dict
for _ in range(int(input("How many students in this case? "))):
# same as we did before, but skipping one step
name = input("Student name: ")
score = input("Student score: ")
case[name] = score # tie the score to the name
# at this point in execution, all data for this case should be
# saved as keys in the dictionary `case`, so...
cases.append(case) # we tack that into our list of cases!
# once we get here, we've done that for EVERY case, so now `cases` is
# a list of every case we have.
for case in cases:
max_score = 0
max_score_student = None # we WILL need this later
total_score = 0 # we don't actually need this, but it's easier to explain
num_entries = 0 # we don't actually need this, but it's easier to explain
for student in case:
score = case[student]
if score > max_score:
max_score = score
max_score_student = student
total_score += score
num_entries += 1
# again, we don't need these, but it helps to demonstrate!!
# when we leave this for loop, we'll know the max score and its student
# we'll also have the total saved in `total_score` and the length in `num_entries`
# so now we need to do.....
average = total_score/max_entries
# then to print we use string formatting
print("The highest score was {max_score} recorded by {max_score_student}".format(
max_score=max_score, max_score_student=max_score_student))
print("The average score is: {average}".format(average=average))