Python beginner slot machine - python

I keep getting stuck in an infinite loop with this program. I know I need to assign separate values for each random number but I don't know how and my TAs aren't answering their emails. Here's my code:
import random
random_num = random.randint(0, 10) #generates random numbers between 0 and 10
user_input = input('Play again?(Y or N):')
while user_input != 'N':
print('Python Slot Machine')
print(random)
if random_num != random_num and random_num != random_num:
print('Uh oh! No match this time!')
print(user_input)
elif random_num == random_num and random_num != random_num:
print('You matched two! So close!')
print(user_input)
elif random_num == random_num and random_num == random_num and random_num == random_num:
print('Jackpot!! You matched all 3!')
print(user_input)

You are getting stuck in an infinite loops because your input function is outside of the loop, so the user never gets to decide whether they want to continue or not.
What you've done in your code above is generated a random number, and then made several references to that random number. Each time you place the variable randon_num into your function, it does not generate a new number. Instead, it keeps referencing back to when you defined random_num.
A simple way to do this would be to create a function that generates a random number so you don't have to copy the random.randint() code every time.

if else statments dont work the way you think they do.
If you have multiple loops, you can't check the value multiple times to address the loops. Also you checked random_num against random_num.
Let me show you another way to do this. Instead of giving the user a way to exit, have him play until the end. After 3 guesses it's game over anyways. For each time the user matched the random_number you give him a point.
You also have to refresh the random number after each try, otherwise it will stay the same. And as you show the number after a loop, the user knows the number from there on.
After three loops you end the while loop and print one of the messages from the messages list using the earned points as index for the list.
import random
points = 0
counter = 0
messages = [
'Uh oh! No match this time!',
'You only matched one',
'You matched two! So close!',
'Jackpot!! You matched all 3!'
]
while counter < 3:
random_num = random.randint(0, 10) # generates random numbers between 0 and 10
user_input = input('Please enter your guess: ')
print('Python Slot Machine')
print(f'random number: {random_num}')
if random_num == int(user_input):
points += 1
counter += 1
print(messages[points])

Your Logic don't make sense anyway. but, Correct structure is
import random
random_num = random.randint(0, 10)
while True:
user_input = input('Play again?(Y or N):')
if user_input == "Y":
#your code
#your code
#Your code
else:
print("User want to quit")
break

Your going to need to restart your project. You are telling the program to check if the same number equals the same number multiple times.
Ex. if the random number is 6, all of the random numbers are going to be 6.
You need to use the random.sample function in order to get multiple random numbers differently.
You also need to use functions in order to organize and optimize your code
Here is an example:
import random
random_num = random.sample(range(0,10),4)
#generates random numbers between 0 and 10
def playAgain():
user_input = input('Play again?(Y or N):')
if user_input.startswith('y'):
print('Python Slot Machine')
main()
else:
quit()
def main():
#your code

Related

i made an gusse counter with while loop for 3 trys and the counter stuck at 2

import random
import itertools as it
def guessthenumber():
play = input("do you want to play ?\nanswer yes or no :")
while play != "yes" :
if play == "no" :
quit()
else:
guessthenumber()
break
guessthenumber()
answer = random.randint(1, 5)
def random_func():
gusse = int(input("choose a number between 0 and 10"))
count = 3
while gusse != answer and count != 0 :
count -= 1
print(count)
print("wrong")
random_func()
break
random_func()
print("won")
Why does the guess count stop at 2 even with for loop?
The primary issue is as pointed out by #quamrana. When you call random_func you are adding a new stack frame that has a new count variable initialized to 3, so it immediately decrements, but then you add another call to random_func. You never return and pop this call off the stack, so there is no way to continue.
I don't see why ask if the caller wants to play. If it is the only thing the program does, running it is a pretty good indication. Also, is "gusse" a thing or just a misspelling of "guess".
You should avoid using quit() unless you are in an interpreter. You can use sys.exit, but in simple scenarios like this, returning and finishing the program is more simple.
Consider the following implementation with some slight improvements.
import random
def start(answer, tries):
while tries: # Continue while tries remain.
guess = int(input("choose a number between 0 and 10: "))
if guess == answer:
print("won")
return # Just return from the function.
tries -= 1 # Otherwise, decrement and continue.
print(f"wrong; tries remaining: {tries}")
if __name__ == "__main__":
answer = random.randint(1, 5)
start(answer, 3) # Begin the guessing part of the game.

