Loops and comparing strings in homework assignment - python

I need help with an assignment I have for Intro to Python.
The assignment is to have the computer pick a random number between 1 and 100 and the user has to guess the number. If your guess is too high then you will be told. If your guess was too low then you will be told. It will continue repeating until you guess the correct number that was generated.
My issue is that if an input is a string then you would get a prompt saying that it is not a possible answer. How do I fix this issue?
P.S. If it would not be too much trouble, I would like to get tips on how to fix my code and not an answer.
Code:
import random
#answer= a
a= random.randint(1,100)
#x= original variable of a
x= a
correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")
#guess= g
while not correct:
g= input("Please enter a number between 1 and 100: ", )
if g == "x":
print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")
elif int(g) < x:
print("your guess was too low, try again.")
elif int(g) > x:
print("your guess was too high, try again.")
else:
print("Congratulations, you guessed the number!")

So if you want to sanitize the input to make sure only numbers are being inputted you can use the isdigit() method to check for that. For example:
g=input("blah blah blah input here: ")
if g.isdigit():
# now you can do your too high too low conditionals
else:
print("Your input was not a number!")
You can learn more in this StackOverflow thread.

Related

I am extremely new to python and I am making a random number guessing game [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last month.
For right now, I have it so it will print the random number it chose. However, whether I get it wrong or right it always says I am wrong.
here is my code:
import random
amount_right = 0
number = random.randint(1, 2)
guess = input
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
input("enter your guess here! ")
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")
what did I do wrong? I am using Pycharm if that helps with anything.
I tried checking my indentation, I tried switching which lines were the if and else statements (lines 13 - 21) and, I tried changing lines 18 - 21 to elif: statements
guess = int(input())
You need to convert your guess to int and there should be () in input
Also there are 2 input() in your code. One is unnecessary. This can be the code.
import random
amount_right = 0
number = random.randint(1, 2)
print(number)
print(
"welcome to this number guessing game!! I am going to think of a number from 1-10 and you have to guess it! Good luck!")
guess = int(input("enter your guess here! "))
if guess != number:
print("Not quite!")
amount_right -= 1
print("you have a score of ", amount_right)
else:
print("good Job!!")
amount_right += 1
print("you have a score of ",amount_right,"!")

Stuck in a while loop in guessing game?

So I had to make a guessing game where we have someone enter a number, then someone else has to guess that number until they get it right. We also have to state how many tries it took. This is my code so far, but I got stuck in a while loop and I'm not sure how to get out. Any help is appreciated. We also aren't allowed to use return, so I'm stuck. Should
I maybe use a for loop instead?
initial = int(input("Enter the integer for the player to guess. "))
guess = int(input("Enter your guess. "))
tries = 0
while initial != guess:
tries = tries + 1
if initial < guess:
print("Too high - try again: ")
elif initial > guess:
print("Too low - try again: ")
print("You guessed it in", tries,".")
Your issue is that you're not taking input within the body of the loop, so the input doesn't actually change. The fix for this is really simple:
initial = int(input("Enter the integer for the player to guess. "))
guess = int(input("Enter your guess. "))
tries = 0
while initial != guess:
tries = tries + 1
if initial < guess:
guess = int(input("Too high - try again: ")
else:
guess = int(input("Too low - try again: ")
print("You guessed it in", tries,".")
All I did here was replace your calls to print with input and conversion code. I also replaced the elif with else because your while loop already checks that the values aren't equal and the if checks if the initial value is less than the guess so the only possibility left is that the initial value is greater than the guess.
By the way, you should probably be doing input validation as there's nothing stopping the user from entering something which wouldn't convert to an integer.

How to make my while loop work in Python?

This is my code:
import random
Random = random.randint(1, 10)
print("Number:" + str(Random))
Number = int(input("Guess the number I am thinking of from 1-10"))
while int(Random) != Number:
if(Random > Number):
Number = input("Too low. Guess again!")
elif(Number > Random):
Number = input("Too high. Guess again!")
print("You guessed it!")
When the correct number is guessed, this happens, which is what is supposed to happen.
Number:8
Guess the number I am thinking of from 1-10 8
You guessed it!
But, when the number isn't guessed correctly, it loops though the elif statement only.
Number:10
Guess the number I am thinking of from 1-10 6
Too low. Guess again! 7
Too high. Guess again! 6
Too high. Guess again! 5
Too high. Guess again! 4
Too high. Guess again! 3
Too high. Guess again! 2
Too high. Guess again! 1
Too high. Guess again! 10
Too high. Guess again! 9
Too high. Guess again! 8
Have you tried casting int onto the input within both input lines in the while loop? It seems to work for me when it's like:
if(Random > Number):
Number = int(input("Too low. Guess again!"))
elif(Number > Random):
Number = int(input("Too high. Guess again!"))
import random
number=random.randint(1,10)
guess=int(input("Guess the number I am thinking of from 1-10")
while guess !=number:
if guess < number:
print("Your answer was too low...")
else:
print("Your number was too high...")
guess= int(input("Please try again...")
print("Congratulations! Correct answer!")
you can use this as your reference. thank you...
This is an improved version of your code:
import random
answer = random.randint(1, 10)
print("Number:" + str(answer))
guess = int(input("Guess the number I am thinking of from 1-10"))
while answer != guess:
if guess < answer:
guess = int(input("Too low. Guess again!"))
elif guess > answer:
guess = int(input("Too high. Guess again!"))
print("You guessed it!")
Some remarks on the changes:
The main thing is the int() around the input(). input() gets you a value as a string, but you want to compare the values of the numbers, not the strings. For example '12' < '2' but 12 > 2.
Your variables' names had capital letters in them, that's a bad idea in Python, since that signals to editors and other programmers that they're classes instead of variables.
Your variable Random had the same name as the module you're using, making it easy to get confused, answer seemed like a better choice.
Your code was indented with 2 spaces, but most editors default to 4 and that's also inline with standard Python style guidelines.
Instead of flipping the order of variables, it's often best to make your code read as close as possible to what it means; for example, if guess < answer is exactly what you're saying: "too low".

Python- Finding average

I am trying to find the average number of times a user guesses a number. The user is asked how many problems they want to do and then the program will give them that many problems. I am having trouble recording the amount of times they guess and get wrong and guess and get right and finding the average between the two. This is what I have so far
print("Hello!")
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVGcorrect = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
AVGcorrect+=1
print("Correct!")
AVERAGE+=((AVGcorrect+AVGcounter)/AVGcorrect)
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
numPROBLEMS = input("How many problems would you like to solve? ")
PROBLEMS = int(numPROBLEMS)
if PROBLEMS in range(1,11):
for PROBLEMS in range(PROBLEMS):
HOOBLAH()
else:
print("Average number of tries: {0}".format(HOOBLAH,AVERAGE))
else:
print("Please input a value between 1 through 10!")
main()
Thanks!
So I tried to change as little as possible as to not cramp your style. So think about it like this, the average number of guesses needed to get the correct answer is just the total number of guesses divided by the number of correct guesses. Because you make sure the user eventually gets the correct answer, the number of correct guesses will just be the number of problems!
So each time you run HOOBLAH(), return the number of guesses it took to get the correct answer. Add all those up together outside the for loop, then at the end of the loop, divide the number of guesses by the number of problems and then you've got your answer! Also, I don't think python supports '+=', so you may need to change AVGcounter+=1 to AVGcounter = AVGcounter +1, but I totally may be mistaken, I switch between languages a bunch!
One note is I cast numGuesses to a float ( float(numGuesses) ), that is to make sure the int data type doesn't truncate your average. For example, you wouldn't want 5/2 to come out to 2, you want it to be 2.5, a float!
Hopefully that helps!
from random import randint
def HOOBLAH():
randomA = randint(0,12)
randomB = randint(0,12)
answer = 0
CORRECTanswer = (randomA*randomB)
REALanswer = (randomA*randomB)
AVGcounter = 0
AVERAGE = 0
print("What is {0} * {1} ?".format(randomA,randomB))
while answer != REALanswer:
an = input("What's the answer? ")
answer = int(an)
if answer == CORRECTanswer:
print("Correct!")
return AVGcounter
else:
AVGcounter+=1
if answer > CORRECTanswer:
print("Too high!")
else:
print("Too low!")
def main():
problemsString = input("How many problems would you like to solve? ")
numProblems = int(problemsString)
numGuesses = 0
if numProblems in range(1,11):
for problem in range(numProblems):
numGuesses = numGuesses + HOOBLAH()
print("Average number of tries: " + str(float(numGuesses)/numProblems)
else:
print("Please input a value between 1 through 10!")
main()
I'm not totally sure what you're trying to do, but if you want to give the user x number of problems, and find the average number of guesses per problem, you'll want your HOOBLAH() function to return the number of guesses for each run. You can keep track of this outside your method call and average it at the end. But right now, your program has no access to AVGcounter, which seems to be the variable you're using to count the number of guesses, outside the HOOBLAH() function call.

Python Syntax error while making a little game

New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward

Categories