I'm trying to break the loop by saying
if deff <= int(total):
break
but the loop will break regardless of the input being negative or more than the total it will break the loop
any advice of what am i doing wrong?
P.S i know i will new a formula to decide if player won or lost. right now im just trying to figure out the first code before going there
first time on programming and teacher not helpful ):
def intro():
greeting()
print('How much money do you want to start with?')
print('Enter the starting amount of dollars.', end='')
total = int(input())
print('Your current total is '+ str(total)+'\n')
while True:
print('How much money do you want to bet (enter 0 to quit)?', end='');
# Bett will be the amount of money that the player will play with
bett = int(input())
if bett > int(total):
print('ERROR You don\'t have that much left')
if bett < int(0):
print('ERROR: Invalid bet amount\n')
if bett <= int(total)
break
# Function shows results of slot machine after handle being pulled
def random():
import random
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str (num1)+'-|-'+ str(num2) +'-|-'+ str (num3) +'-|')
print('\---+---+---/ ')
intro()
You need to use elif and else in the successive conditional tests:
bett = int(input())
if bett > total:
print('ERROR You don\'t have that much left')
elif bett < 0:
print('ERROR: Invalid bet amount\n')
else:
break
That way, only one of the statements in executed, instead of more or more.
NB:
It's not necessary to use theint() constructor all the time on something that is already an int
In this block:
if bett <= int(total)
break
You have a syntax error. Add a colon to the end of hte first line:
if bett <= int(total):
break
If it were me, I would use a while loop.
play = True
while play == True:
#all the code
#to be executed
#indented here
#
#Ask user if they want to continue playing
p = input("Play again?[y/n] ")
playAgain = str(p)
if playAgain == "y":
play = True
else:
play = False
Related
I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.
I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...
How do I get this game to end when the input is no without going back to the top and looping through or getting an error code? Note I put "End" in so that it would not iterate again
import random
it's a simple guessing game that I want to start over if yes but end if no
def main():
y_games = 2
for y in range(y_games):
play_guessingGame_()
def play_guessingGame_():
guessesTaken = 0
print('Hello Friend,\n')
print('What is your name?\n')
name = input()
print(name + ' ,It is good to meet you!\n')
print("Let's play a game!\n ")
print('I am thinking of a number between 1 and 10. . . what is my number?\n')
try:
answer = random.randint(1,10)
while guessesTaken < 5:
print("Start guessing!\n")
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
if guess > answer:
print('Too high! Try again!\n')
elif guess < answer:
print('Too low! Try again!\n')
elif guess == answer:
break
while guess == answer:
guessesTaken = str(guessesTaken)
if guessesTaken == str(1):
print('AND ON THE FIRST TRY!!! IMPRESSIVE!!!!')
print('There is no beating you\n')
break
if guessesTaken > str(1):
print('Good job! You guessed my number in ' + guessesTaken + ' guesses')
print('There is no beating you\n')
break
if guess != answer:
print("I'm sorry, you have run out of guess.\n")
print('Better luck next time!\n')
except ValueError:
print('Please enter whole numbers only')
print('\nDo you want to try again? ')
response = input()
if response == 'yes':
print("Great! Let's do this!")
if response == 'no':
print('\nWell, all good things must come to end!')
Exit
main()
i added import random to your code and also changed Exit to exit() and there was no error and the game performed right, i hope i got your problem right..
EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")
I am trying to create a loop that will get me asking for a user's bet until it runs out of money or decides to quit. How can i take inputs from the different functions?
import random
import sys
def greeting():
print('COP1000 Slot Machine - Jesus Pacheco')
print('Let\'s play slots!')
# Function ask user starting amout to bet
# then it will check for any input error
def intro():
greeting()
print('How much money do you want to start with?')
print('Enter the starting amount of dollars.', end='')
total = int(input())
print('Your current total is '+ str(total)+'\n')
while True:
print('How much money do you want to bet (enter 0 to quit)?', end='');
# Bett will be the amount of money that the player will bet
bett = int(input())
if bett == 0:
sys.exit()
if bett > int(total):
print('ERROR You don\'t have that much left')
elif bett < int(0):
print('ERROR: Invalid bet amount\n')
else:
break
# Function will ask user to press enter to play slot machine
def slotMachine():
print('Press enter to pull slot machine handle!')
input()
# Function shows results of slot machine after handle being pulled
def random():
import random
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str (num1)+'-|-'+ str(num2) +'-|-'+ str (num3) +'-|')
print('\---+---+---/ ')
if num1 == num2 and num2 == num3:
print('JACKPOT! cha-ching, you win')
if num1 == num3 or num2 == num3:
print('Match two, you get your bet back!')
else:
print('sorry, no match')
intro()
slotMachine()
random()
input()
What you need to do is create a way to get input, return it, check if it is valid, then call the slot-machine function. Also, you can use input(s); s is the prompt you want to show (s is usually a string). I suggest housing this all under a main() function:
import sys
import random
def main():
intro()
total = int(input('Starting Money: '))
if total <= 0:
raise ValueError('Starting Money must be greater than 0.')
# the above raises an error if the bet is less than 0
while True:
bet = getInput(total)
total = slotMachine(total, bet)
if total == 'win' or total <= 0:
break
def intro():
print('COP1000 Slot Machine - Jesus Pacheco')
print("Let's play slots!")
def getInput(total):
userInput = int(input('Bet (0 to quit): '))
if userInput > total or userInput < 0:
raise ValueError('Bet must be less than total and greater than 0.')
if userInput== 0:
sys.exit()
# the above raises an error if the bet is less than 0 or greater than the total
return userInput
def slotMachine(total, bet):
num1 = random.randint(1, 5)
num2 = random.randint(1, 5)
num3 = random.randint(1, 5)
print('/---+---+---\ ')
print('|-'+ str(num1)+'-|-'+ str(num2) +'-|-'+ str(num3) +'-|')
print('\---+---+---/ ')
if num1 == num2 and num2 == num3:
print('JACKPOT! Cha-Ching, you win!')
return 'win'
elif num1 == num3 or num2 == num3:
print('Match two, you get your bet back!')
return total
else:
print('Sorry, no match.')
return total - bet
main()
I suggest you read about functions and return statements.