Unreliable nested while loops? - python

Im having a logic confusion here and don't know whether a solution is possible with my setup.
I am trying to prompt the user for (in order)
user answer y/n (originally set to 'y')
a bet (based on their current money)
a guess on a number 1-6.
Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.
My code below works, if the user answers with a valid guess all the time:
def roll():
return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]
# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0
# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
break
But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?
I've tried
if (int(guess) < 1 or int(guess) > 6):
guess = input('What number are you betting on? (number 1-6)')
at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.
Is my setup all wrong or how can I fix this?
Updated attempt:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
if(userAnswer.strip().lower() != 'y'):
break

From a quick glance your problem seems to lie in the fact that when you enter an invalid guessing number, you never enter the third and final loop.
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
If you enter in a number that is < 1 or > 6 then you will never enter the while loop and directly jump to the break that is in the end of the second while loop which sends you back to the very first loop and asks you how much you want to bet again.
Try removing the break in the second while loop and see what happens, the logic is currently not what you are looking for.

Alright - this was the right way to do it:
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while userAnswer.strip().lower() == 'y':
while True:
bet = int(input('You have $' + str(money) + '. How much would you like to bet?'))
if bet <=0 or bet > money:
print('Invalid bet - bet must be greater than 0 and less than '+str(money))
continue
# Valid bet entered
break
while True:
guess = int(input('What number are you betting on? (number 1-6)'))
if guess < 1 or guess > 6:
print('Invalid guess - you must enter a value 1-6')
continue
# Valid guess entered
break
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
else:
print('You lost your bet :(')
money += int(computeBetResult(theRoll, bet, guess))
userAnswer = input('Would you like to play again (y/n)?')

Change the while condition in the loop that asks for a valued number and put it inside the actual loop, so that when it is an invalid number, it asks for another one.
Edited while condition because of #AMC 's comment
Edited to put the whole code that solves the problem:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while true:
if int(guess) < 1 or int(guess > 6):
guess = input("Please choose a valid number") #will keep asking for a valid number if it is wrong
continue
else:
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
if userAnswer=="n":
break

Related

ValueError exception in python3?

I'm a python beginner and i was making a simple number guessing game, but every time i accidently type in a letter or a symbol instead of a number, i get the ValueError. How do I pass this error throughout the entire program? i know the code is messy, and I'm sorry for that but I'm just trying to have some fun with it.
import random
tries = 15
money = 0
cheat = 0
run = True
random_number = random.randint(1, 20)
while run:
if cheat >= 1:
print(random_number)
cheat -= 1
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
guess = int(guess)
if guess == random_number:
money += 5
print("You got it right! You got it with " + str(tries) + " tries left", "your balance is", + money)
again = input("Play again? yes/no")
if again == "yes":
random_number = random.randint(1, 20)
else:
break
#store system
shop = input("Would you like to access the shop? yes/no")
if shop == "yes":
try_cost = 10
cheat_cost = 20
#if player has enough money
buy_try = input("Would you like to purchase more tries? price is 10 dollars for 5 tries. yes/no")
if buy_try == "yes" and money >= 10:
tries += 5
money -= 10
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
buy_cheat = input("Would you like to purchase a cheat? price is 20 dollars for 2 cheats")
if buy_cheat == "yes" and money >= 20:
cheat += 2
money -= 20
print("You have", tries, "tries", "and", money, "money", "and", cheat, "cheats")
# if player doesn't have enough money
elif buy_try == "yes" and money != 10:
print("You don't have enough for that, you have", money, "dollars")
elif buy_cheat == "yes" and money != 20:
print("You don't have enough for that, you have", money, "dollars")
elif guess > random_number:
print("Try a little lower!")
tries -= 1
elif guess < random_number:
print("Try a little higher!")
tries -= 1
if tries == 0:
print("you ran out of tries!")
run = False
Pick a number from 1-20! You have 15 triess
Traceback (most recent call last):
File "C:\Users\bashr\PycharmProjects\pythonProject1\main.py", line 15, in
guess = int(guess)
ValueError: invalid literal for int() with base 10: 's'
In this situation, use a try and except clause.
Documentation: https://docs.python.org/3/tutorial/errors.html#handling-exceptions
assuming you want to access that error inside this whole file then you can use global variable or you can use class concept
I think the fastest way to solve that is a while: while the input Is not a digit ask again the input.
So, in your case, every time you use the input function you should use something likes this:
guess = input("Pick a number from 1-20! You have " + str(tries) + " tries")
while not guess.isdigit():
print("the input Is not a digit, please retry")
guess = input("Pick a number from 1-20! You have...")
Or you can use you can use try and except

Is it possible this way? Letting computer to guess my number

I want pc to find the number in my mind with random function "every time"
so i tried something but not sure this is the correct direction and its not working as intended
how am i supposed to tell pc to guess higher than the previous guess
ps:code is not complete just wondering is it possible to do this way
def computer_guess():
myguess = int(input("Please enter your guess: "))
pcguess = randint(1, 10)
feedback = ""
print(pcguess)
while myguess != pcguess:
if myguess > pcguess:
feedback = input("was i close?: ")
return feedback, myguess
while feedback == "go higher":
x = pcguess
pcguess2 = randint(x, myguess)
print(pcguess2)
I wrote this a few years ago and it's similar to what you're trying to do except this only asks for user input once then calls random and shrinks the range for the next guess until the computer guess is equal to the user input.
import random
low = 0
high = 100
n = int(input(f'Chose a number between {low} and {high}:'))
count = 0
guess = random.randint(0,100)
lower_guess = low
upper_guess = high
while n != "guess":
count +=1
if guess < n:
lower_guess = guess+1
print(guess)
print("is low")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
elif guess > n:
upper_guess = guess-1
print(guess)
print("is high")
next_guess = random.randint(lower_guess , upper_guess)
guess = next_guess
else:
print("it is " + str(guess) + '. I guessed it in ' + str(count) + ' attempts')
break

