Python 2.7 Coin Flip Program Crashes Every Time - python-2.7

I'm having this strange problem with a simple coin flip program where, instead of giving me some sort of error, whenever i run this code it just sort of crashes. I type in a yes or no answer and hit enter, but it does nothing. Then I hit enter again and it closes out completely.
import time
import random
constant = 1
FirstRun = True
def Intro():
raw_input("Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ")
def CoinToss():
print "You flip the coin"
time.sleep(1)
print "and the result is..."
time.sleep(1)
result = random.randint(1,2)
if result == 1:
print "heads"
if result == 2:
print "tails"
while constant == 1:
if FirstRun == True:
Intro()
FirstRun = False
else:
answer = raw_input()
if answer == "yes":
CoinToss()
raw_input("Do you want to flip again? (yes or no): ")
else:
exit()

As you simply ignore the return value of the raw_input method, you don't know what the user is entered in order to break out of the loop.
Here is a simplified version of your program, note how I store the result of the raw_input method in result and use that to control the execution loop:
import random
import time
result = raw_input('Hello and welcome to the coin flip game. Do you wish to flip a coin? (yes or no): ')
while result != 'no':
print('You flip the coin....')
time.sleep(1)
print('...and the result is...')
toss_result = random.randint(1,2)
if toss_result == 1:
print('Heads')
else:
print('Tails')
result = raw_input('Do you want to flip again? (yes or no): ')
print('Goodbye!')

Related

Finding 2 numbers and send a message about it

I need to find 2 random numbers from 1-100 and send a message:
to high or to low according to the random number,
This is the code I wrote..., it doesn't work after the first if...,
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while guess != a:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = raw_input("guess a new number:")
from random import randint
a = randint(1, 101)
guess = input("guess the number:")
while True:
if guess > a:
print "your guess is too high"
elif guess < a:
print "your guess is too low"
else:
print 'You are correct'
break
guess = input("guess again:")
If I understood correctly your aim this code will work. It will stop when he guesses correctly the number. You had many mistakes with input and int. For future reference - if you use input() instead of raw_input() it will automatically pick the right type for the var.
In order to make your code work as intended just fix the input:
from random import randint
a = int(randint(1, 101))
guess = int(raw_input("guess the number:"))
while True:
if guess > a:
print "bigger"
print guess
print a
elif guess < a:
print "smaller"
print guess
print a
else:
print "correct"
print guess
print a
break
guess = input("guess a new number:") #not raw_input()

Not understanding the While(True) loop - Python 2.7

Having a hard time figuring out how the while(True) function is supposed to be fitted in the code. Also no idea if that is the right thing to use as I am trying to loop the game until the computer or the user hits the desired amount of points ( which the user inputs as rounds in the beginning)
import random
def main():
print
print "----------------------------------"
print "Welcome to Rock, Paper, Sciccors! "
print "----------------------------------"
rounds = input("How many points to win?: ")
user_choice = input("Choose Rock = 1 , Paper = 2 or Sciccors = 3: ")
user_score = 0
computer_score = 0
if user_choice == 1:
print "You chose Rock"
elif user_choice == 2:
print "You chose Paper"
elif user_choice == 3:
print "You chose Sciccors"
else:
print " Wrong! Choose 1, 2 or 3!"
computer_choice = random.randrange(1, 4)
if computer_choice == 1:
print "Computer chose Rock"
elif computer_choice == 2:
print "Computer chose Paper"
elif computer_choice == 3:
print "Computer chose Sciccors"
def checkResults(computer_choice, user_choice):
checkResults = computer_choice - user_choice
if computer_choice - user_choice == 0:
print("Draw!")
user_score += 1
computer_score += 1
elif computer_choice - user_choice == 1 or computer_choice - user_choice == -2:
print("Computer wins")
computer_score += 1
elif computer_choice - user_choice == -1 or computer_choice - user_choice == 2:
print("You win!")
user_score += 1
print (" Computer {} , You {}" .format(computer_score, user_score))
while(True):
if computer_score == rounds or user_score == rounds:
main()
else:
break
You can make this a bit shorter:
while computer_score == rounds or user_score == rounds:
' Your code returning computer_score and user_score
Basically a while True is an infinite loop that can only be ended using a break statement or via keyboard interrupt.
while True: is an infinite loop that can only be stopped via the command break. In your example, you have created a loop that will infinitely run the main() method (which you defined earlier, by saying def main():). The only time the loop will end is if you kill the process (i.e. using task manager on Windows), or if computer_score and user_score both become unequal to rounds (which is what your else statement is implying on the second to last line). When this happens, the program calls break which forcibly ends the loop immediately and moves on... to the end of the file (which then ends the program).
It should be noted that using a while True ... break loop is sometimes frowned upon by programmers, because it is not seen as "elegant". It is totally fine code to do, but another way to re-write the last few lines is the following:
while computer_score==rounds or user_score==rounds:
main()
This achieves the same result by running the while loop until computer_score and user_score both do not equal rounds. At that point, the while loop ends itself cleanly and ends the program by getting to the end of the file.

