Python 2.7 Slot Machine if statement issue - python

import random
numbers = []
wheel1 = 0
wheel2 = 0
wheel3 = 0
winnings = int(0)
balance = int(50)
def generator(balance):
number1 = random.random()
number2 = random.random()
number3 = random.random()
if number1 < 0.05:
wheel1 = "Cherry"
elif number1 < 0.15:
wheel1 = "Diamond"
elif number1 < 0.30:
wheel1 = "Hearts"
elif number1 < 0.65:
wheel1 = "Spade"
elif number1 < 1:
wheel1 = "Monkey"
if number2 < 0.05:
wheel2 = "Cherry"
elif number2 < 0.15:
wheel2 = "Diamond"
elif number2 < 0.30:
wheel2 = "Hearts"
elif number2 < 0.65:
wheel2 = "Spade"
elif number2 < 1:
wheel2 = "Monkey"
if number3 < 0.05:
wheel3 = "Cherry"
elif number3 < 0.15:
wheel3 = "Diamond"
elif number3 < 0.30:
wheel3 = "Hearts"
elif number3 < 0.65:
wheel3 = "Spade"
elif number3 < 1:
wheel3 = "Monkey"
return wheel1
return wheel2
return wheel3
def win(generator,balance):
generator(balance)
if wheel1 =="Monkey"and wheel2 == "Monkey"and wheel3 == "Monkey":
print "JACKPOT!"
winnings = int(50)
balance + winnings
print 'JACKPOT!'
else:
print 'noice'
winnings = int(10)
balance + winnings
print 'noice'
return balance
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
balance = generator(balance)
print ""
print win(generator,balance)
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I appreciate any suggestions about the method of selecting a random symbol, but please withhold as there is only one question I have. My question is: In the win function, how do I make it recognise the 3 wheel outputs. I've done what I thought would work however it does not, even when I land on 3 monkeys.
Any other suggestions are welcome. But please keep in mind that is the most important.
Thank you very much in advance.

The problem that you have here is that your concept of scope needs a little help.
This answer is a really good start.
To make a short example of your code, let's just do this:
def generator(balance):
wheel_1 = 'Monkey'
wheel_2 = 'Diamond'
wheel_3 = 'Heart'
return wheel_1, wheel_2, wheel_3
def win(generator):
print wheel_1, wheel_2, wheel_3
win(generator)
What you'll get here is a NameError, because wheel_1 (and 2 & 3) don't actually exist within the win function. They only exist within the generator function. So what you need to do is get the values from the generator function, and put them somewhere that 'win' can see. You can actually do this pretty easily, since we're already returning the values from the generator function:
# Note: generator was removed as a parameter.
# We don't need it here, because if Python
# can't find the name `generator` it will look
# in the enclosing scope and find the function
# `generator` there.
def win():
# What we want to do is *call* `generator` and
# assign the results to some variables that *are*
# in `win`'s scope
wheel_1, wheel_2, wheel_3 = generator()
print wheel_1, wheel_2, wheel_3
As you mentioned, you can definitely improve some things in your current code. You've noticed inside your generator function there's code that looks almost exactly the same. When you look at code and you get that feeling, that's what's called a "code smell". That's what happens when your (sub)conscious mind sees some code that it knows could be improved. In this particular case there's a principle called DRY - Don't Repeat Yourself.
You can replace your existing code with the following:
def spin_one():
number = random.random()
if number < 0.05:
result = 'Cherry'
elif number < 0.15:
result = 'Diamond'
elif number < 0.30:
result = 'Hearts'
elif number < 0.65:
result = 'Spade'
else:
result = 'Monkey'
return result
def generator():
return spin_one(), spin_one(), spin_one()
And what I might even do is remove the generator call altogether and simply do this:
if all((spin_one() == 'Monkey' for _ in xrange(3))):
You can read the docs on all.
Though, if you want to have more than just win a lot and win a little, then you'd need to keep the values:
wheels = [spin_one() for _ in xrange(3)]
Then you can do:
if all(wheel == 'Monkey' for wheel in wheels):
# Alternatively, wheels.count('Monkey') == 3
print 'Jackpot'
elif wheels.count('Hearts') == 2:
print 'Win'
elif all(wheel == 'Lemon' for wheel in wheels):
print 'You lose'
And any other kind of winning you might want to add.
Prompt
I don't think this is either better or worse than your current prompt approach, but I used to use it all the time in my C++ course.
def prompt():
choice = raw_input('(Y)es or (N)o: ').lower()
if choice == 'y':
return True
elif choice == 'n':
return False
else:
print '**ERROR** Please input "y" or "n"'
return prompt()
It's a nice, simple way to get a handle on recursion :)

