How do I conditionally loop in Python? - python

I have been trying but struggling to make a rolling dice simulator in Python that is an assignment for school and am looking for some help for it. These are the instructions:
This project involves writing a program that simulates rolling a dice.
When the program runs, it will randomly choose a number between 1 – 6.
Have the dice roll 100 times. The program will count if it is a 1 or 2
or 3 or 4 or 5 or 6. After rolling the dice 100 times the program will
output how many times each number was rolled. It should then ask you
if you’d like to roll again, answer (1 for Yes) and (0 for No).
What you will be Using : Variables Integer Random Print For Loop
and/or While Loop
I have two sections of code that I need to loop over:
import random
for x in range(100):
value = random.randint(1, 6)
print(value)
and:
value = input("Wanna roll? 1 yes 2 no:\n")
print(f'You entered {value}')
y={value}
while y=1
print(value)
What is an idiomatic way of doing this in Python?

Related

Compute future tuition

I have a problem I need to calculate future tuition depending on the input that the user puts. So for example the tuition is 5,000 per year and increases by 7% every year. If a user inputs 6 the program should print the total cost of tuition for years six, seven, eight and nine. So far I have this.
year = 1
n = int(input())
tuition = 5000
for i in range (n,n + 3):
tuition = tuition * 1.07
year = year + 1
print (tuition)
Regardless of what the user inputs, your for loop will run through 3 iterations.
It looks like you're trying to add a 7% increase (compound) every year for 3 years.
You don't need a loop for that.
e.g.,
tuition = 5_000
years = 3
increase = 1.07
print(tuition * increase ** years)
Output:
6125.215
A few hints
The problem with your program is that you are looping using a for loop but you are not using the value i within your for loop. You should use it. Additionally think about how many times your print() statement is executed. Only once, but you need it for every year so think about moving it into the for loop as well.
One other thing: input() takes a string as a parameter so you can provide some description of what a user is supposed to enter. You should use this as well to make your program usable.
n = int(input("Please enter a start year:"))

How do I run the random.randint function multiple times? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm trying to make a dice roller in Python for Warhammer 40,000, and the end goal is for the user to input their Ballistic Skill (and any modifiers), the number of attacks, their Strength, the opponent's Toughness, and other stats. The program will use these stats and complete the following.
Generate a number of random integers equal to the number the user specified as the number of attacks.
Compare these to the Ballistic Skill. Any integers that are greater than or equal to the BS are passed.
Test these against the target's Toughness (this will be summarized in a later question).
Test the successes against the target's save.
Calculate damage.
Right now, I have this smidgen of code.
ballistic: int = input("What is your Ballistic Skill? Please answer in this format: '3'.")
shots: int = input('How many shots will your weapon be firing? Answer as a number.')
print("Rolling dice to hit now. Please wait...")
hits = random.randint(1, 6)
Note the declaration of the variable "hits"- this is important.
The question is: How do I run the random.randint function a number of times equal to the variable "shots"?
Jakub pointed out that in Python a for loop is typically what you would use to repeat an operation a specified number of times. Here is a very basic implementation to give you a feel for how that works.
EDIT 1: Updated Example 1 to print hits only if the value is equal to or greater than the ballistic value.
EDIT 2: Didn't modify the code, but modified the inputs (bumped number of shots up from 10 to 20) to better illustrate the relationship between ballistics and hits.
Example 1:
import random
ballistic = int(input("Enter Ballistic Skill: "))
shot_count = int(input("Enter number of shots: "))
for shot in range(shot_count):
hits = random.randint(1, 6)
if hits >= ballistic:
print(hits)
Output:
Enter Ballistic Skill: 3
Enter number of shots: 20
3
4
5
6
5
4
5
6
4
4
3
One problem with the simple approach is that the value of hits is lost at the end of the loop. That may be okay for what you are doing, but sometimes you want to build a list of something and keep it around for use after the loop. To do that, there is a more advanced technique called list comprehension that is often used, but for illustration purposes we can just build out the example above.
Example 2:
import random
shot_count = int(input("Enter number of shots: "))
hits_list = []
for shot in range(shot_count):
hits = random.randint(1, 6)
hits_list.append(hits)
print(hits_list)
Output:
Enter number of shots: 3
[1, 4, 5]

will randint always generate random numbers?

Does random.randint have a cooldown (or so) time before it generates a new random/seed?
As a part of something bigger I am trying to program a list of 5 "dice rolls" (random numbers from 1 to 6). I have this code in my program:
from random import randint
rolls = [randint(1,6),randint(1,6),randint(1,6),randint(1,6),randint(1,6)]
print (rolls)
When checking things i rolled 1,2,3,4,5 twice in a row and then i checked other rolls and the numbers didnt seem to change much between each roll

