(Python) while loop is breaking my random_number - python

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

Related

Python beginner slot machine

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

How do I keep track of the number of inputs by a user, and display them in a string?

I have a class project, where I am making a number guessing game. I have the following requirements:
#1. A main() function that holds the primary algorithm, but itself only passes information among other functions. main() must have the caller for random_int()
#2. A function called in main() (not nested in main()!) that compares the user's guess to the number from random_int() and lets the user know if it was too high or too low.
#3. A function called in main() that asks the user for a new guess.
#4. A function that prints out a string letting the user know that they won.
#5. Tell the user how many guesses it took them to get the correct answer.
I am struggling to determine how to keep track of the number of times a user guesses before they reach the correct number, and display that number in a string. I currently have a while loop in the function main():
def main(random_int, new_guess, user_attempts): #Function that holds the main algorithim and calls all of the functions in the program
r = random_int(size) #Setting parameters to generate a random number between 1 - 1000
n = new_guess() #Assigns the user's input as "guess", and calls the function "new_guess"
while n != r: #While loop to continue until user guesses correct number
if n > r:
print("The number you guessed is too high, guess again.")
elif n < r:
print("The number you guessed is too low, guess again.")
attempts =+ 1
n = new_guess()
if n == r: #If user guesses correct number, call "win" function
win(random_int, new_guess, user_attempts)
And am attempting to take the value of attempts, and store it in the function user_attempts(): where I can call it in the function win():. I keep getting the error - TypeError: 'int' object is not callable
The full program for context:
#Python number guessing game
#Import randrange module
from random import randrange
#Initialize variables
attempts = 0
size = 1000
def random_int(size): #Generates a random integer from given parameters (size)
return randrange(1, size+1)
def new_guess(): #Prompts the user to enter an integer as their guess
guess = int(input("Enter your guess (between 1 - 1000): "))
return guess
def user_attempts():
a = attempts
return a
def win(random_int, new_guess, user_attempts): #Prints that the answer is correct, along with the number of guesses it took
random_int = random_int(size)
a = user_attempts()
if a >= 2: #If it took the user more than 1 attempt, uses "guesses" for proper grammar
print("You guessed the correct number", str(random_int()), ", you win! It took you ", str(user_attempts()), " guesses.")
elif a < 2: #If it took the user only 1 attempt, uses "guess" for proper grammar
print("You guessed the correct number", str(random_int()), ", you win! It took you ", str(user_attempts()), " guess.")
def main(random_int, new_guess, user_attempts): #Function that holds the main algorithim and calls all of the functions in the program
r = random_int(size) #Setting parameters to generate a random number between 1 - 1000
n = new_guess() #Assigns the user's input as "guess", and calls the function "new_guess"
while n != r: #While loop to continue until user guesses correct number
if n > r:
print("The number you guessed is too high, guess again.")
elif n < r:
print("The number you guessed is too low, guess again.")
attempts =+ 1
n = new_guess()
if n == r: #If user guesses correct number, call "win" function
win(random_int, new_guess, user_attempts)
main(random_int, new_guess, user_attempts) #Calls the "main" function, runs the program
For your "int object is not callable" error, that means you are calling an integer variable like it is a function. I think it's where you do:
random_int = random_int(size)
The first call to random_int may work if it's a function, but then you're assigning a local variable called random_int the return value of that function, which is an integer. So the next time you call random_int, it's an integer instead of a function. To fix it, you should use a different variable name besides random_int, since that is what you called your function.
+= vs =+
It looks like you have:
attempts =+ 1
But you probably mean to swap the + and =:
attempts += 1
attempts =+ 1 is like attempts = +1, where + is unary positive (like unary negative).

Python psychic guessing game repeats 10 times

I want it so it will randomly generate a number between 1-10 and the user will input their guess. It will then output if it is right or wrong, after 10 rounds it will tell them how psychic they are. I have done most of it but I cannot get it to randomly generate 10 numbers instead it generates 1 number and you can just input that number and get it correct every time if you find that number
import random
score=0
random=(random.randint(1,10))
for index in range(10):
guess=int(input("Choose a number between 1 and 10:"))
if random==guess:
score+=1
print ("Correct, Next")
else:
print ("Incorrect, Next")
if score==10:
print("Final score:Super mystic")
elif score>=7:
print("Final score:Good")
elif score>=5:
print ("Final score:You need more practice")
else:
print ("Final score:Dont become a psychic")
You need to put the random=(random.randint(1,10)) inside the for loop for it to change with every loop:
for index in range(10):
random=(random.randint(1,10))
guess=int(input("Choose a number between 1 and 10:"))
Then the rest of the code

using function and random numbers