Related

Why isn't the int changing the str value to int in the try statement?

while True:
printing("Welcome to The Cheapest Dealer Ship\n", 0.025)
printing("What car would you like\n")
printing(
"""
(1) Standard $50
(2) SUV $60
(3) Minivan $80
""", 0.025)
ans = input(">>")
try:
int(ans)
except:
pass
if ans == 1:
Total += 50
Car = "Standard"
Car_cost = 50
break
elif ans == 2:
Total += 60
Car = "SUV"
Car_cost = 60
break
elif ans == 3:
Total += 80
Car = "Minivan"
Car_cost = 80
break
else:
printing("Please chose a valid option")
time.sleep(1)
replit.clear()
So basically this is a school code excersize but I can't quite figure why it will return with an else statement even if you answer 1,2 or 3. Not sure why int isn't working or what I'm doing wrong.
Either change your this line
int(ans)
To:-
ans = int(ans)
Or, you can directly take an integer as a input.
Change these lines of code
ans = input(">>")
try:
int(ans)
except:
pass
To this,
while True:
ans = (input(">>"))
if ans.isnumric():
while True:
if ans=="3" or ans=="2" or ans=="1"
break
else:
print("Please select any one (1\2\3)")
break
else:
print("Please enter only numbers.")
ans = int(ans)
After this you will have no need to use try and except statements and you will have less chances of getting errors.

else command not running correctly? (Python 3 Beginner)

I'm working on a combo menu for my first Python program. I've gotten everything to work properly up to this point. I want the program to exit if the user's input isn't equal to the accepted answers. I've tried a few different methods to get this working, but it still just runs like I answered "Yes" or "yes". Any help? Thanks a ton.
Here is my code:
def p(): #Prints new line quiokly
print()
def error(): #Restarts the main
question = input("You have entered an invalid option. Would you like to try your order again? \n")
if question in ("Yes","yes","yes"):
main()
else:
exit
def main(): #Main block of code
cost = 0 #total cost variable
if cost == 0:
print("What type of sandwhich would you like? Refer to the cost and type of sandwhich below.")
p()
print("Chicken Sandwhich = $5.25")
p()
print("Tofu Sandwhich = $5.75")
p()
print("Beef Sandwhich = $6.25") #initial questions
x = input()
if x == ("Beef") or x == ("beef"):
cost += 6.25
print("You have selected Beef. Your total is so far is $6.25.")
elif x == ("Chicken") or x == ("chicken"):
cost += 5.25
print("You have selected Chicken. Your total is so far is $5.25.")
elif x == ("Tofu") or x == ("tofu"):
cost += 5.75
print("You have selected Tofu. Your total is so far is $5.75.")
if x not in ("beef" , "Beef" , "Tofu" , "tofu" , "chicken" , "Chicken"): #checks for valid resposne
error()
print("Would you like to add a drink to your meal?")
p()
yzz = input()
if yzz == ("Yes") or ("yes"):
p()
print("Okay, would you like small, medium, or large? Refer to the prices below.")
print(cost)
p()
print("Small - $1.00")
p()
print("Medium - $1.75")
p()
print("Large - $2.25")
p()
yzzz = input()
if yzzz == ("Small") or yzzz == ("small"):
cost += 1
print("You have selected a small drink. Your total is so far is " + "$%.2f" %cost + ".")
elif yzzz == ("Medium") or yzzz == ("medium"):
cost += 1.75
print("You have selected a medium drink. Your total is so far is " + "$%.2f" %cost + ".")
elif yzzz == ("Large") or yzzz == ("large"):
cost += 2.25
print("You have selected a large drink. Your total is so far is " + "$%.2f" %cost + ".")
if yzzz not in ("small" , "Small" , "Medium" , "medium" , "large" , "Large"): #checks for valid response
error()
elif yzz not in ("yes","Yes"):
exit
#Main code starts here!
main()
The indent for the line elif yzz not in ("yes","Yes"): is wrong, you need to indent it one more time.
Also the expression if yzz == ('Yes') or ('yes') will always evaluate to True because the or expects a boolean to either side and ('yes') evaluates to True.
instead write if yzz in ['Yes', 'yes']

