Need 2.5 Code Practice Answers

Copy and paste the following code into the sandbox window. Modify the code so that user is asked to multiply two random numbers from 1 to 10 inclusive.

import random
random.seed()

# TODO: Update the following two lines with a call to a function
# from the random library that generates a random number between
# 1 and 10, inclusive.
a = 6 # HINT: Replace 6 with a function call
b = 3 # HINT: Replace 3 with a function call

print ("What is: " + str(a) + " X " + str(b) + "?")
ans = int(input("Your answer: "))
if (a * b == ans):
print ("Correct!")
else:
print ("Incorrect!")

Respuesta :

Answer:

import random

#random.seed() should not be used here as this method will produce same number again and again

a = random.randint(1,11) #this method will generate random number between 1 and 10  

b = random.randint(1,11)

print ("What is: " + str(a) + " X " + str(b) + "?")  

ans = int(input("Your answer: "))

if (a * b == ans):

   print ("Correct!")

else:

   print ("Incorrect!")

Output :

What is: 8 X 5?

Your answer: 40

Correct!

Explanation:

  • First for producing random numbers,random module has to be imported.
  • As mentioned in answer, random.seed() method is used to generate same random number again and again. Here we need to generate 2 different random numbers that is why we won't use this method.
  • To produce a random number, randint() method from random module is used. This method takes 2 parameters i.e. a low and high value. The low value is inclusive and the high value is exclusive. That is why , to get a number between [1,10], randint() takes 1 as low value(inclusive) and 11 as high value(exclusive).

fichoh

Using the randint() function in python, we can generate a random integer number within a stated range of integer values. The required lines of code are :

  • a = random.randint(1, 11)
  • b = random.randint(1, 11)

  • The random.randint() function is given two arguments which are the lower and upper boundaries of the integer we want to generate.

  • While the lower integer, 1 is included in the integer that could be generated, 11 is not inclusive

  • Therefore, the function only generates a random integer value between the values (1 and 10) for each variable.

Therefore, the running code :

a = random.randint(1, 11)

b = random.randint(1, 11)

print("What is: " + str(a) + " X " + str(b) + "?")

ans = int(input("Your answer: "))

if(a * b == ans):

print("Correct!")

else:

print("Incorrect!")

Learn more : https://brainly.com/question/13941657?referrer=searchResults