(Super beginner) Can someone explain what's going wrong with my lists?

Ok, so, this is the longest code I've ever written, so I apologize if it's a bit messy. First computer science assignment ever.
def main():
#generate random value
import random
rand = random.randint(1, 99)
#instructions
print("""The purpose of this exercise is to enter a number of coin values
that add up to a displayed target value. Enter coins as 1=penny, 5-nickel,
10-dime, 25-quarter. Hit return after the last entered coin value.""")
#defining function for 'first coin'
def firstCoin ():
coins = []
global coins
coin = int(input("Enter first coin: "))
if coin > rand:
print("Sorry, total value exceeds", rand, "cents.")
again = input("Try again (y/n): ")
if again == "y" or "Y":
main()
else:
sys.exit() #ends program
elif coin in possible:
coins.append(coin)
nextCoinplease()
#defining function for 'next coin'
def nextCoinplease ():
while True:
nextcoin = (input("Enter next coin: "))
if nextcoin in possible:
coins.append(nextcoin)
elif nextcoin == "":
break
else: print("Invalid entry.")
#making lists
possible = [1, 5, 10, 25]
print("Enter coins that add up to", rand, "cents, one per line.") #program start
firstCoin ()
sumcoin = sum(coins)
print(sumcoin)
if sumcoin == rand:
print("Correct!")
else:
print("Invalid entry.")
firstCoin()
main()
So, this is my issue. For some reason, user input in the function nextCoinplease does not get added to the list "coins", only the first input from the function firstCoin does. This means that sum(coins) is literally only the first input. I cannot for the life of me figure out why, so any input would be greatly appreciated, thanks!
You have two input statements, one to get coin and one to get nextcoin. They are different. What's the difference?
(I'm deliberately not giving the answer outright because from what you've written so far, I am sure you can figure this one out given this hint.)
The return type of input is a string, so nextcoin in possible always fails since possible only contains integers. Try using int() to parse the input as an integer.
Your code never gets to check if the rand is equal to sumCoin, so it never stopped. I've fixed the problem, this code works now.
Demo on repl.it
What did I do?
I moved your if statement that checked if rand == sumCoin at the beginning of the while loop in nextCoinPlease(), so that it will check the sumCoin value before entering each next coin value and will stop once it equals rand.
Code:
import random
import sys
def main():
rand = random.randint(1, 99)
print('''The purpose of this exercise is to enter a number of coin values \
that add up to a displayed target value. Enter coins as 1=penny, \
5=nickel, 10-dime, 25-quarter. Hit return after the last entered \
coin value.''')
coins = []
def firstCoin():
coin = int(input("Enter first coin: "))
if coin > rand:
print('Sorry, total value exceeds ', rand, ' cents.')
again = input('Try again? (y/n): ')
if again == 'y' or 'Y':
main()
else:
sys.exit()
elif coin in possible:
coins.append(coin)
nextCoinPlease()
def nextCoinPlease():
while True:
sumCoin = sum(coins)
print('Total Value: ' + str(sumCoin))
print ''
if sumCoin == rand:
print('Correct! You Win!')
sys.exit()
elif sumCoin > rand:
print('You exceeded the total value! You lose! Try again!')
sys.exit()
nextCoin = (input('Enter next coin: '))
if nextCoin in possible:
coins.append(nextCoin)
elif nextCoin == "":
break
else:
print('Invalid entry.')
possible = [1, 5, 10, 25]
print('Enter coins that add up to', rand, 'cents, one per line.')
firstCoin()
main()

