I'm writing a VERY basic roulette simulator in python. At the moment, I'm only focusing on red/black betting (basically the same as betting on heads or tails, using a coin).
My code has various issues. Please forgive my very basic knowledge of the language.
import random
# Defines initial amounts of money and losses
money = 50
losses = 0
# Asks user how much to bet
def roulette_sim():
print "How much do you want to bet?"
bet = raw_input("> ")
if bet > money:
bet_too_much()
else:
red_or_black()
# Prevents one from betting more money than one has
def bet_too_much():
print "You do not have all that money. Please bet again."
raw_input("Press ENTER to continue> ")
roulette_sim()
# Asks user to select red or black, starts the sim, modifies money/losses
def red_or_black():
print "OK, you bet %r" % (bet)
print "Red or black?"
answer = raw_input("> ")
number = random.randint(1, 2)
if number == 1 and answer == "red":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
elif number == 2 and answer == "black":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
else:
print "You lost!"
money -= bet
losses += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
# Asks user whether he/she wants to play again
def replay():
print "Do you want to play again?"
play_again = raw_input("y/n> ")
if play_again == "y":
roulette_sim()
else:
print "OK, bye loser!"
roulette_sim()
First issue so far: the bet_too_much function doesn't work. Whatever amount I input, the program states it's too much (ie: 'bet' is always greater than 'money'). Why?
Second issue so far: when I want to add/subtract 'bet' to/from 'money' by using, for example:
money += bet
python treats this as summing an int with a string (at least I think it does) rather than summing two variables. Why is this?
Any help would be appreciated.
Thanks
Both things happen because Python does not do implicit conversions. You have to tell it explicitly that you want something to be an integer, it will not do it for you.
So, for the first issue:
bet = raw_input("> ")
if bet > money:
...
has to be
bet = raw_input("> ")
bet = int(bet)
if bet > money:
...
because you do not want to compare a string with an integer (you can, but with the results you're getting right now).
For the second, you have to be explicit as well:
money += int(bet)
(of course, if you already converted bet to an int, you're fine).
Javascript is notorious for doing this implicit conversions, so if you have happen to be familiar with that or a language that is similar, forget about that and be explicit about the type you're using. Which, on the whole, is safer.
The raw_input() function returns a string value, but money is an integer. Comparing strings to numbers always ends up with Python 2 ordering numbers as smaller than strings.
Convert the result of raw_input() to an integer:
def roulette_sim():
print "How much do you want to bet?"
bet = int(raw_input("> "))
This may throw a ValueError exception if the input given is not a valid number; you may want to catch that exception and tell the user to enter a number instead:
def roulette_sim():
print "How much do you want to bet?"
while True:
try:
bet = int(raw_input("> "))
except ValueError:
print "Please enter a valid amount, a number."
else:
break
You are comparing the string you get from raw_input("> ") with a integer. This will not end well.
Try this function instead (havent tested it fully):
def roulette_sim():
while(1):
print "How much do you want to bet?"
try:
bet = int(raw_input("> "))
break
except ValueError:
print 'You need to input a number'
if bet > money:
bet_too_much()
else:
red_or_black()
EDIT: changed to "except ValueError" according to comment. I know I am a bit lazy on the except handling part of python programing, but perhaps I should not teach that to others :-)
Related
I've been trying to write a function that will ask for a number between 1-11 and will randomly choose a number and will compare between them.
I can't figure out why no matter what number I type in (equals or smaller or bigger) it will always type the "Your number is less" message.
def loto():
_number = int(input("Enter any number between 1-10: "))
import random
for x in range(1):
print ("Python chose: " + str(random.randint(1,11)))
if ("_number" == "random"):
print ("You Won! :)")
if ("_number" < "random"):
print ("Your number is less")
if ("_number" > "random"):
print ("Your number is more")
else:
print ("You Lost :(")
loto()
I'm using Python 3.
Thanks:)
Your first problem is that you're comparing the strings "_number" and "random". ASCIIbetically (or, rather, Unicoderifically), "_number" < "random", because the _ character is #95 and the r character is #114.
If you want to compare two variables, you just refer to the variables, not strings that happen to be the same as the names of those variables.
Your second problem is that random isn't your random number, it's the module you used to create that number. And, more seriously, you aren't storing that number anywhere—you're just converting it to a string to print it out and then throwing it away.
Your third problem is that you need to change those ifs to elifs. Otherwise, the You Lost message gets printed whenever _number > random is not true, instead of only whenever all of the three comparisons are not true.
Putting that all together:
choice = random.randint(1,11)
for x in range(1):
print ("Python chose: " + str(choice))
if (_number == choice):
print ("You Won! :)")
elif (_number < choice):
print ("Your number is less")
elif (_number > choice):
print ("Your number is more")
else:
print ("You Lost :(")
Of course there's no way to actually lose your game—one of the three conditions is always going to be true. (If you were using complex numbers, or floats including NaN, you could input a number that wasn't comparable in any way to the selected one, but you're not.)
While we're at it:
There's no reason to name your variable _number instead of number.
That for x in range(1): loop doesn't do anything useful—it loops exactly once, setting x to 0, which you never use.
You don't need parentheses around your conditions.
You shouldn't import modules in the middle of a function like that except in special cases where you need unusual things like lazy loading.
You should follow PEP 8 style, or at least pick a consistent style to follow.
It's simpler to just pass multiple arguments to print, or to use string formatting, than to manually convert things to strings and concatenate them.
So:
import random
def loto():
number = int(input("Enter any number between 1-10: "))
choice = random.randint(1, 11)
print("Python chose:", choice)
if number == choice:
print("You Won! :)")
elif number < choice:
print("Your number is less")
elif number > choice:
print("Your number is more")
else:
print("You Lost :(")
loto()
You were comparing strings not variables, you need to remove quotes, and you not saved random number into a variable. The for loop is making one repetition only, you can remove it.
Update your cod like this:
import random
def loto():
_number = int(input("Enter any number between 1-10: "))
rand_number = random.randint(1,11) # can't had the same name as random
if (_number == rand_number):
print ("You Won! :)")
elif (_number < rand_number):
print ("Your number is less")
elif (_number > rand_number):
print ("Your number is more")
else:
print ("You Lost :(")
loto()
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.
#Guess my number
import random
print ("Welcome to the guess my number game")
print ("***********************************")
print ("You will choose a random number between 1-100")
print ("and the computer must guess what it is.")
print ()
number = int(input("Please choose a number between 1-100: "))
guesses = 0
guess = 0
while guess != number:
guess = ("My guess is: ",random.randint(1,100))
guesses=guesses+1
if guess > number:
print("Lower...")
continue
elif guess < number:
print ("Higher...")
else:
print ("Well done you have guessed my number and it took you") print ("guesses,"guesses!")
Basically you choose a number and the computer has to keep guessing until it gets it right but I can't seem to get it to work.
You should learn basic debugging skills. The simplest way to debug this program would be to add print() statements to see what values are in your variables.
Your basic problem is that you set guess to a tuple with two values: the string "My guess is: " and a random number from 1 to 100. You probably intended to set guess to just the number.
You probably want something like this:
guess = random.randint(1,100)
print("My guess is: {}".format(guess))
This will get you one step closer. Then you will need to figure out how to change the program so that it narrows down the guess range. If you have trouble with that, maybe you should find someone to tutor you a bit.
I have been set some homework to make a word guessing game, I have got it to work for the most part but at this point I am using random.choice and that command allows the same string to repeat more than once. I need to know how to use random.randint in this instance.
""" This is a guessing game which allows the person operating the program to
guess what i want for christmas"""
import random
sw = ("Trainers")
print ("In this game you will have 10 chances to guess what I want for christmas, you start with 10 points, each time you guess incorrectly you will be deducted one point. Each time you guess incorrectly you will be given another clue.")
clue_list = ["They are an item of clothing", "The item comes in pairs", "The Item is worn whilst playing sport", "The item is an inanimate object", "The item can be made of leather","They come in differant sizes", "They have laces", "can be all differant colours", "the item has soles", "Im getting it for christmas ;)"]
def guessing_game(sw, clue_list):
x = 10
while x<=10 and x > 0:
answer = input("What do I want for christmas?")
if sw.lower() == answer and answer.isalpha():
print ("Good Guess thats what I want for christmas")
print ("You scored %s points" % (x))
break
else:
print ("incorrect, " + random.choice(clue_list))
x -=1
if x == 0:
print ("You lost, try again")
guessing_game(sw, clue_list)
for your implementation I think you want:
clueint = random.randint(0, len(clue_list))
print("incorrect, " + clue_list[clueint])
to ensure the same clues are not displayed twice declare an empty list to store guess in OUTSIDE the function definition:
clues_shown = []
and then add each int to the list:
def showClue():
clueint = random.randint(0, len(clue_list))
if clueint in clues_shown:
showClue()
else:
clues_shown.append(clueint)
print("incorrect, " + clue_list[clueint])
I am a brand new programmer, and I have been trying to learn Python (2.7). I found a few exercise online to attempt, and one involves the creation of a simple guessing game.
Try as i might, I cannot figure out what is wrong with my code. The while loop within it executes correctly if the number is guessed correctly the first time. Also, if a lower number is guessed on first try, the correct code block executes - but then all subsequent "guesses" yield the code block for the "higher" number, regardless of the inputs. I have printed out the variables throughout the code to try and see what is going on - but it has not helped. Any insight would be greatly appreciated. Thanks! Here is my code:
from random import randint
answer = randint(1, 100)
print answer
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print "Top of Loop"
print guess
print answer
i = i + 1
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
else:
print "else statement"
print "Congratulations! You got it in %r guesses." % i
print "Time to play a guessing game!"
print "Enter a number between 1 and 100:"
guess = raw_input()
guess = int(guess)
logic(guess, answer, i)
I'm sure it is something obvious, and I apoloogize in advance if I am just being stupid.
You've noticed that raw_input() returns a string (as I have noticed at the bottom of your code). But you forgot to change the input to an integer inside the while loop.
Because it is a string, it will always be greater than a number ("hi" > n), thus that is why "Too high. Try again:" is always being called.
So, just change guess = raw_input() to guess = int(raw_input())
Try this:
guess = int(raw_input())
As raw_input.__doc__ describes, the return type is a string (and you want an int). This means you're comparing an int against a string, which results in the seemingly wrong result you're obtaining. See this answer for more info.
Ok, I found your problem. The problem is in this Code:
if guess < answer:
print "Too low. Try again:"
guess = raw_input()
print guess
print answer
print i
elif guess > answer:
print "Too high. Try again:"
guess = raw_input()
print guess
print answer
print i
In the code above you are getting your input as string, but you try to compare it with integer. All you need to do is to convert the input to integer, like this:
guess = raw_input()
guess = int(guess)
This should solve your problem :)
I updated the program. You came out of the while loop because after you get guesss as input inside elif group, you forget to convert that to int, so it throwed back error. Now, corrected but you can also optimise it.
import sys
from random import randint
answer = randint(1, 100)
'''randint(1, 100)'''
print (answer)
i = 1
def logic(guess, answer, i):
guess = int(guess)
answer = int(answer)
while guess != answer:
print ("Top of Loop")
print (guess)
print (answer)
i = i + 1
if guess < answer:
print ("Too low. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
elif guess > answer:
print ("Too high. Try again:")
guess = int(input())
print (guess)
print (answer)
print (i)
else:
print ("else statement")
print ("Congratulations! You got it in %r guesses." % i)
print ("Time to play a guessing game!")
print ("Enter a number between 1 and 100:")
guess = input()
guess = int(guess)
logic(guess, answer, i)