I am new to coding. It works alright until you guess a number. then it says either higher or lower eternally. Please help me understand what I've done wrong. I have tried searching the internet and trying to retype some of the code but it won't work. I am trying to make a conversation as well as a mini guess the number game.
Here's my Code
# Conversation A
import random
print("Answer all questions with 'yes' or 'no' and press ENTER")
print('Hello I am Jim the computer')
z = input('How are you? ')
if z == 'Good' or z == 'Great' or z == 'good' or z == 'great':
print("That's great!")
else:
print("Oh. That's sad. I hope you feel better.")
a = input("what's your name? ")
print(a + "? Thats a nice name.")
b = input('Do you own any pets? ')
if b == 'yes' or b == 'Yes':
print("That's cool. I love pets!")
else:
print("That's a shame, you should get a pet. ")
c = input("Do you like animals? ")
if c == 'yes' or c == 'Yes':
print("Great! Me too!")
else:
print("Oh that's sad. They're really cute. ")
d = input("Do you want to see a magic trick? ")
if d == "yes" or d == "Yes":
input("Ok! Think of a number between 1-30. Do you have it? ")
print("Double that number.")
print("Add ten.")
print("Now divide by 2...")
print("And subtract your original number!")
y = input("Was your answer 5? ")
if y == 'yes' or y == 'Yes':
print("Yay i got it right! I hope you like my magic trick.")
else:
print("Oh that's sad. I'll work on it. I really like magic tricks and games.")
else:
print("Ok. Maybe next time. I love magic tricks and games!")
e = input("Do you want to play a game with me? ")
if e == "yes" or e == "Yes":
randnum = random.randint(1,100)
print("I am thinking of a number between 1 and 100...")
if e == 'no' or e == 'No':
print("oh well see you next time" + a + '.')
guess = int(input())
while guess is not randnum:
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
if guess < randnum:
print("Higher.")
if guess > randnum:
print("Lower.")
You need to add a break statement when you want stop looping and move the input for guess inside the loop so you don't exit before printing the statement:
while True:
guess = int(input())
if guess == randnum:
print("Nice guess " + a + "! Bye, have a nice day!")
break
Edit: Also, you dont want to use is every time: Is there a difference between "==" and "is"?
Related
print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed
I am new to coding and want to train and do my own thing with user inputs. The User Input code does not work. It is a number guessing game. When I guess the right number, it says "Incorrect".
import random
while True:
intro = input("Hello! Want to play a game?(Y or N)")
if intro.lower() == "y" or intro.lower() == "yes":
time.sleep(0.1)
print("Let's play a number-guessing game!")
max_num_in = input("Pick a big number")
max_num = int(max_num_in)
time.sleep(0.1)
min_num_in = input("Now pick a smaller number")
min_num = int(min_num_in)
rndm_num = int(random.randrange(min_num,max_num,1))
print(rndm_num)
rndm_in = input("Guess a number between the maximum and minumum numbers!")
if rndm_num == rndm_in:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in != rndm_num:
print("Whoops, wrong number. Please try again.(Trials left = 2)")
rndm_in1 = input("Guess again!")
if rndm_in1 == rndm_num:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in1 != rndm_num:
print("You didn't get it right. Please try again (Trials left = 1)")
rndm_in2 = input("Guess again!")
if rndm_in2 == rndm_num:
print("Whoo Hoo! You finally did it! The number was" + str(rndm_num))
elif rndm_in2 != rndm_num:
print("Incorrect. The number was " + str(rndm_num))
elif intro.lower() == "n" or intro.lower() == "no":
print("Alright. Bye")
Your inputs are strings convert them to int by using int() function
"5"!=5
This one looks suspicious:
if rndm_num == rndm_in:
It looks like you getting a str as rndm_in but your rndm_num is an int.
Try:
if rndm_num == int(rndm_in):
I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.
I am using Python 2.7. The program generates a random number and asks the user to guess what it is. The while statements work good. The conditional if statement ends the program without following instructions of print followed by calling the function to see if the user wants to play again.
What makes an if statement not follow instructions? Is there a conflict with the later while statements?
# generate random number between 1 & 9
# have user guess the number, then
# tell them if they guessed too low,
# too high, or exactly right
# keep the game going until user types "exit"
# track how many guesses the user has taken, and when game ends, print it out
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
guessThis()
elif wieder == "N":
print ("Have a day")
elif wieder != "Y" or "N":
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
while findout > a:
print ("too high")
findout = int(input("Enter a number from 1 to 9 "))
i += 1
while findout < a:
print ("too low")
findout = int(input("Enter a number from 1 to 9 "))
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Two issues (might be more):
wieder != "Y" or "N": you can't do that, you probably meant to do: wieder not in ["Y", "N"]:
When you declare findout inside a function - it will not be recognized outside. If you want it to be accessed from the outside - create it outside and pass it to the function, or alternatively, make the function return the value that you want back to the caller. Same goes for i.
Comment: regards #1, since you already checked both for 'Y' and 'N', the last condition can be modified from elif wieder != "Y" or "N": to a simple else
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = raw_input("Do you wish to play again? Y or N ")
if wieder == 'Y':
guessThis()
elif wieder == 'N':
print ("Have a day")
elif wieder != 'Y' or 'N':
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
if findout > a:
print ("too high")
guessThis()
i += 1
if findout < a:
print ("too low")
guessThis()
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Replace guessThis() and everything after with this:
def guessThis():
findout = int(input("Enter a number from 1 to 9 "))
i = 1
#Keep going until win condition reached
while findout != a:
#too high guess
if findout > a:
print ("too high")
#too low guess
if findout < a:
print ("too low")
#get next guess
findout = int(input("Enter a number from 1 to 9 "))
i += 1
#We got out of the while, so the game is done :)
print ("You got it correct")
playAgain()
guessThis()
As yours is currently it will not work if the user guesses too high and then too low.
The main problem was that none of your code was executed in the right order cause your indents were off. You need to put the checking logic in the guessThis() function.
Also there is are issues on this function:
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
#need to reset a when playing again
a = random.randint(1, 9)
guessThis()
elif wieder == "N":
print ("Have a day")
#because we have already checked (Y || N), simple 'else' gives us (!Y && !N)
else:
wieder = input("Do you wish to play again? Y or N ")
The !"Y" or "N" doesn't work quite like you expect it does, and I assume you want a new value of a for a new game
Okay so I have been learning quite a bit of Python over the past few days, two or three, and I decided to take my knowledge and create something simple, but sort of entertaining, so I created a Guessing Game.
After about 30 minutes of creating this program and getting it to work 100% I was wondering if there was anything I could have done better, etc. I want to make sure I learn from any mistakes so I appreciate it!
So here is the code:
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
while yourGuess != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
yourGuess = int(input("Take A Guess, Numbers 1 Through 10: "))
else:
if yourGuess == randomNumber:
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame == "N" or playGame == "n":
print("Okay Thanks Anyways!")
break
Thanks Again!
Instead of
if playGame == "Y" or playGame == "y":
print("Okay Lets Play!")
guessingGame()
I kind of like
if playGame.lower() == "y":
# ...
I even better like:
def quit():
print("Okay Thanks Anyways!")
actions = {"y": guessingGame}
actions.get(playGame.lower(), quit)()
from random import randint
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's no integer!")
def play():
secret = randint(1,10)
while True:
guess = getInt("Take a guess (1-10):")
if guess==secret:
print("Congrats, you beat The Guess Game!")
break
else:
print("D'oh! You guessed wrong. Try again!")
def main():
while True:
inp = input("Would you like to play The Guessing Game? (Y/N)").lower()
if inp=="y":
print("Okay, let's play!")
play()
elif inp=="n":
print("Alright. Thanks anyways!")
break
else:
print("You don't follow directions too good, eh?")
if __name__=="__main__":
main()
A few things I noticed:
You should handle the case where user tries to guess something that doesn't look like a number, say the letter 'a' for example.
Python style guide says to prefer lower_with_underscores over CamelCase for variable names.
The line yourGuess = int(input("Take A Guess, Numbers 1 Through 10: ")) is unnecessarily duplicated, see below for one possible way to refactor that part.
General cleanup:
import random
def guessing_game():
random_number = random.randint(1, 10)
assert random_number in range(1, 11)
your_guess = None
while your_guess != random_number:
try:
your_guess = int(input("Take A Guess, Numbers 1 Through 10: "))
except ValueError:
print("That wasn't a number")
continue
if your_guess != random_number:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
print("Congrats You Beat The Guess Game!")
break
play_game = None
while play_game not in ['y', 'n']:
play_game = input("Would You Like To Play The Guessing Game (Y/N): ").lower()
if play_game == "y":
print("Okay Lets Play!")
guessing_game()
else:
assert play_game == "n":
print("Okay Thanks Anyways!")
I imagine you could use a "break" statement inside a while loop, as in
import random
def guessingGame():
randomNumber = random.randrange(1, 10)
while True:
yourGuess = input("Take A Guess, Numbers 1 Through 10: ")
if !yourGuess.isdigit():
print ("That's not a number!")
elif int(yourGuess) not in range(1,10):
print("I said between 1 and 10!")
elif int(yourGuess) != randomNumber:
print("DOH! You Did Not Guess Right, TRY AGAIN")
else:
break
print("Congrats You Beat The Guess Game!")
playGame = input("Would You Like To Play The Guessing Game (Y/N): ")
if playGame.lower() == "y":
print("Okay Lets Play!")
guessingGame()
elif playGame.lower() == "n":
print("Okay Thanks Anyways!")
break
Read the Pep 8 documentation on naming conventions and Python's style of coding.
import random
def guessing_game(x=1, y=10):
"""
A simple number guessing game.
"""
while int(input("Take A Guess, Numbers 1 Through 10: ")) \
!= random.randrange(x, y):
print("DOH! You Did Not Guess Right, TRY AGAIN")
print("Congrats You Beat The Guess Game!")
if input("Would You Like To Play The Guessing Game (Y/N): ") == 'Y':
print("Okay Lets Play!")
guessing_game()
else:
print("Okay Thanks Anyways!")
if __name__ == '__main__':
guessing_game(1, 10)