Max Regitnig
Max Regitnig

Reputation: 11

Basic python coding

Trying to do a simple guessing game program in python, but I'm more comfortable in java. When the correct number is entered, it says it is too high and won't exit the while loop. Any suggestions?

import random
comp_num = random.randint(1,101)
print comp_num
players_guess = raw_input("Guess a number between 1 and 100: ")
while players_guess != comp_num:
    if players_guess > comp_num:
        print "Your guess is too high!"
    elif players_guess < comp_num:
        print "Your guess is too low!"
    players_guess = raw_input("Guess another number between 1 and 100: ")
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"

Upvotes: 1

Views: 564

Answers (5)

Shubh Patel
Shubh Patel

Reputation: 79

in your code change in print formation and use 'int' datatype in numerical argument. i will change the cond so try it once:

    import random
comp_num = random.randint(1,101)
print ('comp_num')
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
    if players_guess > comp_num:
        print('Your guess is too high!')
    elif players_guess < comp_num:
        print('Your guess is too low!')
    players_guess = int(raw_input("Guess another number between 1 and 100: "))
print('CONGRATULATIONS! YOU GUESSED CORRECTLY!')

Upvotes: 0

Uddeshya Singh
Uddeshya Singh

Reputation: 21

Try this code:

import random
comp_num = random.randint(1,101)
print comp_num
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
    if players_guess > comp_num:
        print "Your guess is too high!"
    elif players_guess < comp_num:
        print "Your guess is too low!"
    players_guess = int(raw_input("Guess another number between 1 and 100: "))
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"

Upvotes: 0

Hackaholic
Hackaholic

Reputation: 19733

import random
comp_num = random.randint(1,101)
print comp_num
players_guess = int(raw_input("Guess a number between 1 and 100: "))
while players_guess != comp_num:
    if players_guess > comp_num:
        print "Your guess is too high!"
    elif players_guess < comp_num:
        print "Your guess is too low!"
   players_guess = int(raw_input("Guess another number between 1 and 100: "))
print "CONGRATULATIONS! YOU GUESSED CORRECTLY!"

you need to force the input to int

Upvotes: 0

khelwood
khelwood

Reputation: 59096

You are comparing a string to an int. That's why you get odd results.

Try this:

players_guess = int(raw_input("Guess a number between 1 and 100: "))

Upvotes: 5

ugo
ugo

Reputation: 2696

I would guess it is because you are comparing string and int. Whatever is captured from raw_input is captured as a string and, in Python:

print "1" > 100    # Will print true

For it to work, convert:

players_guess = raw_input("Guess a number between 1 and 100: ")

to

players_guess = int(raw_input("Guess a number between 1 and 100: "))

Upvotes: 8

Related Questions