I would like to generate a number between 1 and 6 and have the user guess it. The check function, as in if input == variable: is not working.
global count
count = 0
def guess():
a = random.randint(1,6)
print (a)
ffs =input ("whats my nr?")
if ffs == (a):
print ("Correct")
sys.exit()
else:
global count
print ("guess again")
count +=1
print ("you have attempts remaining")
def mainz():
while count < 6:
guess()
mainz()
First of all your mainz() function and your mainz() call are in the guess() function but I guess that it's just a formatting error. The real error resides in the fact that input returns a string which you are trying to compare to an int. I would recommend simply doing this:
ffs = int(input("What's my nr? ") )
global count
count = 0
def guess():
a = random.randint(1,6)
print (a)
ffs =input ("whats my nr?")
if ffs == str(a):
print ("Correct")
sys.exit()
else:
global count
print ("guess again")
count +=1
print ("you have attempts remaining")
def mainz():
while count < 6:
guess()
mainz()
Needed str(a)
Related
i'm trying to make a guessing game, and i want to give the user 5 chances, but the loop keeps going after the chances given if the answer is incorrect.
if the answer is correct the program will print the losing text
i think the problem is with the value of full but the solutions i've tried broke the code
def proceso(ingreso, correcto, usos, usos_completos, usos_visibles, full):
if usos < usos_completos:
while ingreso != correcto and not full:
print("you have " + str(usos_visibles) + " chances")
ingreso = input("guess the word: ")
usos += 1
int(usos_visibles)
usos_visibles -= 1
else:
full = True
if full:
print("you lost. Correct answer was: " + correcto)
else:
print("you won")
palabra_secreta1 = "cellphone"
palabra_ingresada = ""
oportunidades = 0
limite_oportunidades = 5
contador_visible = 5
sin_oportunidades = False
print("5 oportunities")
proceso(palabra_ingresada, palabra_secreta1, oportunidades, limite_oportunidades, contador_visible, sin_oportunidades)
You should use break if the correct word is inputted and then count the number of chances taken in the while loop and then use else to print if the correct input has not been given after the desired number of attempts. I've removed some arguments because they seemed to be the same and I'm not sure what they mean, but maybe they're useful? Also, you should use f-strings for formatting variables into strings:
def proceso(correcto, usos_completos):
usos = 0
while usos != usos_completos:
print(f"you have {usos_completos-usos} chances")
ingreso = input("guess the word: ")
if ingreso == correcto:
print("you won")
break
else:
usos += 1
else:
print(f"you lost. Correct answer was: {correcto}")
palabra_secreta1 = "cellphone"
limite_oportunidades = 5
print("5 oportunities")
proceso(palabra_secreta1, limite_oportunidades)
GUESSING GAME
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
get_user_guess()
if get_user_guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
Here is the code. I made a running version in python 2, but translating it to python 3 has been a headache. I have defined that get_user_guess, where guess = an int. But further down in the roll_dice section, after I have called on the previous function and its answer I'm getting error messages.
That's not how you access the return value of a function. You should assign the return value to a new name, then use that in the following comparisons.
guess = get_user_guess()
if guess > 13:
print("invalid guess")
else:
...
if guess == total_roll:
print("Congratulations")
else:
print("sorry")
So, this seems like a small logic error and a syntax error as well. First the syntax error. You're not really initializing or calling the function in the comparison by doing:
if get_user_guess > 12
rather than doing:
if get_user_guess() > 12
So there is nothing for the ">" operator to compare against.
Second, seeing as you're trying to reuse the variable for the next comparison.You will need to store it as well otherwise it would prompt the user again for a new value again. Note the changes in lines 13,14 and 28 will fix it:
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
guess = get_user_guess()
if guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
I am creating a guessing game and I have created two functions. One to take the user input and the other to check whether the user input is correct.
def getGuess(maxNum):
if maxNum == "10":
count=0
guess = -1
guessnum = [ ]
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
guesses.append(guess)
return guesses
return guess
def checkGuess(maxNum):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
print (guesses)
and the main code is
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
while guess != num1:
getGuess("10")
checkGuess("10")
count = count+1
print (guess)
Although the function returns the users guess the code always takes the guess as 11. If I don't define guess, it doesn't work either. Please help.
First, you are returning two values. A return statement also acts as a break, so the second return will not be called. Also, you are not storing the returned value anywhere, so it just disappears.
Here is your edited code:
def getGuess(maxNum):
if maxNum == "10":
guess = -1
while guess >10 or guess<0:
try:
guess=int(input("Guess?"))
except:
print("Please enter valid input")
return guess
def checkGuess(maxNum, guess, num1):
if maxNum == "10":
if guess>num1:
print("Too High")
elif guess<num1:
print ("Too Low")
else:
print("Correct")
return True
return False
if choice == "1":
count = 0
print("You have selected Easy as the level of difficulty")
maxNum= 10
num1=random.randint(0,10)
print (num1)
guess = 11
guesses = []
while guess != num1:
guess = getGuess("10")
guesses.append(guess)
hasWon = checkGuess("10", guess, num1)
if hasWon:
print(guesses)
break
count = count+1
You have selected Easy as the level of difficulty
2
Guess?5
Too High
Guess?1
Too Low
Guess?2
Correct
[5, 1, 2]
>>>
You have a programming style I call "type and hope". maxNum seems to bounce between a number and a string indicating you haven't thought through your approach. Below is a rework where each routine tries do something obvious and useful without extra variables. (I've left off the initial choice logic as it doesn't contribute to this example which can be put into your choice framework.)
import random
def getGuess(maxNum):
guess = -1
while guess < 1 or guess > maxNum:
try:
guess = int(input("Guess? "))
except ValueError:
print("Please enter valid input")
return guess
def checkGuess(guess, number):
if guess > number:
print("Too High")
elif guess < number:
print("Too Low")
else:
print("Correct")
return True
return False
print("You have selected Easy as the level of difficulty")
maxNum = 10
maxTries = 3
number = random.randint(1, maxNum)
count = 1
guess = getGuess(maxNum)
while True:
if checkGuess(guess, number):
break
count = count + 1
if count > maxTries:
print("Too many guesses, it was:", number)
break
guess = getGuess(maxNum)
A couple of specific things to consider: avoid using except without some sense of what exception you're expecting; avoid passing numbers around as strings -- convert numeric strings to numbers on input, convert numbers to numeric strings on output, but use actual numbers in between.
am trying to teach myself Python and am building myself a basic hangman game. I've got a little way but now I'm stuck.
I've tried to put the bulk of the 'counter' for guessing in one function and then reference another function to actually work out whether the guess is correct or not.
So here is my counter function:
def game(generated_word):
hangman_lst = []
guess_num = 0
for i in range(0, len(generated_word)):
hangman_lst.append("__")
print(" ".join(hangman_lst))
while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
guess(l, random_word_stripped, hangman_lst, guess_num)
if "__" not in hangman_lst:
print("**Ta-da!** You're a winner!")
and here is my function to work out whether the guess is correct or not:
def guess(ltr, word, lst, try_num):
upper_ltr = ltr.upper()
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
elif len(upper_ltr) < 1:
print("You didn't enter a letter, try again:")
print(" ".join(lst))
elif upper_ltr in lst:
print("You already guessed that letter, try again:")
print(" ".join(lst))
elif upper_ltr not in word:
print("Sorry, that's incorrect. Try again.")
print(" ".join(lst))
try_num += 1
return try_num
else:
for n in range(0, len(word)):
if word[n] == upper_ltr:
lst[n] = upper_ltr
print("Nice job. That's one. You get a bonus guess.")
print(" ".join(lst))
return lst
So it kind of works, in that the hangman word is updated with the letters as they are guessed. But I can't get the counter to work - guess_num seems to always stay on 0 and so it always loops through this part:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
guess(l, random_word_stripped, hangman_lst, guess_num)
But, it seems as if lst is returned ok from the guess function, so why isn't try_num?
Cheers!
You need to increment guess_num. Adding guess_num = guess_num + 1 at the end of the while loop would fix this, but you only want guess_num incremented on a bad guess, so you would do something like this. (I haven't tested this)
while "__" in hangman_lst:
if guess_num == 0:
l = input("This is your first guess. Guess a letter!")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1
elif guess_num == 9:
print("Sorry - you lose!")
print("The word was " + str(random_word_stripped))
break
else:
l = input("This is guess #" + str(guess_num + 1) + ":")
if guess(l, random_word_stripped, hangman_lst, guess_num):
print("good guess")
else:
guess_num += 1
And then in your guess function you need to add the line return True or return False to return the appropriate True/False value depending on if there guess was valid.
So the part of the guess function that goes
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
Will need to be changed to
if len(upper_ltr) > 1:
print("That's more than 1 letter, try again:")
print(" ".join(lst))
return False
And then you will do this for each of the if conditions. As soon as python sees a return statement it will exit the function and will return whatever you tell it to return which in our case will be either True or False.
When you use the return keyword, that indicates that you're trying to a give a computed value back to the function's caller. Since with return you are giving the caller back a value, you would expect to assign that value to something once the function is completed...something you aren't doing.
In case you don't understand, here is an example...
Say I have my main function calling a function called add(), and say I want this function to compute the value of two integers being passed in. Then, I would have to return the computed value back to the caller for further use.
def main():
a = 5
b = 20
sum = add(a, b)
print(sum)
def add(num1, num2):
return num1 + num2
THEN, this code would print the value of a + b, or in this case, 25.
This code is from a small game i've been working on over the past day or so, i know i shouldn't really post the whole code but i'm not entirely sure which part of the code is not working as intended, any help would be appreciated. the code is a hangman game and i am aware of the huge amount of repetition in the code but am unsure how to reduce it to one of every function that will work with each difficulty setting.
import random
import time
#Variables holding different words for each difficulty
def build_word_list(word_file):
words = [item.strip("\n") for item in word_file]
return words
EASYWORDS = open("Easy.txt","r+")
MEDWORDS = open("Med.txt","r+")
HARDWORDS = open("Hard.txt","r+")
INSANEWORDS = open("Insane.txt", "r+")
easy_words = build_word_list(EASYWORDS)
medium_words = build_word_list(MEDWORDS)
hard_words = build_word_list(HARDWORDS)
insane_words = build_word_list(INSANEWORDS)
#Where the user picks a difficulty
def difficulty():
print("easy\n")
print("medium\n")
print("hard\n")
print("insane\n")
menu=input("Welcome to Hangman, type in what difficulty you would like... ").lower()
if menu in ["easy", "e"]:
easy()
if menu in ["medium", "med", "m"]:
med()
if menu in ["hard", "h"]:
hard()
if menu in ["insane", "i"]:
insane()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
def difficulty2():
print("Easy\n")
print("Medium\n")
print("Hard\n")
print("Insane\n")
print("Quit\n")
menu=input("Welcome to Hangman, type in the difficulty you would like. Or would you like to quit the game?").lower()
if menu == "hard" or menu == "h":
hard()
elif menu == "medium" or menu == "m" or menu =="med":
med()
elif menu == "easy" or menu == "e":
easy()
elif menu == "insane" or menu == "i":
insane()
elif menu == "quit" or "q":
quit()
else:
print("Please type in either hard, medium, easy or insane!")
difficulty()
#if the user picked easy for their difficulty
def easy():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
print ("the word was, ", word)
difficultyEASY()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyEASY()
#if the user picked medium for their difficulty
def med():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10:
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyMED()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyMED()
#if the user picked hard for their difficulty
def hard():
global score
print ("\nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyHARD()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyHARD()
#if the user picked insane for their difficulty
def insane():
global score
print ("This words may contain an apostrophe. \nStart guessing...")
time.sleep(0.5)
word = random.choice(words).lower()
guesses = ''
fails = 0
while fails >= 0 and fails < 10: #try to fix this
failed = 0
for char in word:
if char in guesses:
print (char,)
else:
print ("_"),
failed += 1
if failed == 0:
print ("\nYou won, WELL DONE!")
score = score + 1
print ("your score is,", score)
difficultyINSANE()
guess = input("\nGuess a letter:").lower()
while len(guess)==0:
guess = input("\nTry again you muppet:").lower()
guess = guess[0]
guesses += guess
if guess not in word:
fails += 1
print ("\nWrong")
if fails == 1:
print ("You have", + fails, "fail....WATCH OUT!" )
elif fails >= 2 and fails < 10:
print ("You have", + fails, "fails....WATCH OUT!" )
if fails == 10:
print ("You Lose\n")
print ("your score is, ", score)
print ("the word was,", word)
score = 0
difficultyINSANE()
def start():
Continue = input("Do you want to play hangman?").lower()
while Continue in ["y", "ye", "yes", "yeah"]:
name = input("What is your name? ")
print ("Hello, %s, Time to play hangman! You have ten guesses to win!" % name)
print ("\n")
time.sleep(1)
difficulty()
else:
quit
#whether they want to try a diffirent difficulty or stay on easy
def difficultyEASY():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
easy()
#whether they want to try a diffirent difficulty or stay on medium
def difficultyMED():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
med()
#whether they want to try a diffirent difficulty or stay on hard
def difficultyHARD():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
hard()
#whether they want to try a diffirent difficulty or stay on insane
def difficultyINSANE():
diff = input("Do you want to change the difficulty?. Or quit the game? ")
if diff == "yes" or difficulty =="y":
difficulty2()
elif diff == "no" or diff =="n":
insane()
score = 0
start()
When i run this code the error i get is:
Traceback (most recent call last):
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 316, in <module>
start()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 274, in start
difficulty()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 41, in difficulty
insane()
File "P:/Computer Science/Hangman All/Hangman v8.0.py", line 227, in insane
word = random.choice(words).lower()
NameError: name 'words' is not defined
I'm not sure what is wrong with words or how to fix it.
Your words variable is only defined in the scope of build_word_list function.
All the other functions don't recognize it so you can't use it there.
You can have a "quickfix" by defining it as a global variable, although usually using global variables isn't the best practice and you might want to consider some other solution like passing words to your other functions that use it or use it within the confines of a class.
(If avoiding global variables interests you, maybe you would like to read this and this)
You have words defined in the method build_word_list.
You should declare words as a global variable so that it can be accessed everywhere or restructure you program into a class and use self to reference it.