I'm an introvert to Python Code error

Asked 2 years ago, Updated 2 years ago, 17 views

import random

secret = random.randint(1, 99)

guess = 0

tries = 0

print "AHOY! I'm the Dread Pirate Roberts, and I have a secret!"

print "It is a number from 1 to 99. I'll give you 6 tries. "

while guess != secret and tries < 6:

guess = input("what's yer guess? ")

if guess < secret:

    print "Too low , ye scurvy dog!"

elif guess > secret:

    print "Too high, landlubber!"



tries = tries + 1

if guess = secret:

print "Avast! Ye got it! Found my secret, ye did!"

else:

print "No more guesses! Better luck next time, matey!"

print "The secret number was", secret

I like the book Hello Python, so I'm copying the example, but I keep getting errors;;;

If guess = secret appears in red with error red.

= The book says it's marked like this, but I can't change it to this... I'm not sure what the problem is.

I'd appreciate it if you could answer me I use 2.7.14 for the version, but I don't think it's because I used 2.7.3 for the book

It's frustrating.

python

2022-09-22 08:07

2 Answers

guess = input ("what's your guess?" ")

This is where the problem started.

When something is input through the input function, it passes the value in str (string) type. What this means is as described below.

After executing the code, you can enter a value on your keyboard when what's your guess? is displayed on the screen. If you enter the number 45, the string "45" is entered instead of the integer 45 in the Guess variable. That's why we can't do comparative operations like Guess < secret. Because Guess is a string and secret is an integer.

Therefore, the method of converting the input value into an integer in the Guess variable and storing it is as follows.

guess = int("what's your guess"? "))


2022-09-22 08:07

Looks like there's a print on the book

ifguess==secret:
    print "Avast! Ye got it!  Found my secret, ye did!"

Compare with ==.

Hello! Python programming example code: GitHub link


2022-09-22 08:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.