Guessing a number, true or false? Python - python

I want to assign something a value and then try and get someone to guess that value. I have tried something along the lines of this but I can't seem to get it to work...:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
if foo != guessfoo:
print('haha, fail.')
Why doesn't this work? And how should I be doing it? I am a beginner at this, please help!

With python version 3 :
input() returns a 'str' (string) object. A string compares to an integer returns False :
1 == '1'
False
You must cast your input like that :
guessfoo = int(input('Guess my number: '))
Don't forget to try...except if the result of the input cannot be casted into an int.
Full example code :
try:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
else:
print('haha, fail.')
except ValueError:
# cannot cast your input
pass
EDIT:
With python version 2 :
Thanks for this comment :
In previous versions, input would eval the string, so if the user typed in 1, input returned an int.
Ouput or your original code:
$ python2 test.py
Guess my number: 1
Well done, You guessed it!

Currently you have no condition to stop the loop. You're just printing stuff. Put a break after you guessed the number, or set loop to a different value than 1.

Because integers (foo) aren't strings (result of input()).
If you think that Python behaves like PHP or Perl then you are wrong
1 is something completely different than '1'.
You have to either convert the string using int(..) to an int or check against 'foo'
as a string.

It looks like the first problem will be an infinite loop, since the condition you're checking each iteration will always be true with the above code. When you loop, you need to make sure you change something that will bring loop closer to that condition. As a start, your code should look like this:
loop = 1
while loop == 1:
foo = 1
guessfoo = input('Guess my number: ')
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
if foo != guessfoo:
print('Oh no, try again')
This will cause the loop to finish executing if the number is actually guessed.
The next problem is that input returns a String, so the check to see if the entered number is equal to the expected number will always fail. In python, use the int() function to convert a string to a number, so that line looks like:
guessfoo = int(input('Guess my number: '))
At this point, you should have a decently-working loop. However, there are a few things you could do to make your code simpler. Here are some suggestions, starting with the simplest tweaks and moving to cleaner code.
The first step could be to use if...else to make sure only one condition is executed, and you only have to check the value of foo once. If the condition is true, the first branch is executed; if it fails, execution proceeds to the else block.
loop = 1
while loop == 1:
foo = 1
guessfoo = int(input('Guess my number: '))
if foo == guessfoo:
print('Well done, You guessed it!')
loop = 0
else:
print('Oh no, try again')
This works, but we can also move the check for a correct result in the condition of the loop. This way, the program only loops until the number is displayed:
foo = 1
guessfoo = 0
while foo != guessfoo:
guessfoo = int( input( 'Guess my number: ' )
if guessfoo != foo:
print( 'Oh no, try again' )
print( 'Well done, You guessed it!' )
Now the success message will only be displayed when foo == guessfoo. This loop is a bit clearer and simpler.
As a beginner, you've chosen a great place to ask for help! Welcome to StackOverflow!

Also, should you be using two different if's?
shouldn't it be something more like
if foo == guessfoo:
print('Well done, you guessed it!')
else:
print('haha, fail.')

import random
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
foo = random.randint(1,10)
while True:
guess = int(inp('Guess my number: '))
if guess < foo:
print('Too low!')
elif guess > foo:
print('Too high!')
else:
print('You got it!')
break

Related

Python How to break loop with 0

I don't understand why is not working on my code
def random_calculation(num):
return((num*77 + (90+2-9+3)))
while random_calculation:
num = int(input("Pleace enter number: "))
if num == "0":
break
else:
print(random_calculation(num))
Can you guide me what is wrong here, i really dont understand
You have several errors in your code:
You cannot do while random_calculation like this. You need to call the function, but since inside the loop you are already checking for a break condition, use while True instead.
Also, you are converting the input to int, but then comparing agains the string "0" instead of the int 0
Here's the corrected code:
def random_calculation(num):
# 90+2-9+3 is a bit strange, but not incorrect.
return((num*77 + (90+2-9+3)))
while True:
num = int(input("Please enter number: "))
if num == 0:
break
# you don't need an else, since the conditional would
# break if triggered, so you can save an indentation level
print(random_calculation(num))
so,when you start the loop it ask you what number you want to enter and then the code checks if the number is == to 0. IF the number is equal to 0: break the loop. IF the number is equal to any other number it prints the "random_calculation" function

Why isn't my program noticing the equivalency between letters?

I am working on making a simple game of Hangman in Python 2. The code I have so far is the ground work I have for it, but it doesn't seem to be working. If I could have a simple wake-up call as to what about what code I made isn't working I would appreciate it.
Code:
secret_word = 'tracy'
secret_word_list = []
for letter in secret_word:
secret_word_list += letter
print secret_word_list
def get_guess(guess = input("Guess: ")):
while len(guess) != 1:
print "Your guess must be exactly one character!"
guess = input("Guess: ")
while guess.isalpha() == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
while guess.islower == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
else:
return guess
while True:
if str(get_guess) in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
get_guess(guess = input("Guess: "))
Output:
Output of the Code
You've got several problems here, but the big one is that you're not calling functions, so you compare the function itself to the secret.
Code with fixes:
secret_word = 'tracy' # Don't make secret_word_list, there's no point; just use the str itself since you only test len 1 strings against it anyway
print secret_word
def get_guess(guess): # Don't make the default call input, that'll prompt once for an input and store it as the permanent default
while True:
# Test each condition and break loop only if all past; original code would never
# recheck length if new value entered after testing isalpha
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower(): # Add missing call parens on islower; use not, never compare to False; islower implicitly verifies isalpha, so avoid testing isalpha
print "Your guess must be a lowercase letter!"
else:
break # Passed all tests, break loop
# Get new guess if any test failed
guess = raw_input("Guess: ") # Use raw_input on Python 2, never input (which eval's the result of raw_input)
# Removed else (loop always ends by breaking, using else nonsensical but harmless in original code too
return guess
while True:
# Move guess getting to if, because having it in else case never actually checked it
if get_guess(raw_input("Guess: ")) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
Try it online!
Note: I kept the kinda odd behavior of having get_guess take an argument, but then reprompt for guesses on failure. A saner solution would be to remove the guess argument entirely, and move the guess = raw_input("Guess: ") to the top of the while loop (removing the else block at the end).
get_guess is a function, you need to put () after it to call the function.
You shouldn't put the call to input() as a default argument. The default value is evaluated once, when the function is defined, not every time the function is called. You should assign guess inside the function.
You should test for all the invalid inputs in a single loop.
def get_guess():
while True:
guess = input("Guess:")
if len(guess) != 1:
print "Your guess must be exactly one character!"
continue
if not guess.isalpha() or not guess.islower():
print "Your guess must be a lowercase letter!"
continue
break
return guess
while True:
guess = get_guess()
if guess in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"

How do you use an if statment to only except integers and give an invalid entry message?

I'm making a simple guessing game in python and was trying to create an "Invalid entry" message for when the user enters in any input that is not an integer.
I have tried to use just 'int' in an if statement to address all integers, but that is not working.
I know that I have the syntax wrong. I'm just not sure what the correct syntax to do it would be.
import random
play = True
while play:
count = 1
hidden = random.randrange(1,5)
guess = int(input("Guess a number between 1 and 5:"))
if guess != int
guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))
while guess != hidden:
count+=1
if guess > hidden + 10:
print("your guess is to high!")
elif guess < hidden -10:
print("your too low!")
elif guess > hidden:
print("your really warm, but still to high!")
elif guess < hidden:
print("your really warm, but still to low")
print("You have guessed incorrectly, Try again!. \n")
#reset the guess variable and make another guess
guess = int(input("Guess a number between 1 and 5:"))
print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")
count = 1
playagain = str(input("Do you want to play again?\nType yes or no: "))
if playagain == "no" or "n" or "N" or "no thank you":
play = False
elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
play = True
else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
playagain = str(input("Invalid Entry. Please Type yes or no: "))
This is the error that I'm getting. There may be some other mistakes in my code as well.
File "comrandomguess.py", line 18
if guess != int
^
SyntaxError: invalid syntax
If you really want to verify that the user entry is an int, you want to keep the input in string form. Then write a small function to test the input. Here, I'll use a list comprehension and the string join and isdigit methods, to ensure the user has only entered digits 0-9 in the string, i.e. then this function returns True (else False) (*modified as per Jack Taylor comment below, also for s = '' case):
def testForInt(s):
if s:
try:
_ = s.encode('ascii')
except UnicodeEncodeError:
return False
test = ''.join([x for x in s if x.isdigit()])
return (test == s)
else:
return False
If you want to sandbox the user entirely, wrap it in a loop like this:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
if testForInt(entry):
entry = int(entry)
acceptable = True
else:
print("Invalid Entry")
If you want a simpler version with no function call(see Jack Taylor comment), this works too:
acceptable = False
while not acceptable:
entry = input("Enter an int: ")
try:
entry = int(entry)
acceptable = True
except ValueError as e:
print(f"Failed due to {str(e)}")
Now you've got what you know is an int, with no worries. This kind of approach to verifying user entry saves many headaches if consistently implemented. See SQL injection etc.
I always use this method to check if something is not an integer:
Python 3
if not round(guess) == guess: print("Do Stuff")
Python 2
if not round(guess) == guess: print "Do Stuff"
You need to do something like this:
play = True
while play:
guess = input("Guess a number between 1 and 5: ")
try:
number = int(guess)
except ValueError:
print("You need to input an integer.")
continue
if number < 1 or number > 5:
print("You need to input an integer between 1 and 5.")
continue
# ...
print("Your number was: " + guess)
play = False
When you first use input(), you get a string back. If you try to turn that string into an integer straight away by doing int(input()), and if the player types a string like "abcd", then Python will raise an exception.
>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'
To avoid this, you have to handle the exception by doing int(guess) inside a try/except block.
The continue statement skips back to the start of the while loop, so if you use it you can get away with only having to ask for input once.
Parse the user input as string to avoid ValueError.
guess = input("Guess a number between 1 and 5: ")
while not guess.isdigit() or int(guess) > 5 or int(guess) < 1:
guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")
guess = int(guess)
Above code ensures that user input is a positive integer and between 1 and 5. Next, convert the user input to integer for further use.
Additionally, if you want to check the data type of a python object/variable then use the isinstance method. Example:
a = 2
isinstance(a, int)
Output:
>>> True

