IF statement skipped-Python 2.7 - python

The first IF statement is being ignored and I have no idea what could cause this. I checked the indentation and everything seems fine.As you can see in the code it prints numberRolled but when I run it it justs ignores the first IF.`
import random
numberRolled = random.randint(1,6)
print numberRolled
while True:
userGuess = raw_input("Guess a number\n")
if userGuess == numberRolled:
print "You got it right!"
quitYN = raw_input("Would you like to play again?\n").lower()
if quitYN == "yes":
continue
else:
break
elif userGuess != numberRolled:
print "Wrong!"`

raw_input() returns a string, but random.randint() returns an int. This means that when doing userGuess == numberRolled you are comparing a string to an int (which returns False).
To fix this simply convert one of the variables to the correct type:
userGuess == str(numberRolled)
Take a look at this answer for more information about variable types and how to compare them in python.

Related

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

Python, How do I use a string in a while loop and then an if statement?

I cannot figure out why this won't work, I have gone as far as to apply integer variables, I would prefer to keep it purely to strings. I'm new, what am I doing wrong?
x = int(2)
y = int(1)
while userinput != (1,2):
userinput = input("Do you wish to continue, to start from scratch?")
if input == 1:
print("y")
if input == 2:
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
I presume you want to check directly on the "y" and "n" characters, note that, among the other things, in your code you are checking the wrong input, you should check the variable userinput that you assign in the loop with the user input.
Here is a working example, note that i convert to lowercase in order to accept both "y\n" and "Y\N" with a single if statement.
userinput = ""
while (userinput !="y" and userinput !="n"):
userinput = input("Do you wish to continue, to start from scratch?").lower()
if userinput == "y":
print("y")
elif userinput == "n":
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
EDIT: if statement fixed as suggested by #Kumar

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.

Bagel Pico fermi error?

Current code may have more bugs than I see at the moment, but what I am trying to fix is the get_guess() function. At the moment I have coded it to print i in the "for i in range..." because whenever I input a guess, it automatically assumes i = 0 and prints "You can only guess numbers." I'm not sure why, when 0 is part of the list of numbers that it is supposed to check. Any ideas on how to fix this?
Side note, things are indented correctly, I am just not used to the formatting of this website.
import random
def explain_instructions():
print("I am thinking of a number with nonrepeating digits. You will have 10 attempts to try and guess my number.")
print("'Bagel' will be displayed if no digits are correct.")
print("'Pico' will be displayed if a digit is correct but in the wrong place.")
print("'Fermi' will be displayed if a correct digit is in the correct place.")
def generate_number(length):
num_list = [0,1,2,3,4,5,6,7,8,9]
random.shuffle(num_list)
secret_num = num_list[0:length]
secret_num = "".join(str(digit) for digit in secret_num)
return secret_num
def give_clues(secret_num, guess):
clues = []
for i in range(len(str(guess))):
if guess[i] == secret_num[i]:
clues.append("Fermi")
elif guess[i] in secret_num and guess[i] != secret_num[i]:
clues.append("Pico")
if clues == []:
clues.append("Bagel")
return(clues)
print(clues)
def get_guess(length, guess):
for i in range(int(length)):
if guess[i] in guess[:i] or guess[i] in guess[i+1:]:
print("Repeating numbers don't work in this game.")
return
elif len(guess) != len(secret_num):
print("You don't have the correct number of digits.")
return
elif guess[i] not in num_list and guess != "":
print(i,"You can only guess numbers.")
return
else:
return int(guess)
def play_again():
print("Would you like to play again? (Yes/No)")
answer = input()
if answer.lower()== "yes":
return True
else:
print("That wasn't a firm 'yes' so.... goodbye :( ")
print("Welcome to Bagel, Fermi, Pico!")
explain_instructions()
num_list = [0,1,2,3,4,5,6,7,8,9]
game_is_done = False
while True:
print("How long would you like your number to be?")
length = input()
secret_num = generate_number(int(length))
print(secret_num)
max_guess = 0
while max_guess < 10:
print("Enter a", length, "digit guess:")
guess = input()
if guess == "411":
print(explain_instructions())
elif get_guess(length,guess):
max_guess += 1
clue = give_clues(secret_num,guess)
print(clue)
if clue == ['Fermi'] * len(secret_num):
print("Congrats! You guessed the correct number!")
break
if max_guess == 10:
print("Oh no! You have run out of guesses. The secret number was:", secret_num)
if not play_again():
break
I think it might be because you are declaring num_list inside the function
generate_number(length)
So when you ask for num_list outside the function, python has no idea what num_list is. Declaring it as a global variable could solve your problem (haven't tested it, though)
And yes, i = 0 because it's the iterator, not the number you've guessed. If you want to see your guess, write
print(guess[i],"You can only guess numbers.")
I would be careful with a couple things, nontheless
1. Specify that the input has to be a string. If you input an int without the quotes, it crashed (at least for me it crashed), or cast it to string before passing it to the function. It crashed when trying to access the array guess[i]
2. Be careful with digits that start with 0 (e.g. 02). Casting to int will transform it to 2 if you don't specify otherwise.

Categories

Resources