Python Blackjack Game how to carry a variable in a while loop

I'm still deep into the making of my Blackjack game in Python, my aim is to allow the computer to 'twist' (Take another card) until the total value is greater than 15. From then onwards I want it so that as the total of the cards gets higher, the chance of the computer taking another card gets smaller just like a human (taking a risk if the number isn't TOO big).The following code occurs after the computer has been dealt two values.
if (computerCardValueTotal < 15):
print ("The computer has decided to twist")
ranCompCard3 = random.choice(availableCards)
computerCardValueTotal = ranCompCard + ranCompCard2 + ranCompCard3
if (computerCardValueTotal < 15):
print ("The computer has chosen to twist again")
My aim is to have this piece of code loop if the total value is less than 15 so that the computer twists until it is over 15. I have considered using a while loop but I'm unsure on how to carry the current total to the start of the loop so that the next card value is added to the current total. Does anyone have a solution they could help me out with?
Also, secondly, it's not the biggest of the two issues in this question, but how would you recommend doing the computer so that the chance of it twisting again is smaller as the total value of cards get bigger? For example, for if the value of the cards totals at 17, there's a 1/10 chance of the computer twisting but if the total value of the cards is 19 the chance of the computer twisting is 1/20.
All valuable help will be voted up and as always, thanks in advance! :)
You have hobbled yourself by making e.g. ranCompCard, ranCompCard2, ranCompCard3, ... when a list would make life much easier:
compCards = [ranCompCard, ranCompCard2]
while sum(compCards) < 15:
compCards.append(random.choice(availableCards))
For adjusting the probability of picking another card, you could do something like:
while True:
gap = 21 - sum(compCards)
if gap > 0 and random.random() < (1 / (40 / float(gap))):
compCards.append(random.choice(availableCards))
else:
break
Note that this is a linear relationship between gap and the probability of picking another card:
>>> for card_sum in range(15, 21):
print card_sum, 1 / (40 / float(21 - card_sum))
15 0.15
16 0.125
17 0.1
18 0.075
19 0.05
20 0.025
but you can adjust the equation as needed.
While you're editing your code, take a look at (and consider following) the official style guide; variable names should be lowercase_with_underscores.
Simply reassign the value when it changes.
while computerCardValueTotal < 15:
# other code
computerCardValueTotal = <new value>

Probability exercise returning different result that expected

As an exercise I'm writing a program to calculate the odds of rolling 5 die with the same number. The idea is to get the result via simulation as opposed to simple math though. My program is this:
# rollFive.py
from random import *
def main():
n = input("Please enter the number of sims to run: ")
hits = simNRolls(n)
hits = float(hits)
n = float(n)
prob = hits/n
print "The odds of rolling 5 of the same number are", prob
def simNRolls(n):
hits = 0
for i in range(n):
hits = hits + diceRoll()
return hits
def diceRoll():
firstDie = randrange(1,7,1)
for i in range(4):
nextDie = randrange(1,7,1)
if nextDie!=firstDie:
success = 0
break
else:
success = 1
return success
The problem is that running this program with a value for n of 1 000 000 gives me a probability usually between 0.0006 and 0.0008 while my math makes me believe I should be getting an answer closer to 0.0001286 (aka (1/6)^5).
Is there something wrong with my program? Or am I making some basic mistake with the math here? Or would I find my result revert closer to the right answer if I were able to run the program over larger iterations?
The probability of getting a particular number five times is (1/6)^5, but the probability of getting any five numbers the same is (1/6)^4.
There are two ways to see this.
First, the probability of getting all 1's, for example, is (1/6)^5 since there is only one way out of six to get a 1. Multiply that by five dice, and you get (1/6)^5. But, since there are six possible numbers to get the same, then there are six ways to succeed, which is 6((1/6)^5) or (1/6)^4.
Looked at another way, it doesn't matter what the first roll gives, so we exclude it. Then we have to match that number with the four remaining rolls, the probability of which is (1/6)^4.
Your math is wrong. The probability of getting five dice with the same number is 6*(1/6)^5 = 0.0007716.
Very simply, there are 6 ** 5 possible outcomes from rolling 5 dice, and only 6 of those outcomes are successful, so the answer is 6.0 / 6 ** 5
I think your expected probability is wrong, as you've stated the problem. (1/6)^5 is the probability of rolling some specific number 5 times in a row; (1/6)^4 is the probability of rolling any number 5 times in a row (because the first roll is always "successful" -- that is, the first roll will always result in some number).
>>> (1.0/6.0)**4
0.00077160493827160479
Compare to running your program with 1 million iterations:
[me#host:~] python roll5.py
Please enter the number of sims to run: 1000000
The odds of rolling 5 of the same number are 0.000755

Categories

Resources