Access a function variable from outside the function in python

I have a python function and would like to retrieve a value from outside the function. How can achieve that without to use global variable. I had an idea, if functions in python are objects then this could be a right solution?
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
while check_difficulty.tries > 0:
I am new to python so excuse me...
def check_difficulty(difficulty):
if (difficulty == 1):
return 10
elif (difficulty == 2):
return 5
elif (difficulty == 3):
return 3
tries = 0
while tries > 0:
difficulty = int(input("Choose your difficulty: "))
tries = check_difficulty(difficulty)
tries = tries - 1
if you use a while loop and put everything inside in a structured way, a function will not be needed.
You can change this to a class to get your tries:
class MyClass:
def __init__(self):
self.tries = 0
def check_difficulty(self, difficulty):
if (difficulty == 1):
self.tries = 10
elif (difficulty == 2):
self.tries = 5
elif (difficulty == 3):
self.tries = 3
ch = MyClass()
try:
difficulty = int(input("Choose your difficulty: "))
ch.check_difficulty(difficulty)
except ValueError:
difficulty = int(input("Type a valid number: "))
ch.check_difficulty(difficulty)
ch.tries
# 5
If you want the question answered within the construct of your current code simply put your try, except before the function. You can call a function anywhere in the code it doesn't ave to be after the function is created . So something like this:
try:
difficulty = int(input("Choose your difficulty: "))
check_difficulty()
except ValueError:
difficulty = int(input("Type a valid number: "))
check_difficulty()
def check_difficulty():
if (difficulty == 1):
check_difficulty.tries = 10
elif (difficulty == 2):
check_difficulty.tries = 5
elif (difficulty == 3):
check_difficulty.tries = 3
while check_difficulty.tries > 0:
however, I would have to agree with the other answers and just kind of put everything together within the same loop and you won't have to worry about this. I created a guessing game recently that actually had something similar to this. Here is the difficulty portion of that code:
def guessing_game():
again = ''
# Define guesses/lives
while True:
try:
guesses_left = int(input('How many guess would you like(up to 4)?: '))
if 1 > guesses_left or guesses_left > 4:
print('You must choose between 1 and 4 for your guess amount. Try again.')
continue
break
except:
print('You must enter a valid number between 1 and 4. Try again.')
# Define difficulty based on guesses_left
difficulty = ''
if guesses_left == 1:
difficulty = 'Hard Mode'
elif guesses_left == 2:
difficulty = 'Medium Mode'
elif guesses_left == 3:
difficulty = 'Easy Mode'
elif guesses_left == 4:
difficulty = 'Super Easy Mode'
print('You are playing on ' + difficulty + ' with ' + str(guesses_left) + ' guesses.')
#code continues under this line to finish#

Completing a Startup Menu in Function - Python

I'm trying to finish writing this function that contains five different options and uses a While loop to allow the user to enter in their choice with the entry '5' exiting the loop. Below is the code I have so far, I'm having trouble completing the menu part within the def_main function. I keep getting an error after else:
break
Any input would be appreciated. Thank you for reading.
def main():
menuOption = 0
while 1 == 1:
print("1. Expanded Sum\n2. Reverse Expanded Sum\n3. Reverse Integer\n4. Product Table\n5. Exit\n")
menuOption = int(input("Enter correct menu option: "))
while menuOption<1 or menuOption>5:
print("Incorrect menu option!!")
menuOption = int(input("Enter correct menu option: "))
if menuOption == 5:
return
while 1 == 1:
num = int(input("Enter positive Integer: "))
if num <= 0:
print("You have entered negative integer or zero.")
continue
else:
break
if menuOption == 1:
printSum(num, int(False))
elif menuOption == 2:
printSum(num, int(True))
elif menuOption == 3:
print(str(reverseInt(num)))
elif menuOption == 4:
printProductTable(num)
if __name__ == "__main__": main()
def printSum(n, reverse):
s = sum(range(n+1))
if reverse:
print('+'.join(str(i) for i in range(1, n+1)) + ' = ' + str(s))
else:
print('+'.join(str(i) for i in range(n, 0, -1)) + ' = ' + str(s))
def reverse_int(n):
Reverse = 0
while(n > 0):
Reminder = n %10
Reverse = (Reverse *10) + Reminder
n = n //10
print(Reverse)
def printProductTable(n):
for row in range(1,n+1):
print(*("{:3}".format(row*col) for col in range(1, n+1)))
What is the error you are getting at the break?
It looks like your spacing might be off in the continue, I assume your else goes to the if at the top of the statement, but your continue does not match with it.
Rather than doing while 1==1 you can write while True. And also you have already checked while menuOption<1 or menuOption>5. So if your menuOption is a negative number it already falls into this condition as, say, -2 < 1.
And also seems like your code is not formatted. Means, continue is just above the else. It will generate the error. Re-formate your code. Give proper indentation.

