Using try and except statement for exception handling, using raise to throw out the exception and stop the program.
An if else statement is a conditional statement that runs a different set of statements depending on whether an expression is true or false.
The def keyword defines a function. A function is a group of statements that can be called upon repeatedly to perform a specific task.
The import keyword is used to import modules. You can choose to import parts from a module, by using the from keyword.
When two fair dice are rolled, let the sum of the number shown on each die be n. Write a code or draw a flowchart to find P(n). The input is n, where 2 n 12 and the output is P(n).
The print built-in function displays the specified string to the output.
X
Game Code
The for loop repeats codes within itself for a fixed number of times determined by the specified expression.
00:00
from fractions import Fraction
def load_input(input_str):
try:
x = int(input(input_str))
if x<2 or x>12:
raise ValueError
else:
return x;
except ValueError:
print("Enter integer between 2 to 12!")
raise
n = load_input('Enter a positive integer n: ')
sumOf2dices = []
for i in range(1,7):
for j in range(1,7):
sumOf2dices.append(i + j)
frequencies = [0] * (1+max(sumOf2dices))
for i in sumOf2dices:
frequencies[i] += 1
if n >= len(frequencies) or n < 0:
probability = 0
else:
probability = Fraction(frequencies[n],36)
print("The probability that the sum of the two numbers is equal to {n} is {probability}.".format(n=n, probability=probability))
A variable stores a value that can be referred to or modified later in the program. A name, output, is assigned to the variable as an identifier in this case.