Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my code:
name = input("What is your name? ")
print name + " do you want to play a game?"
answer = input("To play the game, type either yes or no. ")
if answer == yes:
print "Great," + name + "lets get started!"
elif answer == no:
print "Okay, good bye!"
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?"
while answer == yes:
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?
elif answer == no:
print "Okay. Good game " + name + "!"
print "Play again soon!"
Ok, my first question is why does python not recognize input for the name variable as a string.
The second question is the last elif statement keeps giving me a syntax error. I am not sure why.
The last question is can I loop this code any easier way?
In Python 2x versions, input() takes variable as integer, you could use raw_input() to take it as string.
So basically change your input() to raw_input() for taking the data as string.
In Python 3x versions there is no raw_input, there is only input() and it takes the data as string.
Second question;
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
This is not a correct syntax, your else needs an if block above itself. You can't use else without an if block.If you think for a second, that makes sense.
Your last question is not fit with SO rules.
Related
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,"!")
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am a beginner at python programming. I am trying to make a game, which will asked you how many numbers of letters of hint you want. Then it will ask you number of lives you want. Then it will give a hint, and ask you to guess a number and type any one letter of your word.
For example, if your word is for and you type O it will show --.o.-- and then if you type f it will show F.O.--. So I am not able to finish my project.
This is my code:
import random
allthewords =['ability','absence','academy','account','accused','achieve','acquire','address','advance','adverse','advised','adviser','against','airline','airport','another','ancient','auction',
'average','backing','balance','article','barrier','capable','banking','bedroom','caliber','capital','bearing','beating','calling','captain','battery','because','anxious']
random =(random.randrange(0,len(allthewords)))
randomwords = (allthewords[random])
letters=(len(randomwords))
hintnum=input("how many number of letter you want the hint of? ("+str(letters)+" is maximum): ")
hint= ''.join(randomwords)
hint1= hint[0:int(hintnum)]
while hintnum > str(letters):
print("sorry "+str(letters)+" is maximum")
hintnum=input("how many number of letter you want the hint of? ("+str(letters)+" is maximum): ")
print(" ")
hint= ''.join(randomwords)
hint1= hint[0:int(hintnum)]
print(" ")
l= input("how many number many lives you want?: ")
lives = l
live = 1
print("hint: " +hint1 + " is in the word")
x=1
place= -1
while x==1:
user =input("whats your letter?: ")
print("hint: " +hint1 + " is in the word")
if 1 != 3:
place1=place+1
if place == user.find(user):
print(" ")
empty=("_."*letters)
empty = empty[:place] + user + empty[place+1:]
print (empty)
print("its correct")
##############
if user != randomwords[place+1]:
lives=int(1)-1
print("wrong answer try again!")
print(" ")
if live == 0:
print("you lost!, too many tries ")
x= x-1
a=input("do you want to know the answer?: yes/no")
if a==("yes"):
print(randomwords)
if a==("no"):
print("ok,thanks")
The main things I noticed:
The lives input is a string, so convert it to an int first
In the place calculation, each letter takes two spaces
When inserting user in the empty string, remove two characters to compensate for the user character
Avoid using single letter l (L) as a variable. It looks like the number 1 which caused some typos in your code
Some of the words have repeated letters so only the first letter instance will be found
Set a variable to maintain the current state of the guess word so each correct guessed letter fills in a blank
This code seems to work correctly:
import random
allthewords =['ability','absence','academy','account','accused','achieve','acquire','address','advance','adverse','advised','adviser','against','airline','airport','another','ancient','auction',
'average','backing','balance','article','barrier','capable','banking','bedroom','caliber','capital','bearing','beating','calling','captain','battery','because','anxious']
random =(random.randrange(0,len(allthewords)))
randomwords = (allthewords[random])
letters=(len(randomwords))
print(randomwords) # for testing
hintnum=input("how many number of letter you want the hint of? ("+str(letters)+" is maximum): ")
hint= ''.join(randomwords)
hint1= hint[0:int(hintnum)]
while hintnum > str(letters):
print("sorry "+str(letters)+" is maximum")
hintnum=input("how many number of letter you want the hint of? ("+str(letters)+" is maximum): ")
print(" ")
hint= ''.join(randomwords)
hint1= hint[0:int(hintnum)]
print(" ")
l= input("how many number many lives you want?: ")
lives = int(l)
live = 1
print("hint: " +hint1 + " is in the word")
x=1
place= -1
wordstate = " "*len(randomwords) # start all blank
while x==1:
user =input("whats your letter?: ")
print("hint: " +hint1 + " is in the word")
# find letter in word with blank in wordstate
for i in range(len(wordstate)):
if wordstate[i] == " " and randomwords[i] == user: # letter found
wordstate = wordstate[:i] + user + wordstate[i+1:] # udpate display word
print('.'.join(wordstate.replace(" ","_"))) # print word with periods
print("its correct")
if wordstate.find(' ') == -1: # no spaces remaining, word done
print("You win!")
exit()
break # found letter
##############
if not user in randomwords:
lives=lives-1
print("wrong answer try again!")
print(" ")
if lives == 0:
print("you lost!, too many tries ")
x= x-1
a=input("do you want to know the answer?: yes/no")
if a==("yes"):
print(randomwords)
if a==("no"):
print("ok,thanks")
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 4 years ago.
I have just started to learn coding. This is a simple number guessing game that I created with Python. It works fine but I feel like the code can be simplified/optimized so it looks more neat. Another thing is that every time I try to input a non-integer, an error occurred. Is there a way to check if the user input is an integer or not and then proceed to the next step only if it is an integer. Thank you in advance!
from random import randint
random_number = randint(1, 10)
guesses_taken = 0
print ("Hello! What is your name?")
guess_name = input()
print ("Well, " + guess_name + ", I am thinking of a number between 1-10.")
while guesses_taken < 4:
print ("Take a guess!")
guess = int(input())
if guess not in range(1, 11):
print ("Oops! That's not an option!")
elif guess == random_number:
print ("You're right! Congratulations!")
break
else:
guesses_taken += 1
if guesses_taken < 4:
print ("Nope! Try again,")
else:
print ("Out of chances. You lose.")
You could use a try except block, to check if the value is an integer and throw an error/user message if not, (this would go where you have guess = int (input())
something like:
try:
val = int(guess)
except ValueError:
print("Please enter an Integer")
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!
#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()
print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)
#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
guess = int(input())
if type(guess) != int:
print ("You did not enter a number, please re-enter")
continue
if guess < secretNumber:
print ("The number you guessed was too low")
elif guess > secretNumber:
print ("The number you guessed was too high")
else:
break
if guess == secretNumber:
print ("Oh yeah, you got it")
else:
print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))
print ("You took " + str(guessesTaken) + " guesses.")
Use a try and except:
for guessesTaken in range(1, 7):
try:
guess = int(input())
except ValueError:
print ("You did not enter a number, please re-enter")
continue
So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.
You can try a simple while loop that waits until the user has entered a digit. For example,
guess = input("Enter a number: ") # type(guess) gives "str"
while(not guess.isdigit()): # Checks if the string is not a numeric digit
guess = input("You did not enter a number. Please re-enter: ")
That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).
You can then convert the digit to an integer as before:
guess = int(guess)
For example, consider the following cases:
"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer
I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.