The assignment was to make a guessing game where the parameter is the answer. At the end if the person gets it right, it prints a congratulatory statement and returns the number of tries it took, if they type in quit, it displays the answer and tries == -1. other than that, it keeps looping until they get the answer correct.
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1
When i run it, no matter what i put in it just keeps asking me for my guess.
Since you called your variable num so I'm guessing it's a integer, you were checking equality between an integer and a string so it's never True. Try changing the num to str(num) when comparing, so:
def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1
Is the code properly indented?
The body of the function you are defining is determined by the level of indentation.
In the example you pastes, as the line right after the def has less indentation, the body of the function is 'empty'.
Indenting code is important in python
Additionally, for assigning one value to a variable you have to use a single '=', so the:
tries == -1
should be
tries = -1
if you want to assign the -1 value to that variable.
Related
When I run the code, the 3rd guess gives me an output of High/Low. On the 3rd try, I don't need it to tell me if I'm high or low. How can I fix the problem with out using "while" loops or "range." We haven't covered these two keywords yet.
python
print("You have 3 tries to guess the letter.")
letter = "F"
tries = 0
# [ ] create letter_guess() function, call the function to test
def letter_guess(tries):
if not tries == 3:
guess = input("Guess a letter: ")
tries = tries + 1
check = check_guess (guess,letter)
if check == True:
print('Winner')
else:
letter_guess(tries)
else:
print ("GAME OVER!")
pass
# def check_guess(guess,letter)
def check_guess (guess, letter):
#if else to see if correct letter
if letter == guess.upper():
print ("correct")
return True
elif letter < guess.upper():
print ("You are wrong, guess lower.")
return False
elif letter > guess.upper():
print ("You are wrong, guess higher.")
return False
else:
print("Invalid response!")
return False
letter_guess(tries)
One way to get result similar to a loop is to use recursion. But if you have not done loops yet, you almost certainly have not done recursion. So just use straightforward code.
The tricky part is that you need to ask for a guess, input the guess, and check for a correct guess three times, once for each guess. However, you need to give feedback on whether the guess is high or low only two times. Therefore, you cannot put those actions in the same function. Just split them into separate functions, and handle each guess in your main routine. No need to count guesses--the position in the main routine makes that clear.
"""Guess-a-letter game."""
def get_guess(letter):
"""Get a guess an note if it is correct. If correct, return None.
Otherwise, return the guess."""
guess = input("Guess a letter: ").upper()
if guess == letter:
print("Correct: You win!")
return None
else:
return guess
def give_feedback(guess, letter):
"""Give feedback on a wrong guess."""
if letter < guess:
print("You are wrong, guess lower.")
else:
print("You are wrong, guess higher.")
def letter_guess():
# Store the letter for the user to guess.
letter = "F"
# Introduce the game.
print("You have 3 tries to guess the letter.")
# Handle the first guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the second guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the third and last guess.
guess = get_guess(letter)
if guess is None:
return # Success!
print("You were wrong three times. GAME OVER!")
letter_guess()
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.
I am new to python and trying to write a program that requires the user to guess a number, 1 - 6 and then they are told if they guessed right or not. However, even when the user guesses right the else statement is still returned.
I apologise for the beginner question, although this really has me stuck because the 'guess' variable is being assigned correctly, I tested this by moving the print("Your guess was: ",guess) outside of the function and executed after the function was called which always returned with the same value that the user inputs.
#Function to take guess
def userGuess (guess):
guess = input("Take a guess.\n")
print("Your guess was: ",guess)
return guess
#Define Variables
diceNum = random.randint(1,6)
guess = 0
#Call Function
guess = userGuess(guess)
#Check answer
if guess == diceNum:
print("You guessed right!, the number was: ",diceNum)
else:
print("You did not guess it right, the number was: ",diceNum)
You need to convert the user input to an integer prior to comparing:
guess = int(input("Take a guess.\n"))
If you want an explanation as to why your if statement returned false for a comparison between an integer and a string, take a look at this question.
I am new to programming and I am having difficulty accumulating within a loop
wrong_guesses=0
formSoFar=''
game_over=False
while (game_over==False and wrong_guesses<max_guesses):
guess1= raw_input("Please enter an operation symbol or digit: ")
if (guess1 in formula):
print "Your guess is correct!"
for i in range (len(formula)):
if (randomFormula[i] == guess1):
formSoFar += formula[i]
else:
formSoFar+= "-"
print "The formula you have guessed so far is: ",formSoFar
Supposed the equation the user is trying to guess is 1+2+3 and their first guess is 2 the formSoFar is --2-- but the second time they guess it should show the first guess as well so if they guess 1 it should be 1-2-- but this code is printing--2--1-2--
please help :(
In each loop, you are appending characters to formSoFar. What you want to do instead is have it start with some value and edit it as you go:
formSoFar = ['-'] * len(formula)
while not game_over and wrong_guesses < max_guesses:
guess = raw_input(...)
if guess in formula:
for i, c in enumerate(formula):
if c == guess:
formSoFar[i] = c
print 'The formula you have guessed so far is:', ''.join(formSoFar)
Also note that you don't need ()s in an if statement. That's a C/C++/Java thing.
I've made a simple program where the users adds as many numbers as they would like then type 'exit' to stop it and print the total but sometimes it says the converting the string to int fails, and sometimes it does convert but then it has the wrong out put e.g I type 1 + 1 but it prints 1
def addition():
x = 0
y = 1
total = 0
while x < y:
total += int(input())
if input() == "exit":
x += 1
print(total)
addition()
I have tryed converting it to a float then to an int but still has inconsistency, I did start learning python today and am finding the syntax hard coming from c++ / c# / Java so please go easy on the errors
Maybe this is what you are looking for:
def addition():
total = 0
while True:
value = input()
if value == "exit":
break
else:
try:
total += int(value)
except:
print('Please enter in a valid integer')
print(total)
EDIT
There are two reasons why the code isn't working properly:
First, the reason why it is failing is because you are trying to cast the word "exit" as an integer.
Second, as user2357112 pointed out, there are two input calls. The second input call was unintentionally skipping every other number being entered in. All you needed to do was one input call and set the entered value into a variable.
You can break the while loop, without using x and y.
def addition():
total = 0
while True:
total += int(input())
if input() == "exit":
break
print(total)
addition()
These are a few ways you can improve your code:
Run the loop forever and break out of it only if the user enters "exit"
To know when the user entered "exit" check if the input has alphabets with isalpha()
Making the above changes:
def addition():
total = 0
while True:
user_input = input()
if user_input.strip().isalpha() and user_input.strip() == 'exit':
break
total += int(user_input)
print(total)
addition()
def safe_float(val):
''' always return a float '''
try:
return float(val)
except ValueError:
return 0.0
def getIntOrQuit():
resp = input("Enter a number or (q)uit:")
if resp == "Q":
return None
return safe_float(resp)
print( sum(iter(getIntOrQuit,None)) )
is another way to do what you want :P