I have a question:
When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
This is what I have done so far:
import random
x = random.randint(1,6)
print("You roll a die ", x)
new_try = input("\n\n Do you want to roll a die again?")
if str(new_try) == 'yes':
print("You roll a die ", x)
else:
print("Cool game!")
I am still getting same numbers :(
You aren't changing x the second time, and merely printing it out again, giving the same result. Here is the code for a fixed version:
import random
x = random.randint(1, 6)
print("You roll a die", x)
new_try = input("\n\n Do you want to roll again? ")
if new_try == 'yes':
x = random.randint(1, 6)
print("You roll a die", x)
else:
print("Cool game!")
If you want to use a function for it, you can do it over multiple times:
import random
def roll_dice():
x = random.randint(1, 6)
print("Dice was rolled: " + str(x))
try_again = input("Do you want to try again? ")
if try_again == 'yes':
roll_dice()
roll_dice()
I reckon what you can do is set a different seed each time you run a new try.
x is not the diceroll, that is random.randint(1,6). So after x = random.randint(1,6), x stores the result of a single diceroll which happened earlier, and available to provide that single result any time in the future. So x stores a number, not the fact that it should be generated randomly.
If you want a function for rolling a dice, that would be def for first attempts:
def diceroll():
return random.randint(1,6)
having this function, any subsequent print(diceroll()) (note that it is a function call, diceroll()) would print the result of a different roll (and results could be equal only by coincidence). Or, you could again store the result of a single diceroll as x=diceroll(), so it could be re-used multiple times in the future (let's say you want to compare it to the user's guess and also print it)
Side note: technically you can store functions in variables too, x=diceroll would store the function, so x would not be a number, but the act of rolling the dice, and would have to be called as a function, like print(x()).
If you want to produce different numbers at different times, you have to use a seed value. Here is an example to explain:
import random
random.seed( 3 )
print "Random number with seed 3 :", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()
I will not make the program for you. I have explained you the concept. Now just implement it.

Game of Pig - can't figure out how to loop through all the players

I have figured out most of the problem but can't seem to figure out how to loop through each of the players to let them play the game. This is the code I have so far. I think that my while loop in the main() function is wrong but I don't know what to do to fix it. Let me know if you can point me in the right direction. I also need to figure out how to end the turn if you roll a 1.
import random
def instructions():
print ("==================================================")
print ("\nWelcome to the Game of Pig. To win, be the")
print ("player with the most points at the end of the")
print ("game. The game ends at the end of a round where")
print ("at least one player has 100 or more points.\n")
print ("On each turn, you may roll the die as many times")
print ("as you like to obtain more points. However, if")
print ("you roll a 1, your turn is over, and you do not")
print ("obtain any points that turn.\n")
def num_players():
while True:
players = raw_input("How many players will be playing? ")
if players.isdigit():
return int(players)
else:
print "\nPlease enter a valid number of players.\n"
def name_players(players):
count = 1
list_of_players = []
for i in range(players):
name = raw_input("Enter the name for Player {}: ".format(count))
list_of_players.append(name)
count += 1
print ""
return list_of_players
def start_game(list_of_players):
points = 0
for player in list_of_players:
print "{0} has {1} points.".format(player, points)
print ("==================================================\n")
s = input("How many sides of the dice do you want? ")
for player in list_of_players:
print ("\n{0}'s turn:").format(player)
answer = raw_input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s)
if roll > 1:
points += roll
print "{0} has {1} points.".format(player, points)
answer = raw_input("Press y to roll the dice?")
def main():
instructions()
players = num_players()
list_of_players = name_players(players)
start_game(list_of_players)
if __name__ == "__main__":
main()
The problem you encountered is due to the local variable, points, in function start_game. All your players are sharing the same variable to keep tracking their score. Therefore, once, your first player reaches/passes 100 points, the game logic will move to the second player. However, the points variable is still keeping the score from the previous player (which is more than or equal to 100). Because of that, the following players will never get chance to get into while loop.
You should declare points vriable for each players OR reset points variable every time when points variable holds value is greater than or equal to 100.
def start_game(list_of_players):
points = 0 #<----------------- points is local variable to the function
for player in list_of_players:
print("{0} has {1} points.".format(player, points))
print ("==================================================\n")
s = int(input("How many sides of the dice do you want? ")) ###
# validate value of s?
for player in list_of_players:
### the variables declared in for loop is unique to each player
print ("\n{0}'s turn:".format(player))
answer = input("Press y to roll the dice?")
while answer == 'y' and points <= 100:
roll = random.randrange(1, s + 1, 1) ### randrange
if roll > 1:
points += roll
print("{0} has {1} points.".format(player, points))
answer = input("Press y to roll the dice?")
PS. I'm running your code with Python 3.6.1.
Furthermore, one more thing you need to take care of is that for random.randrange(start, stop, step). The output will not include the value of stop. e.g. random.randrange(0, 10, 1) will generate integers from 0 to 9 inclusive. Therefore, if a player chose 6 sides of dice, that means the random number range should be from 1 to 6. In this way, you need to increment whatever number player entered.
e.g. 6 sides of dice
either random.randrange(0, 6+1, 1) or random.randrange(6+1) should work.

Categories