1

I'm pretty new here and looking for some more programming knowledge. I'm sorry if this question is already answered or if it might be stupid.

I'm trying to build a simple programming game. But the while function is not letting me. I guess it's something really simple for you guys, so please help!

I want to create a looping game for guessing the right number.

I've tried looking on google for different codes but no luck so far.

#This is a guess the number game.
import random

print('Hello, what is your name?')
name = input()

print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

print('Take a guess......')
guess = int(input()

while guess != secretNumber:
    print('Take a guess.')


if guess == secretNumber:
    print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')

The problem seems to be in the "while function", I want it to loop non stop until someone guesses the number.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Robert Grootjen
  • 197
  • 2
  • 13
  • You missed closing parenthesis after input() – Hayat Aug 26 '19 at 20:34
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Trenton McKinney Aug 26 '19 at 20:39

2 Answers2

1

I am a beginner as well! It's nice to have someone to learn together.

Here are what I think you are trying to do:

import random

print('Hello, what is your name?')
name = input()

print('Well, ' + name + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1, 20)

print('Take a guess......')
guess = int(input())
guessesTaken = 1

while guess != secretNumber:
    print('Take another guess.')
    guessesTaken += 1
    guess = int(input())

if guess == secretNumber:
    print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')

What I edited in there:

1) I added the right parenthesis on line #10;

2) On line #15 I add 1 to guessesTaken every time a guess is wrong to count how many attempts there have been;

3) On line #16 I ask for an input again after the previous guess is wrong, so that the player actually has a chance to reenter a different guess.

Like I said, I am new to python as well (first time posting here actually). But I hope this helps!

RaspXin
  • 26
  • 1
  • 4
0

You are not asking for another guess in the loop (there's not input in the loop), you should use an infinite while loop and break out of it when the guess is correct. You can also put the text you want to prompt inside the input function instead of printing it with print:

while True:
    guess = int(input('Take a guess: '))
    if guess == secretNumber:
        print('Good job, ' + name + '! You guessed my number in ' + str(guessesTaken) + ' guesses!')
        break
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55