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]
Related
This question already has answers here:
A weighted version of random.choice
(28 answers)
Closed 2 years ago.
i have a list ["a","b","c"] where `"a" should represent 85% of the output and "b" should represent 10% of the output and "c" should represent 5%
i want to print a array that has these percentage of its size and the array size is variable
for ex: if input size is 20 then "a" should in the array 17 times and "b" should be there 2 times and "c" 1 time
any idea ?
If I got your question well, I would start by getting:
the ouput number
the percentages you want the three letters to represent (unless it's fixed at 85 - 10 - 5)
then proceed to divide said input number by 100 and multiply it by the desired percentage, to initiate a for loop for each of the letters, populating your array (which will stay variable in size).
To represent what I got of your question in Python3:
print("please type an integer, then Enter : ")
# the following integer will be the size of your array. Here I chose to prompt the user so that you can execute and see for yourself that you can change it as you like and the solution will stay valid.
startingInteger = int(input())
print(f"the startingInteger is {startingInteger}")
print("what is the percentage of a?")
aPercentage = int(input())
print("what is the percentage of b?")
bPercentage = int(input())
print("what is the percentage of c?")
cPercentage = int(input())
array = []
for i in range(int(round(startingInteger/100*aPercentage))):
array.append("a")
for i in range(int(round(startingInteger/100*bPercentage))):
array.append("b")
for i in range(int(round(startingInteger/100*cPercentage))):
array.append("c")
print(array)
You would then need to scramble the resulting array (if that's what you mean by "random"), which should pose no problem if you import the "random" module and use the scrambled(). It's quick and dirty and inelegant but the logic is very explicit this way, hope it illustrates the idea.
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?
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 3 years ago.
Improve this question
So basically I want to calculate the average of (x) test marks. So far this is what I have:
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
However, I want it so that the average variable add ALL the inputs together. Right now, I made it so that it only calculates 3. I want it something like:
for i in range(7):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (**[sum of all test marks]**) / (i + 1)
print("Your average is", average, "percent.")
That's a good start. However, You can do it in a better way like this:
iters = int(input("How many numbers do you have?\n"))
sum = 0
for number in range(iters):
sum += int(input("Give a number: "))
print(f"The average of those inputs is {sum/iters}") # I'm assuming you have Python >= 3.6
Lets start by taking a look at the issues you encountered and how you can address them;
for i in range(3):
testmark = int(input("Enter one test mark: "))
print("Calculating...")
average = (testmark + testmark + testmark) / (i + 1)
print("Your average is", average, "percent.")
You override testmark every iteration, meaning you only ever store ONE value
You attempt to call i outside of the for loop, which will fail if i is not defined prior
We can adjust you code to be more resilient and provide the end-user more ability to modify the functions, such as how may iterations we test and the testmarks we would like to calculate.
test_marks = []
tests = int(input('How many tests are there? '))
#How many tests are there? 5
for i in range(tests):
test_marks.append(int(input("Enter one test mark: ")))
#Enter one test mark: 5
#Enter one test mark: 10
#Enter one test mark: 56
#Enter one test mark: 99
#Enter one test mark: 1
print(f"The average test mark is: {sum(test_marks) / len(test_marks)}")
#The average test mark is: 46.5
Declare an empty list to store marks in as test_marks
Prompt the user to define the total tests being entered
Iterate over the total tests and prompt the user for a mark
Calculate and print the average (This is Python 3.6+ Syntax!)
This is a good opportunity to dive a little deeper to bolster your understanding of some core workings on Python, i have included a few links for your learning!
Iterating over lists in Python
Appending & extending lists
Python 3.6 f-strings
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Functions are confusing me majorly.
What is wrong with my code here, I'm sure there are plenty things, but elaborate on what I'm doing wrong, please.
2000 steps is 1 mile, input is number of steps, output is miles walked.
def steps_to_miles(user_steps):
steps = input();
mile = steps / 2000
return user_steps
print('%0.2f' % user_steps)
Problems
Input returns a string, which you cannot do arithmetic on
Python doesn't use semicolons as line terminators
You're returning the number of steps, not the number of miles
You're not calling the function in the print statement
Your conversion function shouldn't ask for input
Try this
def steps_to_miles(user_steps):
miles = int(user_steps) / 2000
return miles
Example
>>> steps = input()
4321
>>> print( '%0.2f' % steps_to_miles( steps ) )
2.16
for calculating steps code will be like this:
def steps_to_miles():
steps = int(input('Enter Steps: '));
mile = steps / 2000
return mile
print('You Walked',steps_to_miles(),'miles')
The input() function waits for user input - if you feed it no arguments in your code it will show no message and wait for your input.
It does not represent the function input - that is already represented by user_steps parameter.
The user_steps is defined only within the scope of your function (the indented part) so the user_steps variable in your print statement is not the same variable.
I think you meant to write it like this
def steps_to_miles(steps):
return steps / 2000
user_steps = input("Please enter the number of steps walked:\t")
print("You have walked %0.2f miles !" % steps_to_miles(user_steps))
Your code should be like
def steps_to_miles():
steps = input();
mile = steps / 2000
return mile
print('%0.2f' %steps_to_miles())
This should work.
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 7 years ago.
Improve this question
I am working on lab in class and came across this problem:
Write a program using a for statement as a counting loop that adds up integers that the user enters. First the program asks how many numbers will be added up. Then the program prompts the user for each number. Finally it prints the sum.
I am having a lot of trouble answering this, if someone could help me that would be great, thank you!
So far I have written this:
NumOfInt=int(raw_input("How many numbers would you like to add up?"))
for i in range(NumOfInt):
I think this is what you're asking:
Write, using a for loop, a program that will ask the user how many numbers they want to add up. Then it will ask them this amount of times for a number which will be added to a total. This will then be printed.
If this is the case, then I believe you just need to ask the user for this amount of numbers and write the for loop in a similar fashion to your's:
NumOfInt = int(input("How many numbers would you like to add up? : "))
total = 0
for i in range (NumOfInt):
newnum = int(input("Enter a number! : "))
total += newnum
print("Your total is: " + str(total))
This will add their input to the total until the amount of numbers they have input exceeds NumOfInt:
How many numbers would you like to add up? : 4
Enter a number! : 1
Enter a number! : 2
Enter a number! : 3
Enter a number! : 4
Your total is: 10
I hope this helps :)
number = int(raw_input("How many numbers?"))
tot = 0
for x in range(number):
tot += int(raw_input("Enter next number:"))
print tot