# What is wrong with the code?

+3 votes
asked Jul 9, 2020

I 'm a beginner at python and I was trying to make a simple number game. Whats wrong with this code.

Code:

import random

number_list=( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)

random_num = random.choice(number_list)

secretnumber=int(input("What is the number I am thinking (1-100)")

if secretnumber == random_num:
print("You Got It!")

else:
print("Keep on trying")

## 2 Answers

+1 vote
answered Jul 9, 2020 by (78,130 points)
selected Jul 9, 2020 by Ashrith Annamreddy

Best answer

You're missing one more parenthesis in the line

secretnumber=int(input("What is the number I am thinking (1-100)") # Add one more ) to the end.

Also, the program does not do a loop until the number is found (or the user gives up).

One more thing: you can generate the range of numbers from 1 to 100 with a Python function called range(). Have a look at the documentation how it works.

number_list = range(1, 101, 1)

Or simply you can just use randrange() to generate a random number in a given range, you don't even need number_list:

random_num = random.randrange(1, 101, 1)
commented Jul 9, 2020 by (410 points)
Thank You :)
commented Jul 11, 2020 by (78,130 points)
My pleasure.
commented Jul 13, 2020 by (100 points)
nice one......
commented Jul 15, 2020 by (210 points)
I personally use random.randint more than random.randrange.
+1 vote
answered Jul 15, 2020 by (210 points)

This is how I would do that same script:

number = random.randint(1, 100)

while True:

answer = int(input("Enter a whole number between 1 and 100"))

if answer == number:

print(f"Correct! the answer was: {number}!")

break

else:

print(f"{answer} is not correct! Try again!")

continue

Note: f"" is for formatting strings. You can put a variable in {} and it will replace the {} with the variable.

commented Jul 15, 2020 by (410 points)
Thanks, I'll try this too.