Python Guessing game - incomplete code

Can someone please help me re-design this code so that the program prompts the user to choose Easy, Medium or Hard.
Easy: maxNumber = 10
Medium: maxNumber = 50
Hard: maxNumber = 100
It should choose a random number between 0 and the maxNumber.
The program will loop calling a function the get the users guess, and another to check their guess. a function named “getGuess” which will ask the user for their guess and reprompt
if the guess is not between 0 and the maxNumber
r function named “checkGuess” which will check the users guess
compared to the answer.
The function will return “higher” if the number is higher
than the guess; “lower” if the number is lower than the guess and “correct” if thenumber is equal to the guess.
Once the user has guessed the number correctly the program will display all their guesses and
how many guesses it took them. Then the program will ask the user if they would like to try
again and redisplay the difficulty menu.
import random
guessesTaken = 0
print('Hello! Welcome to the guessing game')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low.')
if guess > number:
print('Your guess is too high.')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
You could do something like this:
from random import randint
myName = input("what's your name? ")
def pre_game():
difficulty = input("Choose difficulty: type easy medium or hard: ")
main_loop(difficulty)
def main_loop(difficulty):
if difficulty == "easy":
answer = randint(0, 10)
elif difficulty == "medium":
answer = randint(0, 50)
else:
answer = randint(0, 100)
times_guessed = 0
guess = int()
while times_guessed < 6:
print('Take a guess.')
guess = input()
guess = int(guess)
times_guessed += 1
if guess < answer:
print('Your guess is too low.')
if guess > answer:
print('Your guess is too high.')
if guess == answer:
break
if guess == answer:
guessesTaken = str(times_guessed)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != answer:
print('Nope. The number I was thinking of was ' + str(answer))
next = input("Play again? y/n: ")
if next == "y":
pre_game()
else:
print("Thanks for playing!")
pre_game()

I have made a guess the number game but every time i run it and type a number this it crashes

this is my code:
#This is a guess the number game
import random
print('Hello what is your name')
name = input()
secretNumber = random.randint(1, 20)
print('Well ' + name + ' I am thinking of a number between 1 and 20. You have 6 guesses')
#Ask the player to guess 6 times.
for guessTaken in range(1, 7):
try:
print('Take a guess')
guess = int(input())
except ValueError:
print('That is not a number')
guess = int(input())
guess = str(input())
if guess < secretNumber:
print('Your guess is to low.')
elif guess > secretNumber:
print('Your gues s is to high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job ' + name + '. You guessed my number!')
print('It was ' + str(secretNumber))
print('and you guessed it in ' + str(guessTaken) + ' guesses')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
when ever i run it and type a number this comes up: guess = int(input())
ValueError: invalid literal for int() with base 10: ''
I don't think you want
guess = int(input())
guess = str(input())
in your loop. Try getting rid of those (you only need to take user input once during that loop, not three times). Keep the guess = int(input()) inside of the try block, though.
Try this:
#This is a guess the number game
import random
name = input('Hello what is your name: ')
secretNumber = random.randint(1, 20)
print('Well, ' + name + ' I am thinking of a number between 1 and 20. You have 6 guesses')
#Ask the player to guess 6 times.
for guessTaken in range(1, 7):
try:
guess = int(input('Take a guess: '))
except ValueError:
print('That is not a number')
if guess < secretNumber:
print('Your guess is to low.')
elif guess > secretNumber:
print('Your guess is to high.')
else:
break # This condition is the correct guess!
if guess == secretNumber:
print('Good job ' + name + '. You guessed my number!')
print('It was ' + str(secretNumber))
print('and you guessed it in ' + str(guessTaken) + ' guesses')
else:
print('Nope. The number I was thinking of was ' + str(secretNumber))
You didn't need:
guess = int(input())
guess = str(input())

Ending a program in Python

I am struggling to end my program in Python, all I want is to type q or quit to end the program when done. Here is my code
# This is a guess the number game
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit()
Please tell me where I am going wrong??
From what I can tell you have two errors.
First you need to import the sys module for sys.exit() to work.
Second, your indentation is incorrect in two places. Here is the correct code. The comments show where the indentation is incorrect:
# This is a guess the number game
import random
import sys
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number: #indentation was off here
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over') #and here
choice = input('Press Q to Quit')
if choice == 'q' :
sys.exit() # and here
As #MarkyPython noted, you have some indent error, and you need to import sys if you want to use exit.
Note that given the code that you have, it is actually bad practice to use sys.exit(). I would instead recommend that you use break. This will exit your while loop. Because you have no code after that, your program will graciously exit.
If you add more code later on, you'll probably want to put your code inside a function. At that point, using return will be the way to go.
Using break or return is better practice because it makes it easier to add features to your program later on and makes the flow of your code better (no abrupt exit 'jump').
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20, can you guess it?')
while guessesTaken < 6:
print('Take a guess!')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess < number:
print('Your guess is too low')
if guess > number:
print('Your guess is too high')
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job ' + myName + '!You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q' :
break # instead of exit

Categories