https://i.imgur.com/i4KBnkA.png is an image of the code working and the output.
I have a homework assignment to create a high score list from inputted names and scores. It is supposed to display them in order, and I have it working, I just cannot for the life of me figure out how to remove the unnecessary formatting from my code. I've tried doing join stuff, can't really figure out the converting to String options... I will probably get full credit for this solution, but I really want to know how to make it more easily readable.
Scores = []
count = 0
question = True
while question == True:
name = str(input("Whose score are you inputting?"))
if name != "Done":
score = int(input("What did " + name + " score?"))
entry = score, name
Scores.append(entry)
count = count + 1
elif name == "Done" and count < 5:
print("You haven't input 5 scores yet!")
else:
question = False
Scores.sort(reverse=True)
print(*Scores, sep='\n')
input("")
Related
So the trouble I am having is the score not being properly calculated because it should have a minimum score of 0 and maximum score of 5, instead the minimum score is changed to 12, and maximum to 13. The score should be calculated if the inputted number corresponds to the answer bracket stored.
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
#print (newqlist)
#print (anslist)
score = 0
for i in newqlist:
print (i)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == ("t"):
count += 1
elif answer ==("f"):
count += 1
else:
print("invalid answer")
count += 1
for j in anslist:
if answer == j:
score +=1
print (score)
#gives back the user their score once completed
# if the user gets a question correct, score will be added to a maximum of 5
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )
3 things:
Change the loop statement to this: for q, realAns in zip(newqlist, anslist): This basically iterates through a list that has the question and answer paired up into tuples. So for example, the first element looks like: ("Q1", "t")
Change if answer == ("t"): to if answer == realAns. This just checks whether the user's answer matches the real answer.
Under if answer == realAns:, change the count += 1 to score += 1. A score variable doesn't exist in your code, so it would just error out.
Remove the elif answer ==("f"): statement and its corresponding count += 1.
Remove the count += 1 under your else statement.
Remove this section:
for j in anslist:
if answer == j:
score +=1
Since this loop runs every time your answer a question, it'll add the number of times the answer shows up in the answer list 5 times, which probably isn't what you want if you're just counting how many answers the user got right.
Your code after these changes should look something like this:
#This is an example of a list
questlist = ["Q1","t", "Q2", "f", "Q3", "t", "Q4","f", "Q5", "t"]
#I want to display each question individually, to be answered then moving on to the next question.
#breaks down the questlist into questions and answers.
newqlist = (questlist[::2])
anslist = (questlist[1::2])
score = 0
for q, realAns in zip(newqlist, anslist):
print (q)
answer = input("Enter 'true' for true, 'false' for false.")
if answer == realAns:
score += 1
else:
print("incorrect answer")
#gives back the user their score once completed
print (score)
percentage = ((score/5)* 100)
print ("Your score is " + str(score) + " out of 5 and " + str(percentage) + "%." )
Trying to only allow number inputs in python 3.x no letters and ask user to input a number if they enter a letter. I have two numbers that need to be entered and need it to reject singlarily as they are entered.
print ('Hello There, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname)# String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
num1,num2 = float(input("Enter first number")), float(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <=100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
You need a while loop to continuously accept a valid input which in your case is a numerical one.
Another thing is that you need to check if the entered input is numerical or not, in that case you can use Python's inbuilt isdigit() function to do it.
Lastly, type cast your input to float or int while you add the both to avoid str related errors.
print ('Hello there, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname) # String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
i = False
while i == False:
num1 = input("Enter first number: ")
if num1.isdigit():
i = True
else:
i = False
print() # adds a space
j = False
while j == False:
num2 = input("Enter Second number: ")
if num2.isdigit():
j = True
else:
j = False
sum = float(num1) + float(num2)
if sum > 100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <= 100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
Let me know, if that worked for you!
When you are validating multiple inputs, I usually make a separate function to do so. While it may not be necessary here, it is a good habit to factor out repeated code. It will exit if either of the inputs are not floats. Here's how I would do it, using a try block with a ValueError exception. By the way, newlines can be achieved by putting '\n' at the end of the desired strings. Using print() is a sloppy way of doing it.
import sys
def checkNum(number):
try:
number = float(number)
except ValueError:
print("That is not a float.")
sys.exit()
return number
Then, you can use the original code like so:
print ('Hello There, what is your name?') #String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname + '\n')#String responds "Nice to meet you" and input the users name that was entered
print ('We want to some math today!\n') #String tells user we want to do some math today
num1 = checkNum(input("Enter first number"))
num2 = checkNum(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') #If inputs are > 100 prints "They add up to a big number" and the users name
elif sum <=100 : #Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
Mastermind Game using "ABCEF"I dont know how to check whether it is partial correct. I have to use red to mean correct letter and position. I use white to mean correct letter.
import random
def play_one_round():
N_code=''.join(random.sample("ABCDEF",4))
print (N_code)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess= 1
while N_code != guess and count_guess < 10:
check(N_code,guess)
guess=input("Enter your guess as 4 letters e.g. XXXX:")
count_guess=count_guess + 1
print("This is your",count_guess, "guess")
if guess==N_code:
print('r') #Here I have if the code and guess are equal print r, which mean its the right letters in the right order.
def check(N_code,guess):
result=['r' if c1==c2 else c2 for c1,c2 in zip(guess, N_code)]
for index, char in enumerate(guess):
if result[index] !='r':
if char in result:
result[result.index(char)]='w'
print(result)
def Master_m():
print("Welcome to Mastermind!\n")
print("Start by Choosing four letters")
play_one_round()
answer=input("Play Again? ")
if answer[0]=='y':
Master_m()
Master_m()
I wrote this ages ago but it will do the trick
import random
import itertools
def start():
""" this function is used to initialise the users interaction with the game
Primarily this functions allows the user to see the rules of the game or play the game"""
print ('Mastermind, what would you like to do now?\n')
print ('Type 1 for rules')
print ('Type 2 to play')
path = input('Type your selection 1 or 2: ')
if path == '1':
print ('Great lets look at the rules')
rules()
elif path == '2':
print('Great lets play some Mastermind!\n')
begingame()
start()
else:
print('that was not a valid response there is only one hidden option that is not a 1 or a 2')
start()
def rules():
"""This just prints out the rules to the user."""
print ('The rules are as follows:\n')
print ('1)Mastermind will craft you a 4 digit number that will contain all unique numbers from 1-9, there is no 0s.\n')
print ('2)You will have 12 attempts to guess the correct number.\n')
print ('3)Whites represent a correct number that is not in the correct order\n')
print ('4)Reds represent a correct number in the correct order.\n')
print ('5)If you enter a single number or the same number during a guess it will consume 1 of your 12 guesses.\n')
print ('6)to WIN you must guess the 4 numbers in the correct order.\n')
print ('7)If you run out of guesses the game will end and you lose.\n')
print ('8)if you make a guess that has letters or more than 4 digits you will lose a turn.')
start()
def makeRandomWhenGameStarts():
"""A random 4 digit number is required this is created as its own
variable that can be passed in at the start of the game, this allows the user
to guess multiple times against the one number."""
#generate a 4 digit number
num = random.sample(range(1,9), 4)
#roll is the random 4 digit number as an int supplied to the other functions
roll = int(''.join(map(str,num)))
return roll
def begingame():
"""This is the main game function. primarily using the while loop, the makeRandomWhenGameStarts variable is
passed in anbd then an exception handling text input is used to ask the user for their guees """
print ('please select 4 numbers')
#bring in the random generated number for the user to guess.
roll = makeRandomWhenGameStarts()
whiteResults = []
redResults = []
collectScore = []
guessNo = 0
#setup the while loop to end eventually with 12 guesses finishing on the 0th guess.
guesses = 12
while (guesses > 0 ):
guessNo = guessNo + 1
try:
#choice = int(2468) #int(input("4 digit number"))
choice = int(input("Please try a 4 digit number: "))
if not (1000 <= choice <= 9999):
raise ValueError()
pass
except ValueError:
print('That was not a valid number, you lost a turn anyway!')
pass
else:
print ( "Your choice is", choice)
#Use for loops to transform the random number and player guess into lists
SliceChoice = [int(x) for x in str(choice)]
ranRoll = [int(x) for x in str(roll)]
#Take the individual digits and assign them a variable as an identifier of what order they exist in.
d1Guess = SliceChoice[0:1]
d2Guess = SliceChoice[1:2]
d3Guess = SliceChoice[2:3]
d4Guess = SliceChoice[3:4]
#combine the sliced elements into a list
playGuess = (d1Guess+d2Guess+d3Guess+d4Guess)
#Set reds and whites to zero for while loop turns
nRed = 0
nWhite = 0
#For debugging use these print statements to compare the guess from the random roll
# print(playGuess, 'player guess')
# print(ranRoll,'random roll')
#Use for loops to count the white pegs and red pegs
nWhitePegs = len([i for i in playGuess if i in ranRoll])
nRedPegs = sum([1 if i==j else 0 for i, j in zip(playGuess,ranRoll)])
print ('Oh Mastermind that was a good try! ')
#Take the results of redpegs and package as turnResultsRed
TurnResultsRed = (nRedPegs)
#Take the results of whitepegs and remove duplication (-RedPegs) package as TurnResultsWhite
TurnResultsWhite = ( nWhitePegs - nRedPegs) #nWhite-nRed
#Create a unified list with the first element being the guess number
# using guessNo as an index and storing the players choice and results to feedback at the end
totalResults = ( guessNo,choice , TurnResultsWhite ,TurnResultsRed)
# collectScore = collectScore + totalResults for each turn build a list of results for the 12 guesses
collectScore.append(totalResults)
#End the while loop if the player has success with 4 reds
if nRed == (4):
print('Congratulations you are a Mastermind!')
break
#Return the results of the guess to the user
print ('You got:',TurnResultsWhite,'Whites and',TurnResultsRed,'Red\n')
#remove 1 value from guesses so the guess counter "counts down"
guesses = guesses -1
print ('You have', guesses, "guesses left!")
#First action outside the while loop tell the player the answer and advise them Game Over
print('Game Over!')
print('The answer was', roll)
#At the end of the game give the player back their results as a list
for x in collectScore:
print ('Guess',x[0],'was',x[1],':','you got', x[2],'Red','and', x[3],'Whites')
if __name__ == '__main__':
start()
When you are stuck, decompose into smaller chunks and test those. Focusing on check, you can check whether a guess letter exactly matches the code via its index and whether its in the code at all with in. Here is a self-contained example. Notice that I've pulled out everything except the problem at hand.
If this works for you, I suggest writing a self-contained example of your next problem, test it, and if you are still stuck, post that as a new question.
def check(N_code, guess):
print('code', N_code, 'guess', guess)
result = []
# enumerate gives you each letter and its index from 0
for index, letter in enumerate(guess):
if N_code[index] == letter:
# right letter in right position
vote = 'red'
elif letter in N_code:
# well, at least the letter is in the code
vote = 'white'
else:
# not even close
vote = 'black'
# add partial result
result.append('{} {}'.format(letter, vote))
# combine and print
print(', '.join(result))
check('ABCD', 'ABCD')
check('DEFA', 'ABCD')
import time, random
#WELSCR
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
input("Hit enter to play")
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
doublespace = print("\n\n")
singlespace = print("\n")
tripplespace = print("\n\n\n")
guessed = []
score = 1000
wrong = 0
puzzle , hint = random.choice(questions)
blank = puzzle
for round in range (1,10):
tries = 0
iscorrect = False
while (not iscorrect) and (tries < 6):
blank = puzzle
for letter in blank:
if letter in "abcdefghijklmnopqrstuvwxyz":
blank = blank.replace(letter, "-")
def print_puzzle():
print("\n"*45)
print(WOF1)
print("\n")
print(WOF2)
print("\n"*2)
print(blank.center(80))
print("The hint is:",hint.title())
print("You currently have $",score)
print_puzzle()
input("enter")
break
break
This is the beginning of my program that I just started, a wheel of fortune game for a class. I can get it to replace almost all of the letters with a dash, however, there are the occasional few letters that do not always get hidden by this code and I'm not sure why. I have a variable defined as question which is a nested tuple but I did not include it because it's long and contains about 150 different entries.
Nevermind, the problem was case sensitivity. I had proper nouns and capitalized them, but I did not include capital letters in my replace string.
I'm trying to create a word guessing game, after each guess the computer should return the frequency of letters in the right place, however it is this part that I have been unable to manage to get working. Can anyone help me?
import random
def guess(secret,testWord):
return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))
words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0
print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)
words = words.split('\n')
WordToGuess = random.choice(words)
GameOn = True
frequencies = []
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('Congragulations, You Won!')
GameOn = False
else:
print(correctLength, '/', len(WordToGuess), 'correct')
if Guesses >= 4:
GameOn = False
print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
In your guess function, you are printing the value, not returning it. Later, however, you try to assign something to correctLength. Just replace print by return, and your code should work.
Update to answer question in comments:
I think a very easy possibility (without a lot of changes to your code posted in the comment) would be to add an else clause, such that in case that the input is empty, you return directly to the start of the loop.
while GameOn:
currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
if len(currentguess) <=0:
print('Sorry you must enter a guess')
else:
correctLength = guess(WordToGuess,currentguess)
if correctLength == len(WordToGuess):
print('statement')
GameOn = False
elif Guesses <= 0:
GameOn = False
print('statement')
else:
Guesses = Guesses -1
print('statement')
print('statment')