How to run the code from start after calculation?

What if i want to ask the user whether he wants to perform another calculation or not everytime the user makes a calculation and gets the answer? I just want the code to run again from start everytime user performs calculation
var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division respectively: "))
if var == 1:
print "You chose to add.Lets add!! :)"
def main ():
total = 0.0
while True:
number = float(raw_input('enter a number: '))
total+=number
if number == 0:
break
print "your answer is:",total
main()
elif var == 3:
print "You chose to multiply.Lets multiply!! :) "
def main ():
total = 1.0
while True:
number = float(raw_input('enter a number:'))
total*=number
if number == 1:
break
print "the answer is", total
main()
Just put
while True:
around the whole thing. This will continue looping indefinitely. If you want the user to be able to choose to end the program, try:
while True:
...
continue = raw_input("Continue? (Y/N) ")
if continue.lower in ("n", "no"):
break

Roulette program will not recognize correct guess. Why?

The following is the roulette portion of a casino game I'm putting together, but I can't seem to get it to work correctly. It won't recognize when the player chooses the correct number, and I'm hoping someone can tell me why. Obviously, a few other parts have not been completed, but I'm just trying to get the basics running. Also, I'm pretty new at this, so feel free to critique anything else! Thanks.
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets == True:
bets = True
return bets
else:
print "You bet on: ", bets
print "Better luck next time."
bets = False
return bets
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
self.spin(bets)
# payout for bets
if bets == True:
print "You win $", bet_amount*35
self.wallet += bet_amount*35
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()
Your main error was this:
# start spin
self.spin(bets)
# payout for bets
It should read:
#start spin
bets = self.spin(bets)
# payount bets
the modified code below does it correctly. Overwriting bets with a different type isn't good style, I'd suggest using a different variable. Also win in bets doesn't need to explicitly compared to True (unless for clarification during learning).
Hope that helps, if you have further questions, just comment ;-)
from random import randint
from time import sleep
funds = 50
### Straight Up number bet = 35:1
### Odd/Even payout = 1:1
class RouletteTable(object):
def __init__(self, wallet):
self.wallet = wallet
def spin(self, bets):
print "Spinning..."
sleep(2)
print "The winner is..."
sleep(1)
winner = 25 #randint(0, 36) #FOR TESTING
print "Number ", winner
if winner in bets:
return True
else:
print "You bet on: ", bets
print "Better luck next time."
return False
def game(self):
while self.wallet >= 0:
print "\n\nWelcome to Roulette."
print "Test your luck, and place your bets!"
print "Current funds: $", self.wallet
print "\n(1)Place bet or (2)Exit"
choice = raw_input("> ")
if choice == "1":
bets = []
print '''\n\n\n
__________
[ 0 ]
[ 1][ 2][ 3]
[ 4][ 5][ 6]
[ 7][ 8][ 9]
[10][11][12]
[13][14][15]
[16][17][18]
[19][20][21]
[22][23][24]
[25][26][27]
[28][29][30]
[31][32][33]
[34][35][36]
[ODD] [EVEN]
'''
print "How much will you bet (per number)?"
bet_amount = int(raw_input("> $"))
print "Type a number to bet on, and press Enter."
print "When finished choosing, just press Enter."
while True:
print "Funds: $", self.wallet
print "Current Bets: ", bets
number_choice = raw_input("> ")
if number_choice != "":
bets.append(int(number_choice))
self.wallet -= bet_amount
else:
# start spin
did_win = self.spin(bets)
# payout for bets
if did_win == True:
ammount = bet_amount*35
self.wallet += ammount
print "You win $", ammount
break
if choice == "2":
return self.wallet
break
if self.wallet == 0:
print "You're out of money!\n"
roulette = RouletteTable(funds)
funds = roulette.game()