The program will display random numbers on the screen and requests for the spelling of that number. It checks if the input is correct, then it displays another number. If the input is wrong, then it will send an error message and request another answer. It need to track the number of correct and wrong answers and display it at the end.
Here's the what I've done so far:
import random
numberList = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
word = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
number = random.sample(numberList, 10)
trials = 3
correct = 0
wrong = 0
attempts = 10
print("HELLO, WELCOME TO THE WORD SPELLING GAME!\n")
print("SPELL AS MUCH NUMBER AS YOU CAN TO GET POINTS!")
print("----------------------------------------------\n")
for element in number:
spell = str(input('Spell ' + str(element) + ':'))
while attempts > 0:
if element == numberList[0]:
if spell.lower() == word[0]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[0]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 0:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[0]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[1]:
if spell.lower() == word[1]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[1]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[1]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[2]:
if spell.lower() == word[2]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[2]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[2]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[3]:
if spell.lower() == word[3]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[3]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[3]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[4]:
if spell.lower() == word[4]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[4]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[4]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[5]:
if spell.lower() == word[5]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[5]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[5]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[6]:
if spell.lower() == word[6]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[6]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[6]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[7]:
if spell.lower() == word[7]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[7]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[7]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[8]:
if spell.lower() == word[8]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[8]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[8]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
elif element == numberList[9]:
if spell.lower() == word[9]:
correct = correct + 1
attempts = attempts - 1
elif spell.lower() != word[9]:
trials = trials - 1
print("Incorrect spelling. ", trials, " trials left.")
if trials > 1:
spell = input('Spell ' + str(element) + ':')
if spell.lower() == word[9]:
correct = correct + 1
attempts = attempts - 1
else:
print("Sorry! Number of trials exceeded.")
wrong = wrong + 1
trials = 3
break
else:
print("\n-----------------------------------------------")
print("END OF GAME!\n")
print("CORRECT SPELLING SCORE: ", str(correct), "\n")
print("WRONG SPELLING SCORE: ", str(wrong))
If I understand your question correctly, this is what you want.
I have changed your import at the top. I have also added some more variables at the top. I have replaced all your condition blocks with a regular function. You can see that if have used ".lower()" as this will stop it from being case sensitive.
from random import randint
numberList = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
word = ["One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten"]
trials = 3
correct = 0
wrong = 0
attempts = 10
attemp_number = 0
print("HELLO, WELCOME TO THE WORD SPELLING GAME!\n")
print("SPELL AS MUCH NUMBER AS YOU CAN TO GET POINTS!")
print("----------------------------------------------\n")
def validate_user_input(random_number_to_spell):
global wrong, correct, attemp_number
result = False
while result == False and attemp_number < attempts and wrong < trials:
print("Please spell the number: ", random_number_to_spell)
user_input = input()
correct_spelling = word[random_number_to_spell-1]
if user_input.lower() == correct_spelling.lower():
print("You spelled ", random_number_to_spell, " correctly")
correct = correct + 1
result = True
attemp_number = attemp_number + 1
else:
print("You did not spell", random_number_to_spell, "correctly")
wrong = wrong + 1
attemp_number = attemp_number + 1
while wrong < 3:
if attemp_number < attempts:
random_number_to_spell = randint(1, 10)
validate_user_input(random_number_to_spell)
else:
break
print("You have ", correct, " correctly spelled numbers")
print("You have ", wrong, " wrong spelled numbers")
Related
I did a condition that if there's only one guess remaining, it shows 'one guess remaining', otherwise, it shows 'x guesses remaining".
But no matters if there's 1 guess remaining, the variable which decides the condition is always 3.
sorry for the English by the way.
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
g_remain = g_limit - g_count
while guess != s_word and not out_of_g:
if g_count < g_limit:
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
The printouts will always show 3 guesses remaining because you don't update g_remain. You should do that after checking that the count is smaller than the limit:
#...
while guess != s_word and not out_of_g:
if g_count < g_limit:
g_remain = g_limit - g_count # <------ UPDATE HERE
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
#...
Or if you think further you might be able to get rid of eather g_countor g_remain.
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
g_remain = g_limit - g_count
while guess != s_word and not out_of_g:
if g_count < g_limit:
if g_remain > 1:
print(str(g_remain) + " guesses remaining")
g_remain -= 1
else:
print(str(g_remain) + " guess remaining")
g_remain -= 1
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
Here is the solution. Change the if statement too, for correct version of 'guesses' and 'guess'.
your code has too many unnecessary vars, we should fix it first
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_count = 4
for guess in range(3):
print(str(g_count - 1) + " guesses remaining")
guess = input("enter a word: ")
if guess == s_word:
print('You Won')
break
else:
continue
g_remain is set once. you have to update the value in every stage. here's the solution:
while guess != s_word and not out_of_g:
g_remain = g_limit - g_count
try this:
You need to change only one line g_remian variable should be declare after while loop then only its works properly.
here is the code.
import random
words = ("elephant", "giraffe", "dog", "cat", "turtle", "bird")
s_word = random.choice(words)
guess = ""
g_limit = 3
g_count = 0
out_of_g = False
while guess != s_word and not out_of_g:
g_remain = g_limit - g_count
if g_count < g_limit:
if g_remain < 2:
print(str(g_remain) + " guesses remaining")
else:
print(str(g_remain) + " guess remaining")
guess = input("enter a word: ")
g_count += 1
else:
out_of_g = True
if out_of_g:
print("you lose")
else:
print("you won")
So, recently i have been trying to program a reverse number guessing game whereby the computer tries to guess the number i have in mind. The output i should get is as shown below:
Enter the range: 6
Think of a random number between 1 and 6 and press enter once done!
Is it smaller than 4, 'y' or 'n'?y
Is it smaller than 2, 'y' or 'n'?n
Is it smaller than 3, 'y' or 'n'?y
Wonderful it took me 3 questions to find out that you had the number 2 in mind!
These are my codes so far:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y' or 'n'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
else:
print ('Please only type y, Y, n or N as responses')
numberHasBeenGuessed = True
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
The main algorithm is working but somehow it cant detect it when the number has been 'guessed'..
does anyone know why?
I will greatly appreciate the help :)
Here is a version using try/except
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
elif response == "y" or response == "Y":
highBound = randomNumber - 1
try:
randomNumber = random.randint(lowBound,highBound)
except ValueError:
numberHasBeenGuessed = True
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
When it encounters a ValueError, it will take it that it has found your number. Please make sure there are no other situations that can result in an incorrect answer with this code, as I obviously haven't tested it thoroughly.
You could also put the try/except clauses in a def to make it more compact as they are the same pieces of code, but I wasn't sure if that was allowed or not for your project, so I left it.
You have numberHasBeenGuessed = True outside of the while loop - which means that it can't get called until the loop is over - so it will be forever stuck.
When it gets to your guess - lets say I have the number 7. Your program asks 'Is 7 smaller or larger than 7?' Obviously that makes no sense, 7 is 7. 7 is not smaller or larger than 7: and your program knows that and crashes. So you need to introduce a new user input option:
import random
maxNum = int(input('Enter the range: '))
input('Think of a random number between 1 and ' + str(maxNum) + ' and press enter once done!')
lowBound = 1
highBound = maxNum
response = ''
noOfGuesses = 0
numberHasBeenGuessed = False
randomNumber = random.randint(lowBound,highBound)
while not numberHasBeenGuessed:
noOfGuesses += 1
response = input("Is it smaller than " + str(randomNumber) + ", 'y', 'n', or 'Thats it'?")
if response == "n" or response == 'N':
lowBound = randomNumber + 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "y" or response == "Y":
highBound = randomNumber - 1
randomNumber = random.randint(lowBound,highBound)
print(randomNumber)
elif response == "Thats it": #New input option 'Thats it'
numberHasBeenGuessed = True #Stops the while loop
else:
print ('Please only type y, Y, n or N as responses')
print('Wonderful it took me ' + str(noOfGuesses) + ' attempts to guess that you had the number ' + str(randomNumber) + ' in mind')
Now, you can input 'Thats it' when your number is guessed and the program finishes with the output you want. (Of course, change the inputs and what not to what you want)
Also final programmer tip: comment your code with hashtags, so you know (and others helping) what each part does.
I am creating a random number generator. I want to add up the guess tries I had for different trials and find the average. However, when I add up the list, it will only calculate how many guesses I had for the first trials divided by the number of trials. How could I fix this problem?
import random
import string
#get the instruction ready
def display_instruction():
filename = "guessing_game.txt"
filemode = "r"
file = open(filename, filemode)
contents = file.read()
file.close()
print(contents)
#bring the instruction
def main():
display_instruction()
main()
#set the random letter
alpha_list = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
letter = random.choice(alpha_list)
print(letter)
guess = ''
dist = []
number_of_guess = []
number_of_game = 1
guess_number = 1
game = True
if guess_number < 5:
rank = 'expert'
elif guess_number >= 5 and guess_number < 10:
rank = 'intermidiate'
else:
rank = beginner
while game == True:
guess_number = int(guess_number)
guess_number += 1
#add the input of user
guess = input("I am thinking of a letter between a and z" + "\n" + "Take a guess ")
#what happens if it is not a letter?
if guess not in alpha_list:
print("Invalid input")
elif alpha_list.index(guess) > alpha_list.index(letter):
print("too high")
dist.append(alpha_list.index(guess) - alpha_list.index(letter))
number_of_guess.append(guess)
#what happens if the guess is less than the letter?
elif alpha_list.index(guess) < alpha_list.index(letter):
print("too low")
dist.append(alpha_list.index(letter) - alpha_list.index(guess))
number_of_guess.append(guess)
elif guess == letter:
print("Good job, you guessed the correct letter!")
guess_number = str(guess_number)
print("---MY STATS---" + "\n" + "Number of Guesses:", guess_number + "\n" + "Level", rank)
replay = input("Would you like to play again? Y/N")
if replay == 'y' or replay == 'Y':
number_of_game += 1
game = True
else:
game = False
print(number_of_guess)
print("---MY STATS---" + "\n" + "Lowest Number of Guesses:" + "\n" + "Lowest Number of Guesses:" + "\n" + "Average Number of Guesses:", str(len(number_of_guess)/number_of_game))
If you want to get the average guesses per game, why you divide the length of the guess list? Why it is even a list? You can save it as an int do:
... "Average Number of Guesses:", (number_of_guess / number_of_game))
Also, note the following:
You initialize number_of_guess with 1, means that you will always count one more guess for the first round.
You do not choose a new letter between each round!
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm still a beginner in python, so I decided to make a rock, paper game.
For some reason, when the user or computer wins, it doesn't give them a point until the next round.
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
for x in range(games):
score = (str(usersc) + "-" + str(compsc))
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + score)
elif comp == 1:
compsc += 1
print("loss " + score)
else:
usersc += 1
print("win " + score)
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + score)
elif comp == 1:
print("tie " + score)
else:
compsc += 1
print("loss " + score)
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + score)
elif comp == 1:
usersc += 1
print("win " + score)
else:
print("tie " + score)
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
For example, when the computer wins, it says loss 0-0 when it should say loss 0-1, but then the next round it'll say 0-1.
Any help would be appreciated.
Problem is that you store score in a variable before incrementing it so you will always be 1 game behind. The simplest way to ensure the score is always correct would be to create a function to get the score like this...
def get_score():
return str(usersc) + "-" + str(compsc)
This would ensure the latest user and comp score values are always used.
Using this the code becomes...
import random
games = int(input("")) #how many games
usersc = 0
compsc = 0
def get_score():
return str(usersc) + "-" + str(compsc)
for x in range(games):
user = input("") #ROCK, PAPER, SCISSORS
comp = random.randint(0,2)
if user == 'ROCK':
if comp == 0:
print("tie " + get_score())
elif comp == 1:
compsc += 1
print("loss " + get_score())
else:
usersc += 1
print("win " + get_score())
elif user == 'PAPER':
if comp == 0:
usersc += 1
print("win " + get_score())
elif comp == 1:
print("tie " + get_score())
else:
compsc += 1
print("loss " + get_score())
elif user == 'SCISSORS':
if comp == 0:
compsc += 1
print("loss " + get_score())
elif comp == 1:
usersc += 1
print("win " + get_score())
else:
print("tie " + get_score())
else:
print("try again")
if compsc > usersc:
print("loss")
elif usersc > compsc:
print("win")
else:
print("tie")
When you are printing loss+score or win+score,
first update score as score = (str(usersc) + "-" + str(compsc)) and then print it.
This is my current HiLo game, I want to integrate a menu with 4 options, 1. read csv file 2. play game 3. show results and 4. exit, any help is appreciated.
Because I don't know where to start.
import\
random
n = random.randint(1,20)
print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")`enter code here`
You could place your game loop inside a menu loop, and all the code for csv file, etc. inside these loops...
However, it is surely preferable to learn a little bit about functions, in order to organize your code a little bit:
Here, I placed your game loop inside a function, and also created functions for the other options; right now, they only print what they should be doing, but as you add features, you will fill this with code.
import random
def read_csv():
print('reading csv')
def show_results():
print('showing results')
def play_game():
n = random.randint(1,20)
# print(n)
guesses = 0
while guesses < 5:
print("Guess the number between 1 and 20")
trial = input()
trial = int(trial)
guesses = guesses + 1
if trial < n:
print("higher")
if trial > n:
print("lower")
if trial == n:
print("you win")
break
if trial == n:
guesses = str(guesses)
print("Congratulations it took" + " " + guesses + " " + "tries to guess my number")
if trial != n:
n = str(n)
print("Sorry, the number I was thinking of was" + " " + n + " ")
while True:
choice = int(input("1. read csv file 2. play game 3. show results and 4. exit"))
if choice == 4:
break
elif choice == 2:
play_game()
elif choice == 3:
show_results()
elif choice == 1:
read_csv()