You keep winning, why? - python

so I am trying to do simple rolling of the dice to see if you win(excuse if something is indented wrong, the copy n paste is kinda wonky, here is a pastbin if you would rather have that http://pastebin.com/thg7ruT1). I am not exactly sure what is happen but when I run the YouMightWin function, no matter what StanDice's outcome is it always says "You Win!" even if it rolls less than 6. I am not sure what looks like it should work to me, at least from other things I've played around. If you can help thanks.
def StanDice():
num_dice = 2
num_sides = 6
rand_num = random.randint(1, num_dice*num_sides)
print rand_num
def YouMightWin():
Ans = raw_input("Roll the dice? [Y/N]: ")
Ans = Ans.lower()
dice_roll = StanDice()
if Ans in ("y" or "yes"):
print dice_roll, "This is the Dice"
if dice_roll < 6:
print "You win!"
elif dice_roll > 6:
print "You lose!"
else:
print "Something went wrong!"
elif Ans in ('n' or 'no'):
print "Are you sure you don't want to roll?"
YouMightWin()
else:
print "Something went in the main if statement"

You're printing the value of rand_num instead of returning it, so the function returns None, which is less than 6.
That said, your dice are too naive-- real don't have an equal chance of rolling 2 and 7. Check out a probability table. You should roll each die independently and add them together instead.

Related

Problem with simple dice game using python

I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break

Python; How do I test if something is in a list?

I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed.
It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now!
import random
import math
import time
repeat=True
numbers = ["1","2","3","4","5"]
gamestart=False
gamecontinue=True
def guess():
chosennumber=random.choice(numbers)
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber==chosennumber and guessnumber in numbers:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
print
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
elif not guessnumber in numbers:
while not guessnumber in numbers:
guessnumber=raw_input(">Please enter a number between 0 and 6:")
if raw_input(">Do you want to play guessing game? Y or N:") == "Y":
gamestart=True
else:
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
while gamestart==True and gamecontinue==True:
guess()
if raw_input (">Do you want to play again? Y or N:") == "N":
gamecontinue=False
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
so you figured out what was the issue, good! but i have one more tip for you, a better approach to achieve this is check if the input is correct as soon is readed, if it is correct you keep going, if it not, you ask for it again right there:
while True:
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber in numbers:
print "good!"
break
else:
print "bad!"
and now you're sure that the input is correct so you only check:
if guessnumber==chosennumber:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
else:
print "That is not right."
print "I chose %d." % (int(chosennumber))
if number not in numbers
That will do the trick
It checks if it is true that the selected number is in the list
The problem is that if you put two elif statements the first one will proceed first.
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
This condition will be asked first. But if you look again at it whether the input (guessnumber) is in the list or not it will proceed. So if we want it to become a condition which we enter a number that is in a list but not matching with the chosen number, we will add another condition to elif statement.
code will be like this
elif guessnumber!=chosennumber and guessnumber in numbers:
Slight detail but good to keep in mind I think.

Show me the way to calling my function

So I'm learning to code and I started with Python.
I've learned the very basics of programming in python, like what are variables, operators, some functions etc.
I have this code:
def guessGame():
import random
guesses = 0
randomNo = random.randint(0, 100)
print "I think of a number between 0 and 100, you have 10 guesses to get it right!"
while guesses < 10:
guess = input("Take a guess ")
guess = int(guess)
guesses += 1
if guess < randomNo:
print "The number is higher than your guess"
if guess > randomNo:
print "The number is lower than your guess"
if guess == randomNo:
break
if guess == randomNo:
guesses = str(guesses)
print "You got it in %s guesses!" % guesses
if guess != randomNo:
print "You failed to guess!"
guessGame()
when I run the code in cmd it just ends before the function gets "recalled".
cmd output
You called the game only once in your main program -- which consists of the last line only. It runs the game once and quits. There is no second call in your code. Perhaps you want a classic "play again?" loop:
play = True
while play:
guessGame()
play = lower(raw_input("Play again?")[0]) == 'y'
after each game, you ask the player for input. If that input begins with the letter 'y' (upper or lower case), then you continue playing; otherwise, play becomes False and you drop out of the loop.
Is that what you wanted?

While loop does not seem to check condition correctly

I'm building a game as part of a tutorial on learning code.
The following class has a while loop that should return either 'finished' or, leave the loop and return 'death' (These are dict entries that run the game) but instead does not even seem to run. I'm looking at the while loop after def guess:
The loop is meant to ask the user to guess a number between 1 and three. If they guess wrong more than three times they "lose" and 'death' is returned, else 'finished'.
But, when I play the game I am not even prompted to enter a number, instead "Too many failed guesses, you lose!" is printed, even if guesses is 0.
class Smaug(Scene):
def enter(self):
print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"
print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
print "He says \"Guess a number between 1 and 3\""
smaugNum = random.randint(1, 3)
print "Smaugs number cheat:", smaugNum
guesses = 0
def guess():
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
guess()
print "Too many failed guesses, you lose!"
return 'death'
Looking at the nesting of the code blocks, is it that when 'finished' is returned in the while loop, does it also, automatically, get returned as part of the wider class? Put another way, if numb == smaugNum then I need Smaug class to return finished.
The problem is that you are not calling the guess() function at all.. You have guess() as a function and it is not called at all. so, the control directly jumps to the next line after the function. The best way is to remove the function and use the code like this:
guesses = 0
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
print "Too many failed guesses, you lose!"
return 'death'
You are defining guess smack dab in the middle of enter, but you are never calling it.
The blocks are like
class Smaug:
def enter:
#here's what to do when enter() is called
def guess:
#here's what to do when guess() is called
#here's some more stuff to do when enter() is called
The problem here is that you are infinitely recursing down the guess function and never calling guess() in the first place.
After you increase your guesses counter you do not need to call guess() again as the execution will still be inside the while loop due to the number of guesses being less than 4, simply trust the while loop to do the comparison. Avoid calling guess() manually.

Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"

Categories

Resources