How to stop a while loop from executing continuously?

Sorry if I phrased the question poorly, I am creating a basic game which generates a random number and asks the user to try guessing the number correctly and helps the user in the process.
import random
#print("************* THE PERFECT GUESS *****************")
a = random.randint(1,5)
num = int(input("enter a number : "))
while (num<a):
print("try guessing higher \U0001F615")
num = int(input("enter a number : "))
while (num>a):
print("try guessing lower \U0001F615")
num = int(input("enter a number : "))
if (num == a):
print("yay! You guessed it right,congrats \U0001F60E!")
Here , once I execute the program, it gets stuck in the while loop and the compiler asks me to keep guessing forever. Why is the code stuck in the while loop? Its an entry controlled loop so i thought it would break out of the loop as soon as the condition was false.
Why is the code stuck in the while loop?
Because computers do what tell them to do, not what you want them to do.
Num = new_guess()
While num!=a:
If a<num:
Too_high()
Else:
Too_low()
Num = new_guess()
Sorry for the capitals
For you if you wanted to break put of a loop:
Easiest way:
break
The harder, force stop way:
import sys
sys.exit()

How do I stop a while loop if something happens inside a function that should stop the itterations?

Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1

(Python) while loop is breaking my random_number

so I'm doing a project where it basically chooses a random number from 1 - 6 as a mini project.
On the most part, it works. But when it loops back up, it seems to keep on rolling the same number.
Here's a screenshot of what I mean
As you can see, the dice number keeps on rolling the same. Can you see what is wrong in my code?
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
Random_Number = (random.choice([1,2,3,4,5,6]))
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1
You are generating Random_Number one time, outside of the loop.
Try something like this
while (loop < 10):
Random_Number = (random.choice([1,2,3,4,5,6]))
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
loop = loop + 1
This code chooses the random number once, and then just prints it 10 times. If you want a different random number each time, you should move the random selection inside the loop:
while (loop < 10):
#Chooses random number between 1 - 6
Random_Number = (random.choice([1,2,3,4,5,6]))
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number)
input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1
You need to understand that Python (and similar languages) stores values, not expressions. If you write a = 2 + 2, there is no addition and no 2 in the variable a; there's just the number 4.
Your situation is exactly the same: You thought you defined Random_Number as an alias for the expression next to it, where in reality you only store a number.
You can of course fix the problem by calling random.choice() inside the loop-- as about 10 answers have already suggested. But to do what you meant to do, define a function that selects a number in the way you specified. Function bodies are executed every time you call the function.
def random_number():
return random.choice([1,2,3,4,5,6])
while (loop < 10):
print("you rolled", random_number())
loop += 1
You set the value of Random_Number only once, and then show that on every loop.
Fixed
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
#Random_Number = (random.choice([1,2,3,4,5,6]))
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", (random.choice([1,2,3,4,5,6])))
#input("Press any key to roll again")
print ("===============================")
#looping back to "loop = 1"
Because you generate random number only once.
It should be
...
while (loop < 10):
Random_Number = (random.choice([1,2,3,4,5,6]))
....
Also dont name variables with upper letters instead Random_Number use random_number
If you don't want to redefine a random number at every iteration:
# Useful module for selecting random numbers
import random
# Loop program back to here once user presses anything
loop = 1
#Chooses random number between 1 - 6
Random_Number = lambda : random.choice([1,2,3,4,5,6])
while (loop < 10):
#Printing what the user sees
print ("===============================")
print ("Your random dice number is:", Random_Number())
print ("===============================")
#looping back to "loop = 1"
loop = loop + 1

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Categories