I know all my questions are really easy but I'm a beginner so here it is...
I have been developing the guessing number thing after everyones help, but I want to then return to a menu which has just been left. Here's the code:
import time
import random
animalmenu()
def animalmenu():
print()
print()
print()
print()
print('Welcome to the menu. I am thinking of a menu. Select the option\'s below to try and guess my animal.')
print()
print('a) No. of Legs')
print('b) Type of animal')
print('c) Preffered Climate')
print('d) Size')
print('e) Colour')
print('f) Diet')
print('g) Habitat')
print('h) Can be kept as pet')
print('i) Guess animal')
print()
print('When in a menu, type in \'555\' to return here')
AniChoice = input('Choose your option: ')
if AniChoice == 'a':
loop = 10
while loop == 10:
print()
print('')
print()
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
print('r = Return to menu, g = guess again.')
rg = input()
if rg == 'g':
print('Loading...')
elif rg == 'r':
loop = 0
time.sleep(1)
print('Returning to menu...')
time.sleep(1)
animalmenu()
everytime I run it, I type in a number as the code asks but then, instead of asking if I want to return to the menu it just asks the question again and again, 'Guess the number of legs: '. I know this is something to do with my looping method but I do not understand and because of the integer setting I cannot just make another if, like so:
guessleg = int(input('Guess the number of legs: '))
if leg == guessleg:
print('True')
elif leg != guessleg:
print('False')
elif guessleg == 'back':
loop = 0
animalmenu()
And I do not see any other way of doing it as neither way seems to work? How would you suggest returning to animalmenu()?
As the message is telling you, 'back' is not an integer, but you are comparing it to a variable into which you have put an integer value. Specifically, your line:
guessleg = int(input('Guess the number of legs: '))
puts an integer value into guessleg (or more properly tries to) from the user's input.
One approach to resolve this is to capture the user's input in a string variable, compare that string to 'back' first, and then convert to an integer if needed.
Another approach is to wrap a try/except around the integer conversion and proceed with the integer check if the conversion is successful and with the check against 'back' if the exception is encountered. This is probably preferred these days and I've put it into code:
inp_val = raw_input('Guess the number of legs: ')
try:
guess_num = int(inp_val)
if guess_num == leg:
print('True')
else:
print('False')
except ValueError:
if inp_val == 'back':
loop = 0
else:
print 'Invalid entry'
animalmenu()
because the you convert your input into integer and store it into guessleg which means guessleg is also an integer. However, 'back' is a string. You can't compare the string with integer. the 3 == 'back'means nothing.
and syntax error may because of your indent.
UPDATE:
if you want to return to the top menu, you can do something like:
def animalmenu():
while True:
print your menu here
and do something....
while ...:
get input and do something...
if get the input of 'back to menu':
break
UPDATE again:
I don't think you shall use input() here, try readline() or raw_input() instead.
Related
it seems to only recognise decimals as non digit value but if i wear to write a word it would say could not convert string to float-How do i fix this im new to programming
Try this
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = float(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
exit
elif selection<=0 or selection>4:
print("There is no menu",end=" ")
print(selection)
I've made a few changes to your code and added a few comments inline
# We start with None so that it enters the loop at least once
selection = None
# We create loop to keep asking the question until the user provides a number
while not selection:
selection=input("Select a menu- Input a number:")
# Check if the number is a decimal
if selection.isdecimal():
# I convert to an int since it's more natural
selection = int(selection)
# At this point, it will exit the loop
else:
# The user has intereed an incorrect value.
print("You have input a non integer value. Select again:")
# We empty selection so that it loops and asks the question again
selection = None
# Here we have an int
# If the selection is 1, 2 or 3, we display the menu. I use a list,
# but range(1, 3) would have worked too
if selection in [1, 2, 3]:
# Note I use an f-string here. You might not have learned about
# them yet. Requires at least Python 3.6
# This helps avoid repetition
print(f"::menu {selection}::")
elif selection==4:
# always call it like a function
exit()
else:
# Any other selection (remember, we know we have an int) should get this message
print(f"There is no menu {selection}")
Try this:
while True:
selection=input("Select a menu- Input a number:")
if not selection.isdigit():
print("You have input a non digit value. Select again:")
else:
selection = int(selection)
if selection==1:
print("::menu 1::")
elif selection==2:
print("::menu 2::")
elif selection==3:
print("::menu 3::")
elif selection==4:
print('Exiting...')
quit()
else:
print("There is no menu",end=" ")
print(selection)
I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,
if guess.isdigit():
guess = int(guess)
Please help
import random
a = random.randint(1,10)
print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")
if question_one == "Yes":
print("Let's go!")
else:
print("That sucks!")
exit()
guess = None
while guess != a:
guess = (input("Alright, guess a number from 1-10"))
if guess.isdigit():
guess = int(guess)
if guess > a:
guess = int(input("Guess lower!"))
elif guess < a:
guess = int(input("Guess higher!"))
else guess == a:
print("you got it!")
else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif. Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.
If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.
An else statement contains the block of code that executes if the conditional expression in all your if or elif statements is false. Hence in your case you're supposed to use the elif statement instead of else. See the following:
elif guess == a:
print("you got it!")
How do I make a specific line of code execute only once inside a while loop?
I want the line:
"Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.
Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")
You can create a flag variable, e. g.
print_username = True
before the while loop. Inside the loop uncheck it after loop's first iteration:
if print_username:
guess = input("Hello %s, please enter your guess: " % p1)
print_username = False
else:
guess = input("Try a new guess:")
You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.
To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:
# [start identical]
while guess != number and guess != "exit":
guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0
else "Try again: ")
# [rest identical]
See Does Python have a ternary conditional operator?
The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).
You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well
A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.
You should ask for the username outside of the loop and request input at the beginning of the loop.
Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)
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.
I have updated my code with the changes made. I am still getting incorrect results...
# Import statements
import random
# Define main function that will ask for input, generate computer choice,
# determine winner and show output when finished.
def main():
# Initialize Accumulators
tie = 0
win = 0
lose = 0
score = 0
# initialize variables
user = 0
computer = 0
# Initialize loop control variable
again = 'y'
while again == 'y':
userInput()
computerInput()
if score == win:
print('You won this round, good job!')
win += 1
elif score == tie:
print('You tied this round, please try again!')
tie += 1
else:
print('You lost this round, please try again!')
lose += 1
again = input('Would you like to play another round (y/n)? ')
#determine winning average
average = (win / (win + lose + tie))
print('You won ', win, 'games against the computer!')
print('You lost ', lose, 'games against the computer.')
print('You tied with the computer for', tie)
print('Your winning average is', average)
print('Thanks for playing!!')
# get user input for calculation
def userInput():
print('Welcome to Rock, Paper, Scissor!')
print('Please make your selection and and Good Luck!')
print('1) Rock')
print('2) Paper')
print('3) Scissor')
user = int(input('Please enter your selection here: '))
print('You selected', user)
# get compter input for calculation
def computerInput():
computer = random.randint(1, 3)
print('The computer chose', computer)
def getScore():
if user == 1 and computer == 3:
score = win
return score
elif user == 2 and computer == 1:
score = win
return score
elif user == 3 and computer == 2:
score = win
return score
elif user == computer:
score = tie
return score
else:
score = lose
return score
# Call Main
main()
In Python:
>>> print("3" == 3)
False
Strings and integers are values of different data types, and will not compare equal. Try changing your input to:
userInput = int(input('Please enter your selection here: '))
This will convert the string typed by the user to a number for later comparison. (Note that I have assumed you are using Python 3.x, because input() behaves slightly differently in Python 2.x.)
Note that this will throw an error if you type anything other than a number.
Update: As pointed out by #FelipeFG in the comments below, you are also overwriting the function userInput with the value typed by the user. You'll need to change the name of one or the other, for example:
def getUserInput():
...
Also don't forget to change the place where you call the function. Do the same for computerInput (change to getComputerInput).
Later on, you can change those to actual functions that return values.
userInput() calls the function "userInput", but you discard the result. The same remark applies to computerInput().
userInput == 1 asks whether the function userInput itself is equal to 1. It isn't. The same remark applies to computerInput == 3 and the others.
In the function "userInput", userInput = ... binds the name "userInput" to the result of the expression. This makes "userInput" a local variable of the function. The function doesn't explcitly return anything, therefore it returns None.
If you're using Python 3, input returns a string, and you should convert its result to an int. If you're using Python 2, input evaluates whatever is entered, which isn't safe; you should use raw_input instead and convert its result to an int.
You need to compare against the return value of your function, not the function itself.
Also:
again = input('Would you like to play another round (y/n)? ')
This will throw an exception if you enter y or n, because there is no defined identifier of that name! What you want to use instead is raw_input()
Edit: As pointed out by Greg, this only applies to Python 2.x. You seem to be using Python3 though.