I am new to Python, so I decided to start with a numbers game. I have my numbers being input correctly, but I would like it to display the number of correct answers and the correct original, random numbers.
Code as follows:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = [random.randint(0, 10), numberOfNumbers]
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got' + numCorrect + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Current output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Original: [5, 3]
Your guess: [1, 2, 3]
Target Output:
Now try to guess a list of numbers! The range of number is 0-10
How many numbers do you want?
Enter the number: 3
Enter your 3 numbers.
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
(Currently not working for print) You got (x) Correct!
(Here prints answers, it's only printing two numbers) Original: [5, 3, x]
(Your input prints here, working as planned) Your guess: [1, 2, 3]
You do this:
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
But, since you keep appending to values, it will never be equal to (==) answers until all the correct answers are in there, and even then only if they are in the correct order.
If you want numCorrect to have the number of answers in values that is currently correct, you can write something like:
numCorrect = len([v for v in values if v in answers])
Of course, if you only want to print numCorrect if it changes, you have a bit more code to write.
(also note that this goes sideways if you have duplicate correct answers, so it's not quite this simple, but I'm not writing your game, just correcting your code so it does what you appear to want it to do)
You do this:
answers = [random.randint(0, 10), numberOfNumbers]
That creates a list with two numbers, a random number and numberOfNumbers. It looks like you really want a list of length numberOfNumbers with all random numbers:
answers = [random.randint(0, 10) for _ in range(numberOfNumbers)]
This could include duplicates, but you get to figure out how to avoid that.
In general, I would recommend using a free IDE like PyCharm or Spyder to debug your code. They have options that allow you to step through your code one line at a time, so you can see how the values of variables change as your commands execute - that will make a lot more sense.
Since you are pretty new to python I decided to stick to your code and correct them instead of complicating it. So, what you basically did wrong was that you were using print('You got ' + str(numCorrect) + ' correct!') inside the if statement because if the condition wasn't true the print statement wouldn't work.
The next was that you needed to get the random numbers inside while loop to get the x number of random numbers. Or, else what you were doing was that you simply got one random number and the input from numberOfNumbers.
Here's the final code:
import random
print('============================')
print('Now try to guess a list of numbers! The range of number is 0-10')
print('How many numbers do you want?')
numberOfNumbers = int(input('Enter the number: '))
counter = 0
answers = []
values = []
numCorrect = 0
print('Enter your ' + str(numberOfNumbers) + ' numbers.')
while numberOfNumbers != counter:
ans_var = random.randint(0,10)
answers.append(ans_var)
counter += 1
values.append(int(input("Enter number " + str(counter) + ": ")))
if values == answers:
numCorrect += 1
print('You got ' + str(numCorrect) + ' correct!')
print('Original: ' + str(answers))
print('Your guess: ' + str(values))
Hope it helps :)
Related
I need to make a program that takes an integer input and when you enter a number, it types out the spelling of each digit. For example, I inputted 12, the program will print out:
One
Two
I have a little problem with the code, how do I print out the results (or the spellings) vertically and in separate lines? The output should be:
Enter the number: 86
Eight
Six
But my output is:
Enter the number: 86
Eight Six
I just need it to print vertically and in different lines like I said. Thank you! You can alter the code itself too, This is my code:
arr = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine']
def number_2_word(num):
if(num==0):
return ""
else:
small_ans = arr[num%10]
ans = number_2_word(int(num/10)) + small_ans + " "
return ans
num = int(input("Enter the number: "))
print(end="")
print(number_2_word(num))
In this line:
ans = number_2_word(int(num/10)) + small_ans + " "
Use line break rather than space
ans = number_2_word(int(num / 10)) + small_ans + "\n"
I did a few tests, seems work as you expected
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 12 months ago.
I'm a python beginner in and got an assignment for school to make the simple number guessing "game" where you have to figure out a number by guessing and it either says higher or lower until you guess the correct number. It worked well until i added two player support and the ability to choose the interval that the random number will be in. Now the higher/lower result from the guess is the opposite if the amount of digits in the guess is different from the random unkown number. Lets say that the random number is 50, then guessing a number between 10-49 will give the result "guess higher", guessing a number between 99-51 will give the result "guess lower" like it's supposed to do. However if the guess is a different amount of digits like 0-9 it will say "guess lower" which is the opposite, same if i guess 100 or anything above it will say "guess higher".
The code:
import random
while True:
select = input("En eller två spelare? ")
if select == '1':
y = input("0 - ")
num = str(random.randint(1, int(y)))
while True:
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
elif guess > num:
print('Lägre än ' + guess)
if select == '2':
spelare1 = input("Spelare 1: ")
spelare2 = input("Spelare 2: ")
y = input("0 - ")
num = str(random.randint(1, int(y)))
spelare = 0
while True:
if spelare%2 == 0:
print(spelare1 + 's tur')
if spelare%2 == 1:
print(spelare2 +'s tur')
guess = input('Gissa mellan 0 - ' + y+": ")
if guess == num:
print('Rätt nummer: ' + guess)
if spelare%2 == 0:
print(spelare1, "vann!")
break
if spelare%2 == 1:
print(spelare2, "vann!")
break
elif guess == "haks":
print(num)
elif guess < num:
print('Högre än ' + guess)
spelare = spelare+1
elif guess > num:
print('Lägre än ' + guess)
spelare = spelare+1
I can't find any logic in this and already spent to much time on trying to fix it. Any help is much appreciated and if there are any questions about the code I'll happily answer them.
The number of digits doesn't matter
There's a difference between inequality comparisons on strings (like you're doing) and on actual numbers.
When used on strings, it's comparing alphabetically, not numerically
You should convert all inputs to numbers, not compare them as strings (the default return type of input function). Similarly, don't cast your random digits to strings
I have tried everything i can still doesn't work. Please any help would be appreciated.
Please i have been able to allow it generate one hint, but i need it to generate 3 different hints the 3 different times the user presses 0 for the hint.
I have it give the hint even OR odd. i need it to give extra 2 hints.
Part 1:
Generates a random number between 1 and 100.
Allows the user 10 tries to guess what the number is.
Validates the user input (if user-input >100 or user-input<0) then this is invalid input and should not cost the user to lose any tries.
Gives feedback for each time the user makes a guess. The feedback tells the user whether the number entered is bigger, smaller, or equal to the number generated (and exits the program).
Tells the user if they lost after he/she consumes all the 10 tries. Gives the user 10 tries to guess the number. If the user exhausts the 10 ties. The user loses.
Part 2:
After 2 unsuccessful tries, the program should start offering hints for the users (by having the user input the number 0).
Each hint should be generated within a function of its own.
Each hint will cost the user two tries (the program should indicate this to the user)
The user is allowed a max of 3 hints only.
The program should randomly pick which hint it is going to use and display to the user.
(example of a hint is : 1- The number is bigger than or equal the square of some X (X is an integer and is the largest integer square that is less than the user input))
Here is my program so far:
import random
guessesTaken = 0
print('WELCOME! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Hello, ' + myName + ', I generated a number between 1 and 100.')
unsuccessful_tries = 0
hint_taken = 0
while guessesTaken < 10:
if unsuccessful_tries > 1 and hint_taken<3:
print('Press 0 to get hint')
need_hint = int(input())
if need_hint == 0:
hint_taken += 1
guessesTaken += 1
if number%2==0:
print('The Generated number is an EVEN number')
else:
print('The Generated number is an ODD number')
print('Take a guess.\t%d Attempts Left'%(10 - guessesTaken))
#10-guessTaken gives the number of tries left
guess = input()
guess = int(guess)
#validating the user's input
if guess >100 or guess<0:
continue
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
unsuccessful_tries+=1
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
Let me nudge you towards solving part two:
You're already keeping track of the user guesses with the guessesTaken variable
A random 'Hint' can be simply randomly choosing through a list of pre-made hints ( if you had 5 pre-made hints, you could just choose a random number between 1-5, and select that one)
'Costing' the user two tries is as evaluating whether they have enough guesses to afford it ( i.e: if they are at guess number 9, they can't afford to give up 2 guesses), and then add two to the guessNumber if they accept a hint.
You can evaluate the amount of hints taken with a counting variable, though given your parameters (they have to have two unsuccessful guesses to receive a hint, with a maximum of 3 hints total), they would not be able to have 3 hints.
This is the most exact answer i can give you, since you haven't provided any code for part 2 that isn't working or that you need help with.
loose example for point #2: choose a random function from a list:
my_list = [func_test_1, func_test_2, func_test_3]
random.choice(my_list)()
You should create variables which keep tracks of the number of unsuccessful tries and hint taken. If the number of unsuccessful tries is greater than 2 and hint taken is less than 3 then you should ask the user if he wants hint.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Hello, ' + myName + ', I am thinking of a number between 1 and 100.')
unsuccessful_tries = 0
hint_taken = 0
while guessesTaken < 10:
if unsuccessful_tries > 1 and hint_taken<3:
print('Press 0 to get hint')
need_hint = int(input())
if need_hint == 0:
hint_taken += 1
guessesTaken += 1
print('Here is hint')
#Do this by yourself chose a hint and display
print('Take a guess.\t%d Attempts Left'%(10 - guessesTaken))
#10-guessTaken gives the number of tries left
guess = input()
guess = int(guess)
#validating the user's input
if guess >100 or guess<0:
continue
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
unsuccessful_tries+=1
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
I am working on a guessing game in python, i think i have everything only, i want to make the program to guess between numbers it already guessed for example, if the users number is 5, and it picks 3 the user input '+' and it knows the number is higher, and if the program guess 6 the user input '-' and it knows the number is lower than 6, but sometimes it guesses a 2, its obvious that if the number is higher than 3 it can't possibly be 2 right, so how do i write that? I am a beginner at this and i would appreciate if you could make it simple, below is my code.
print("Hello,")
print("welcome to the guessing game")
print('I shall guess a number between 1 and 99, and then ask you if am right')
print('I have a maximum of 20 chances\n')
import random
guess = random.randint(1,99)
print("Your number is %f, Am i right?" % guess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
print("You chose %s" % ans)
minguess = 1
maxguess = 99
count = 0
while (count < 20):
count = count + 1
if ans == '+':
##I am using these prints to keep track of the numbers and if everything is working correctly
maxguess1 = guess + 1
print('THe maxguess is', maxguess1)
newguess = random.randint(maxguess1, maxguess)
print('The newguess is', newguess)
newguess = int(newguess)
print("Is it %d?" % newguess)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
elif ans == "-":
maxguess2 = guess - 1
print('The minus maxguess is', maxguess2)
newguess = random.randint(minguess, maxguess2)
print('The minus newguess is', newguess)
newguess1 = int(newguess)
print("Is it %d?" % newguess1)
print('If I am, enter =, If the number is higher enter (+), if the number is lower enter (-)')
ans = input('Which is it: ')
if ans == "=":
print('YAAAAAAS MAN')
i wanted it to change the numbers whenever it guessed a new number
guess = newguess
NOTE: This example is in Python 2.7, NOT Python 3, but the concepts are the same.
Break down the problem into its individual elements:
import random
# Possible Range is [1-99], 1 inclusive to 99 inclusive
min_possible = 1
max_possible = 99
# Number of Guesses
max_guesses = 20
# Process
for i in xrange(max_guesses): # Loops through the process 'max_guesses' times
# Program Takes a Guess
guess = random.randint(min_possible, max_possible)
print 'My guess is ' + str(guess)
# Ask for User Feedback
user_feedback = ''
while not user_feedback in ['+', '-', '=']:
user_feedback = raw_input('Is the number higher (+), lower (-), or equal (=) to my guess?')
# Use the User Feedback
if user_feedback == '+':
min_possible = guess + 1 # B/c low end is inclusive
elif user_feedback == '-':
max_possible = guess - 1 # B/c high end is inclusive
else:
print 'I knew the answer was ' + str(guess)
break
I am supposed to write a program in python that asks the user how many multiplication questions they want, and it randomly gives them questions with values from 1 to 10. Then it spits out the percentage they got correct. My code keeps repeating the same set of numbers and it also doesn't stop at the number the user asked for. Could you tell me what's wrong?
import random
import math
gamenumber = int(input("How many probems do you want?\n"))
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
correct = guess == answer
if guess == answer:
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
You only assign to num_1 and num_2 once. Their values never change; how can your numbers change? Furthermore, you don't increment count, so its original value is always compared against gamenumber.
You need to assign a new random number to your two variables and increment your counter.
You forgot to increment count in your loop and num_1 and num_2 don't get new values.
Problems you mentioned
My code keeps repeating the same set of numbers
This is no surprise, as you set your num_1 and num_2 (1) outside the main function and (2) outside the main while loop. A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
My code doens't stop at the number asked for:
There again, no surprise, as you never increment the count counter: you always have count < gamenumber.
A simple correction is:
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
Here, the count += 1 means add 1 to count *in place*. You could also do count = count + 1 but it's a bit less efficient as you create a temporary variable (count + 1) that you don't really need.
Other problems
You never define wrong
You define gamenumber outside the function. While it's not an issue in this case, it'd be easier to use gamenumber as an argument of main, as it's the variable that drives the game.
Your result is defined in the loop. You probably want to increment a counter for each good answer and print the result after the main loop.
Your result is calculated as correct/wrong. While I'm sure you meant correct/gamenumber, you have to be extra careful: count and gamenumber are integers, and dividing integers is no the same as dividing floats. For example, 2/3 gives 0, but 2/float(3) gives 0.6666666. So, we'll have to use a float somewhere.
You want to print a percentage: your result should then be result=correct*100./gamenumber.
You don't want to gamenumber to be 0, otherwise your result will be undefined.
So, all in all, your main function should be
def main(gamenumber):
random.seed()
count = 0
correct = 0
while count < gamenumber:
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
count += 1
if guess == answer:
correct += 1
print("Correct!")
else wrong:
print("Sorry, the answer is", answer, ".")
if gamenumber > 1:
result = correct * 100./gamenumber
print("You got ", "%.1f"%result, "of the problems.")
The most glaring issue to me is that you have an infinite loop; you don't increase count anywhere.
You're only generating the question numbers once, before you start looping. You need to generate num_1 and num_2 every time, before the user is asked a question.
You never actually update the count value after initializing it, so your loop will go on forever.
import random
import math
spelling of "problems" is wrong
gamenumber = int(input("How many probems do you want?\n"))
move these next two lines inside the loop
num_1 = random.randint(1,10)
num_2 = random.randint(1,10)
def main():
random.seed()
count = 0
while count < gamenumber:
You can use "What is {}x{}?".format(num1, num2) here.
guess = int(input("What is " + str(num_1) + "x" + str(num_2) + "."))
answer = str(num_1*num_2)
Is this supposed to count the correct answers? should be correct += guess == answer
correct = guess == answer
Do you mean to count the number of wrong answers? wrong += guess != answer
if guess == answer:
print("Correct!")
else wrong: is a syntax error else: #wrong perhaps?
else wrong:
print("Sorry, the answer is", answer, ".")
This isn't how to compute a percentage. You should use correct*100/gamenumber and dedent to match the print()
result = correct/wrong
print("You got ", "%.1f"%result, "of the problems.")
main()
Also you're not incrementing count anywhere. It's easier to just use
for count in range(gamenumber):
instead of the while loop
Python is a procedural language. It executes statements in your method body from top to bottom. This line:
num_1 = random.randint(1,10)
is an assignment statement. It does not equate num_1 with a random process for assessing its value; it evaluates an expression - by calling random.randint(1,10) - and assigns that value to num_1, once.
You must force another call to random.randint to obtain another random number, and you must have a statement assign a value to num_1 each time you want num_1's value to change.
Write a multiplication game program for kids. The program should give the player ten randomly generated multiplication questions to do. After each, the program should tell them whether they got it right or wrong and what the correct answer is
from random import randint
for i in range (1,11):
num1 = randint (1,10)
num2 = randint (1,10)
print ("Question",i,":",num1,"*",num2,"=", end = " ")
guess = int (input())
answer = num1*num2
if guess == answer:
print ("Right!")
else:
print ("Wrong. The answer is: ",answer)