Can you make my code cleaner if possible? The essence of the game is for the player to enter a number greater than the computer. But if the player's number is 50 more than the number chosen by the computer, the player also loses.
This is my code:
from random import randint
#Variables
choice_ai = randint(0,1000)#AI selection
choice_p = int(input("Enter the number: "))#Player selection
choise_win = choice_ai + 50
print(choice_ai)
while True:
if choice_p == choice_ai:
print("You and the computer pick the same numbers")
elif choice_p <= choice_ai or choice_p >= choise_win:
print("You lose")
elif choice_p >= choice_ai and choice_p <= choise_win:
print("You won")
If you use the code above, you get an infinite loop printing always the same result, because nothing changes inside the loop and at each iteration of the loop the same condition is satisfied. If you want the game to keep going, you should rewrite your code as below:
from random import randint
while True:
choice_ai = randint(0,1000)#AI selection
choice_p = int(input("Enter the number: "))#Player selection
choise_win = choice_ai + 50
print(choice_ai)
if choice_p == choice_ai:
print("You and the computer pick the same numbers")
elif choice_p <= choice_ai or choice_p >= choise_win:
print("You lose")
elif choice_p >= choice_ai and choice_p <= choise_win:
print("You won")
Also, beware that in this way the loop is still infinite. So, if you want the game to finish at some point, you can, for example:
I had fun doing this:
from random import randint
# Variables
INPUT_MESSAGE = "\nPlease, choose a number : "
OVER_PICK_VALUE = 50
while True:
while not (raw_input := input(INPUT_MESSAGE)).isdigit():
print(f"'{raw_input}' is not a number")
choice_p = int(raw_input)
choice_ai = randint(0, 1000)
print(f"The computer chose {choice_ai}.")
if choice_p == choice_ai:
print("You and the computer both chose the same value")
elif choice_ai < choice_p < choice_ai+OVER_PICK_VALUE:
print("You won")
else:
print("You lost")
improvements done:
what you can add:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.