Program runs and stops after conditions are met. I need the program to stop after 3 consecutive heads are flipped. How can this be done?
import random
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
print("heads")
sum_heads += 1
else:
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
flips()
You can add a counter for consecutive heads that turns back to 0 in case the next is tail.
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
consecutive = 0
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
print("heads")
consecutive+=1
if consecutive==3:
print("Simulation complete! 3 consecutive heads were flipped.")
break
sum_heads += 1
else:
consecutive = 0
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
I tried to keep it as simple as possible. You can try this.
import random
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
last_3_results = []
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
sum_heads += 1
print("heads")
else:
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
last_3_results.append(coin)
if len(last_3_results) > 3:
last_3_results.pop(0)
if len(last_3_results) ==3 and len(set(last_3_results)) == 1 and last_3_results[0] == 0:
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
flips()
Related
I've been trying to figure out how to add a score to this for ages. I'm still not sure ;( sorry I'm new to coding.
this is the code for the main part
while roundsPlayed > 0:
chips_left = MAX_CHIPS
n = 1
rounds = 1
while chips_left > 0:
while True:
print("Number of chips left {}".format(chips_left))
if n%2 == 0:
print("{} How many chips would you like to take (1 - 3): ".format(playerTwo))
else:
print("{} How many chips would you like to take (1 - 3): ".format(playerOne))
try:
chipsTaken = int(input())
if chipsTaken < 1 or chipsTaken > 3:
print("Please enter a valid number from 1 to 3!")
else:
break
except:
print("Thats not even a number brotherman")
n += 1
chips_left = chips_left - chipsTaken
roundsPlayed = roundsPlayed - 1
rounds += 1
I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review
I am writing a function fizzbuzz and what I want to do is input value and return it as fizz, buzz or fizzbuzz. However, there is a problem with my code. Whenever I run this, I just only get the first condition and it does not continue. Here is the code below for you:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0:
return ('Fizz')
elif a % 5 == 0:
return ( 'Buzz' )
elif a % 15 == 0:
return ('Fizzbuzz')
else:
return a
print(fizzbuzz(a))
The problem is in the ordering of your if conditionals.
Consider that if a is divisible by 15 then it is also divisible by 3 and 5 and so your code will just enter the first conditional and not the one you want.
Arrange the conditionals in descending order of 15, 5, 3 etc. and you should see what you want.
def fizzBuzz(n):
for n in range(1,n+1):
if n % 3 == 0 and n % 5 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
if __name__ == '__main__':
n = int(input().strip())
fizzBuzz(n)
Be sure that your conditions are checked in the right order.
A Fizzbuzz number is also a Fizz (divisible by 3) and a Buzz (divisible by 5), just to be clear.
In the code you wrote if you ask the function if 15 is a Buzz, since it is the 1st check, you will get a positive result.
The condition you want to test here is not if a number is divisible by 15 but if a number is divisible by 3 and 5 at the same time.
Given this explanation you need to write conditions a bit differently:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0 and a % 5 == 0:
return('Fizzbuzz')
elif a % 3 == 0:
return('Fizz')
elif a % 5 == 0:
return('Buzz')
else:
return a
print(fizzbuzz(a))
I recently ran into a problem where the code would start repeating itself around line 69. I don't know why this is and any help would be amazing.
Here is the code.
import time
import threading
import random
totalviews = 0
videoViews = 0
totallikes = 0
videolikes = 0
totaldislikes = 0
videodislikes = 0
subscribers = 0
videolength = 0
midroles = 0
uploadTimer1 = 0
waitTimer1 = 0
x = 0
comadymins = 0
comadysecs = 0
def timer1():
global uploadTimer1
global waitTimer1
global x
time.sleep(.75)
if x == 1:
print(uploadTimer1, 'mins remaining')
uploadTimer1 -= 1
time.sleep(60)
if uploadTimer1 == 0:
x = 0
Timer1 = threading.Thread(target=timer1)
print('')
print("you decided to start a youtube channel")
while True:
time.sleep(1.25)
print('')
print('what type of video will you make')
print('1. comedy')
print('2. gaming')
print('3. science')
print('4. check timer')
UserInput = input('')
if UserInput == '1':
if waitTimer1 == 0:
comadymins = random.randint(10, 30)
comadysecs = random.randint(0, 60)
time.sleep(0.1)
print('video length will be', comadymins, ":", comadysecs)
time.sleep(1)
if comadymins <= 29 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
uploadTimer1 += 4
x += 1
Timer1.start()
waitTimer1 += 1
else:
print('okay')
if comadymins <= 19 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
waitTimer1 += 1
uploadTimer1 += 4
x += 1
Timer1.start()
else:
print('okay')
else:
print('you already have a video running')
time.sleep(1)
if UserInput == '4':
print('okay')
print(uploadTimer1, "mins remaining")
any help would be amazing. I am also very new to coding so sorry if the code is messy or not to the average standards. I have only been coding for about a month and do it about 3 hrs a week if you have any recommendations that would be amazing.
your problem is, you have the same print data "would you like to upload now?" and two conditional statements that both act the same way.
you have a
if comadymins <= 29 and comadysecs <= 59:
and a
if comadymins <= 19 and comadysecs <= 59:
since you have a random number here:
comadymins = random.randint(10, 30)
something like "11" that is less than "19" and "29" at the same time so both of your conditions will fire and you will see the repeated sentence "would you like to upload now?".
you should work on the logic of your problem.
you may use elif for you second conditional statement to avoid firing in case of first statement was true, or choose a range without overlap.
try this for your first if statement:
if 19<comadymins <= 29 and comadysecs <= 59:
You have an infinite loop when you state while True:
This will run through all lines underneath it forever.
You could exit this loop by adding a break inside the loop if a certain condition is met.
So, what I'm doing here is I'm generating 1000 coin tosses, and putting these tosses in a list. What I'm then trying to do is find how many times heads was tossed 3 times in a row, or tails was tossed 3 times in a row. My attempt:
toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
toss = random.randint(1, 2)
if toss == 1:
coin_tosses.append("heads")
toss_count += 1
elif toss == 2:
coin_tosses.append("tails")
toss_count += 1
so up until here the code is doing what I want. My problem occurs with what I'm trying to do next though:
for trips in coin_tosses:
if "'heads', 'heads', 'heads'" in coin_tosses:
trips_count += 1
print(trips_count)
Something like this clearly does not work, but I don't know how else to achieve what I'm trying to achieve here.
you can use the following code that slice array every item in it that takes three items every item coin_tosses[counter:counter+3]
toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
toss = random.randint(1, 2)
if toss == 1:
coin_tosses.append("heads")
toss_count += 1
elif toss == 2:
coin_tosses.append("tails")
toss_count += 1
print(coin_tosses)
counter = 0
for trips in coin_tosses:
if ['heads', 'heads', 'heads'] == coin_tosses[counter:counter+3]:
trips_count += 1
counter +=1
print(trips_count)
I'd iterate through, checking whether the value is the same as the previous two. I think this should work. It counts the total number of triples, regardless of whether they're heads or tails, which your code seems to suggest is what you're after. Can easily add a check if you need them seperately.
trips_count = 0
previous_value = None
value_before_that = None
for current_value in coin_tosses:
if (current_value == previous_value) and (current_value == value_before_that):
trips_count += 1
value_before_that = previous_value
previous_value = current_value
You can try this:
import random
toss_count = 0
trips_count = 0
coin_tosses = []
while toss_count < 1000:
toss = random.randint(1, 2)
if toss == 1:
coin_tosses.append("heads")
toss_count += 1
elif toss == 2:
coin_tosses.append("tails")
toss_count += 1
for i in range(len(coin_tosses)-2):
if coin_tosses[i] == coin_tosses[i+1] == coin_tosses[i+2]:
trips_count += 1
print(trips_count)