In: Computer Science
Write a program that generates a random number in the range of 1 through 100, and asks the user to guess what the number is. When the number is generated by the computer, don’t display the number to the user, but only display if the number generated is odd or even.
If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” Keep asking the user till the correct number is guessed. If the user enters 0 for the guess, the game terminates.
When the user successfully guesses the number, the application should congratulate the user and then display how many tries it took the user to guess the number. Moreover, display all the odd or even numbers starting at 1, up to that number. (Display all odd numbers if the number itself was odd, or all even numbers if the number was even). For example, assume that 16 was the generated number. The final display should be:
You took x tries to guess the number.
16 is an even number.
All even numbers up to 16 are: 1, 2, 4, 6, 8, 10, 12, 14
To generate the random number, you need to import the random library (import random) and use the randint function ( random.randint(1, 100) )
Python code for the given requirement
import random
# generating random number between 1 and 100
x = random.randint(1, 100)
#Printing if the number is Even or Odd
if (x % 2 == 0 ):
print("The generated number is Even")
else:
print("The generated number is Odd")
#Initializing the number of guesses.
count = 0
guess = -1
#Getting the number from user to guess the generated random number
while (guess != x):
# taking guessing number as input
guess = int(input("Guess a number: "))
count += 1
# Condition testing
if x == guess:
print("You took",count,"tries to guess the number")
# Once guessed, loop will break
break
elif x > guess:
print("Too low, try again")
elif x < guess:
print("Too high, try again")
#Printing all even numbers if x is even
if (x % 2 == 0 ):
print(x,"is an even number")
print("All even numbers up to", x, "are: ", end =" ")
for i in range (2,x,2):
print(i, end = ", ")
#Printing all odd numbers if x is odd
else:
print(x,"is an odd number")
print("All Odd numbers up to", x, "are: ", end =" ")
for i in range (1,x,2):
print(i, end = ", ")
Code screenshot:
Outputs: