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.
Related
I am learning python and I cannot figure out how to get back to a certain part of loop depending on the response.
If it reaches:
else :
print('Answer must be yes or no')
I want it to start back at:
print ("We are going to add numbers.")
I have tried several different suggestions I have seen on here, but they result in starting back at the very beginning.
My code:
import random
num1 = random.randint(1,100)
num2 = random.randint(1,100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print ("Nice to meet you " + name)
print ("We are going to add numbers.")
print ("Does that sound good?")
answer = str.lower(input())
if answer == str('yes'):
print ('Yay!!')
print ('Add these numbers')
print (num1, num2)
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
elif answer == str('no'):
print ('Goodbye')
else :
print('Answer must be yes or no')
You need a loop that starts with the thing you want to get back to:
def start():
import random
num1 = random.randint(1, 100)
num2 = random.randint(1, 100)
addition = num1 + num2
print("Hello. What is your name?")
name = str(input())
print("Nice to meet you " + name)
while True:
print("We are going to add numbers.")
print("Does that sound good?")
answer = str.lower(input())
if answer == "no":
print("Goodbye")
return
elif answer == "yes":
break
else:
print('Answer must be yes or no')
print('Yay!!')
print('Add these numbers')
print(num1, num2)
# This following part might want to be a loop too?
numbers = int(input())
if numbers == addition:
print('Good Job!')
else:
print('Try again')
numbers = int(input())
With my guess the number program, when I try to run it tells me the the variable "number" is not defined. I would appreciate it and be thankful if someone came to my aid in this!
import random
guesses = 0
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
Your problem is that number is not defined in the function correct. number is defined in _main_. When you call correct in _main_, it does not get access to number.
This is the fixed version of your code:
import random
guesses = 0
number = random.randint(1, 100)
def higher(guesses):
print("Lower")
guesses = guesses + 1
def lower(guesses):
print("Higher")
guesses = guesses + 1
def correct(guesses):
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_(guesses):
print("Welcome to guess the number")
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher(guesses)
elif guess < number:
lower(guesses)
elif guess == number:
correct(guesses)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
break
elif answer == "N":
exit()
else:
exit()
_main_(guesses)
What I changed is I moved the definition of number to the top, which allowed it to be accessed by all functions in the module.
Also, your code style is not very good. Firstly, do not name your main function _main_, instead use main. Additionally, you don't need a function to print out 'lower' and 'higher.' Here is some improved code:
import random
def main():
number = random.randint(1, 100)
guesses = 0
while True:
guessed_num = int(input('Guess the number: '))
guesses += 1
if guessed_num > number:
print('Guess lower!')
elif guessed_num < number:
print('Guess higher!')
else:
print('Correct!')
print('The number was {}'.format(number))
print('It took you {} guesses.'.format(guesses))
break
main()
Your specific problem is that the variable number is not defined in function correct(). It can be solved by passing number as an argument to correct().
But even if you correct that problem, your program has another major issue. You have defined guesses globally, but you still pass guesses as an argument to lower(), higher() and correct(). This creates a duplicate variable guesses inside the scope of these functions and each time you call either of these functions, it is this duplicate variable that is being incremented and not the one you created globally. So no matter how many guesses the user takes, it will always print
You took 1 guesses.
Solution:
Define the functions lower() and higher() with no arguments. Tell those functions thatSo ultimately this code should work:
import random
guesses = 0
def higher():
global guesses
print("Lower")
guesses = guesses + 1
def lower():
global guesses
print("Higher")
guesses = guesses + 1
def correct(number):
global guesses
print("You got it correct!")
print("It was {0}".format(number))
guesses = guesses + 1
print ("It took you {0} guesses".format(guesses))
def _main_():
print("Welcome to guess the number")
guesses = 0
number = random.randint(1, 100)
while True:
guess = int(input("Guess a number: "))
if guess > number:
higher()
elif guess < number:
lower()
elif guess == number:
correct(number)
while True:
answer = input("Would you like to play again? Y or N: ")
if answer == "Y":
_main_()
elif answer == "N":
exit()
else:
exit()
_main_()
while True:
# main program
number = (" ")
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer in y, n:
break
print("Invalid input.")
if answer == 'y':
continue
else:
print 'Goodbye'
break
Essentially I want the program to restart when the user enters 'y' as a response to 'run again?' Any help would be vastly appreciated. Thanks.
As #burhan suggested, simply wrap your main program inside a function. BTW, your code has some bugs which could use some help:
if answer in y, n: - you probably mean if answer not in ('y', 'n'):
number = (" ") is an irrelevant line
while True makes no sense in your main program
print("Invalid input.") is below a break, thus it'll never be executed
So you'll have something like:
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
while True:
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
break
if answer == 'y':
main()
else:
print("Goodbye")
break
def main():
total = 0
num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
answer = raw_input("Run again? (y/n): ")
if answer not in ('y', 'n'):
print("Invalid input.")
if answer == 'y':
main()
else:
print 'Goodbye'
if __name__ == '__main__':
main()
You should probably add a few checks to handle cases when users enter non-number input etc.
Your code looks really messed up. Try to write some better(clean) code next time.
while True:
total = 0
num1 = int(input("enter a number"))
num2 = int(input("enter a number"))
num3 = int(input("enter a number"))
total = num1 + num2 + num3
if total > 100:
print("That's a big number!")
else:
print("That's a small number.")
print(total)
con = int(input("Run again? 1/0: "))
if con==0:
break
I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)
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