Insights and exception mishandling : basic command-line game in Python

I am a beginner Python programmer (Python 3) and I just made my first real working program. I encounter an issue with the try: except: part (ln 63), I can't manage to trigger the range_error condition in the usr_input() function. I'm probably not using exceptions the right way.
from random import randint
def gen_num():
magic_num = randint(1,100)
return magic_num
def usr_input(range_error = False):
if range_error == True: # If number is out of range, displays additionnal warning message
print("Make sure you enter a number between 1 and 100 !")
usr_num_guess = input("Please enter an integer between 1 and 100 : ")
return int(usr_num_guess)
def play_again():
# We ask the user to choose if he wants to play again or not (yes / no)
yes = set(['yes','y','ye','yeah',''])
no = set(['no','n'])
usr_choice = input("Do you wish t play again ? (Y/n):").lower()
if usr_choice in yes:
return True
elif usr_choice in no:
return False
else:
sys.stdout.write("Please write 'yes' or 'no'")
def player_level_initialize():
# Setting up the user's desired level
easy_level = set(['easy',1])
med_level = set(['medium','med',2,''])
hard_level = set(['hard','difficult',3])
level_choice = input("Please select your level (easy,MED,hard) :").lower()
if (level_choice in easy_level):
return "easy"
elif (level_choice in med_level):
return "med"
elif (level_choice in hard_level):
return "hard"
else:
sys.stdout.write("Please write 'easy', 'med' or 'hard'")
print("Hello and Welcome to this awesome game !")
player_name = input("Please enter your name : ")
level = player_level_initialize()
keep_playing = True
usr_score = 0
while (keep_playing == True):
num_to_guess = gen_num()
num_of_attempts = 1
too_m_attempts = False
max_number_of_attempts = {
"easy":10,
"med":6,
"hard":3
}
usr_num_guess = usr_input()
while (too_m_attempts == False or usr_num_guess != num_to_guess):
if (num_of_attempts < max_number_of_attempts[level]):
try:
(usr_num_guess >= 1 and usr_num_guess < 100)
except:
usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input
else:
if (usr_num_guess != num_to_guess):
if (usr_num_guess < num_to_guess):
print("It's more !")
else:
print("It's less !")
num_of_attempts += 1
usr_num_guess = usr_input()
elif (usr_num_guess == num_to_guess):
usr_score += 1
print("Good job", player_name, "you found the magic number in only", num_of_attempts, "attempts ! It was", num_to_guess, "You have a current score of", usr_score)
else:
print("Sorry, too many attempts ! The magic number was", num_to_guess)
too_m_attempts = True
keep_playing = play_again()
print("Thank you ! I hope you enjoyed the game !")
What you need is an if block instead of a try-except block:
if not (usr_num_guess >= 1 and usr_num_guess < 100):
usr_num_guess = usr_input(True) # If the input number is out of range, the player gets a warning message + new input
The code in the except part will only be executed if the line (usr_num_guess >= 1 and usr_num_guess < 100) raises an exception.
On the use of exception, when you write
try:
...
except:
...
the code will catch every possible exception and execute th code in the except block which is supposed to fix the situation. This is probably not what you want most of the time. For example, mis-spelling a variable (e.g. usr_num_guesss) will raise a NameError, and whatever user_input() do will not fix the error -- it is an entirely different problem already than an out-of-range input. You should only catch and handle the exceptions that can be handled by your code, such as:
except ValueError:
...

Categories