Issue
Today I want to design a game to guess a list of number set by me. The player should print all the 5 numbers to win the game. And it is not allowed to print the repeated number. The code is as followed:
def guess():
print "Please input a number smaller than 10, let's see if it is in my plan."
print "You should figure out all the 5 numbers."
n = int(raw_input('>'))
my_list = [1, 3, 5, 7, 9]
your_list = []
count = 0
while count < 5:
if n in my_list:
if n not in your_list:
your_list.append(n)
count = count + 1
print "Good job! You have got %d numbers!" % count
n = int(raw_input('>'))
else:
print "You have already typed that. Input again!"
n = int(raw_input('>'))
else:
print "That is not what I want."
n = int(raw_input('>'))
print "Here you can see my plan:", my_list
print "You are so smart to guess out, you win!"
guess()
when I tried to run it, I was very confused to see the result:
Please input a number smaller than 10, let's see if it is in my plan
You should figure out all the 5 numbers
>1
Good job! You have got 1 numbers
>2
That is not what I want
>3
Good job! You have got 2 numbers
>5
Good job! You have got 3 numbers
>7
Good job! You have got 4 numbers
>4
Here you can see my plan: [1, 3, 5, 7, 9]
You are so smart to guess out, you win!
When I type 4, it should print "That is not what I want" instead of indicating “win”. Why did it go wrong?
Solution
On my side, it was working. Only point not working, I needed to input a 6th element before breaking out of the while loop. I'm just going to provide you with an overview of possible improvement and different implementations.
Moreover, you are using python 2. You should consider moving to python 3 especially if you just started to learn it.
Improvements:
while count < 5:
could simply becomewhile sorted(my_list) != sorted(your_list):
.- The nested statements can be simplified.
- A check on the input would be nice.
Implementation:
def guess_2():
print ("Please input a number smaller than 10, let's see if it is in my plan.")
print ("You should figure out all the 5 numbers.")
# Parameters
my_list = [1, 3, 5, 7, 9]
your_list = []
count = 0
while sorted(my_list) != (sorted(your_list)):
# Input:
not_valid = True
while not_valid:
try:
n = int(input('>'))
not_valid = False
except:
print ("Please input a number.")
if n in my_list and not n in your_list:
your_list.append(n)
count = count + 1
print ("Good job! You have got %d numbers!" % count)
elif n in my_list and n in your_list:
print ("You have already typed that. Input again!")
else:
print ("That is not what I want.")
print ("Here you can see my plan:", my_list)
print ("You are so smart to guess out, you win!")
Answered By - Mathieu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.