Why does this print the error message twice?

New to stackoverflow, and new to python (python-3). Currently learning on edx.org and ran into the following error.
I created a function that checks a user-input str against the answer str and returns True or False.
When testing the function, I created a while loop to stop at the 3rd unsuccessful attempt. However, whenever there is an unsuccessful attempt, the function prints the error message twice when it should only print it once.
I fixed the error by storing the returning Bool value of the function into a variable rather than calling the function directly in the if condition within the while loop. However, I would like to understand the logic behind the error message printing twice. Here is the original code that prints the error message twice :
def letter_guess(letter, guess):
if len(guess) == 1 and guess.isalpha() and guess < letter:
print(guess,"is lower than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess > letter:
print(guess,"is higher than the answer. Try again.\n")
return False
elif len(guess) == 1 and guess.isalpha() and guess == letter:
print("Correct answer!")
return True
else:
print("Please only enter one alphabet for the letter. Try again.\n")
return False
answer2 = "m"
guess2 = input("Please enter a single alphabet : ")
i = 0
while i < 3:
if letter_guess(answer2, guess2):
break
elif letter_guess(answer2, guess2) == False and i == 2:
print("You have reached 3 guesses. Game over.")
break
else:
i += 1
guess2 = input("Please guess again : ")
You want to call input() inside the while loop:
# ...
answer2 = "m"
i = 0
while i < 3:
guess2 = input("Please enter a single alphabet : ")
# ...
Otherwise the user doesn't have a chance to change their answer, guess2 never changes and they get the same error message multiple times.
You call the function twice, in first if and in elif, with the same wrong guess. You fixed it right calling only once and storing the return value.
I try to explain it better: the function is always called by the first if, to evaluate its condition; if return value is false, is called again to evaluate the elif condition, with same arguments as before.

Python While loop won't exit when asked to

I don't understand why when the user enters "0" the loop won't exit.
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
if integerIn == "0":
done = True
else:
integers.append(integerIn)
return integers
def floatInput():
done = False
while not done:
integerIn = input("Please enter an integer < 0 to finish >: ")
try:
integerIn = int(integerIn)
except:
print("I was expecting an integer number, please try again...")
import sys
sys.exit()
Everything above here is fine, but as soon as you got to the comparison, you forgot that you've casted the input to an int.
if integerIn == "0":
Should be
if integerIn == 0:
The reason is because integerIn is an integer and you are treating it like a string in if integerIn=="0". Replace it with integerIN==0 will do the job.
You're converting to an integer and then checking for equality with the string "0".
EDIT: screw the advice about using input or raw_input. Just saw you python 3.x tag, but decided to leave it for future readers.
You have few problems there...
First, in this line:
integers.append(integerIn)
where is integers to begin with? unless it's a global name you must define it in your function.
Second, in this line:
if integerIn == "0":
you're comparing integer to string here, and here's a thing: in python (using python 2.7 here) a string will be bigger than any number if you're doing a comparison, so integerIn == "0" will evaluate to False, always.
Fix it with this:
if integerIn == 0:
Finally, I should tell you this... your code the way it looks like will throws NameError instead of executing what you've done in your except statement.
Try it with the following test cases and try to explain the behavior yourself :)
Please enter an integer < 0 to finish >: test
Please enter an integer < 0 to finish >: "test"
To avoid such problem next time, use raw_input instead of input. So this line:
integerIn = input("Please enter an integer < 0 to finish >: ")
should be like this:
integerIn = raw_input("Please enter an integer < 0 to finish >: ")
NOTICE: I'm not sure but I think raw_input doesn't exist in python 3.x, instead input there will do exactly the same. please correct if I'm wrong.
However, If you're using python 3 then I think you should have no problem.
Here's input vs raw_input() in python 2.x:
input will evaluate the user input then return it.
raw_input will return the user input as string.
so:
# python 2.x
foo = input("input something") # input 3 + 5
print foo # prints 8
bar = raw_input("input something") # input 3 + 5
print bar # prints "3 + 5"
Try this
if integerIn == 0:
should work now.

Categories

Resources