57.3k views
5 votes
Write a program to do the following:

1. Define function that ensures a user can only input an integer in [1,6], where both ends are included. Return that integer.
2. Define a function. - Call the first function, put the return in variable user. - Computer generates a random integer in [1,6], put in variable computer. - Compare user and computer. If there are both equal, print "draw", otherwise, if the sum of user and computer is 7,8 , or 9 , print "user wins", otherwise, print "computer wins".
3. Define main function, call the second function.

1 Answer

4 votes

Final answer:

To write a program that meets the requirements given, you need to define three functions: one to validate user input, one to compare the user input with a randomly generated number, and one to call the second function. Here's an example code that illustrates this.

Step-by-step explanation:

To write a program that meets the requirements given, you need to define three functions. The first function should take user input and validate that it is an integer between 1 and 6. The second function should call the first function, generate a random number between 1 and 6, and compare the user input to the generated number. The third function should call the second function.

Here's an example code to achieve this:

import random

def get_user_input():
while True:
try:
user_input = int(input('Enter an integer between 1 and 6: '))
if 1 <= user_input <= 6:
return user_input
else:
print('Invalid input. Please enter an integer between 1 and 6.')
except ValueError:
print('Invalid input. Please enter an integer.')

def compare_numbers():
user = get_user_input()
computer = random.randint(1, 6)
print(f'User: {user}')
print(f'Computer: {computer}')
if user == computer:
print('Draw')
elif user + computer in [7, 8, 9]:
print('User wins')
else:
print('Computer wins')


def main():
compare_numbers()


if __name__ == '__main__':
main()
User Giamma
by
8.2k points