Comparing numbers gives the wrong result in Python

Sorry if this is a terrible question, but I'm really new to programming. I am trying to execute a small little test program.

If I enter a value less than 24, it will print the expression "You will become ...". If I enter any value greater than 24 (ONLY up to 99), it prints the expression "you're old."

The problem is that if you enter a value of 100 or more, it prints "You will be older than you know it." statement.

print ('What is your name?')
myName = input ()
print ('Hello, ' + myName)
print ('How old are you?, ' + myName)
myAge = input ()
if myAge > ('24'):
     print('You are old, ' + myName)
else:
     print('You will be old before you know it.')
+4
source share
4 answers

You are testing a string value myAgefor a different string value '24', as opposed to integer values.

if myAge > ('24'):
     print('You are old, ' + myName)

Must be

if int(myAge) > 24:
    print('You are old, {}'.format(myName))

Python , , , . , , int(the_string)

>>> "2" > "1"
True
>>> "02" > "1"
False
>>> int("02") > int("1")
True

, , print('You are old, ' + myName) print('You are old, {}'.format(myName)). , +. docs. .

+5

'100' '24', '1' " " , '2'. .

my_age = int(input())
if my_age > 24:
+1
print ('What is your name?')
myName = input ()
print ('Hello, ' + myName)
print ('How old are you?, ' + myName)
myAge = input ()
if int(myAge) > 24:
     print('You are old, ' + myName)
else:
     print('You will be old before you know it.')

. myAge (int) (), 24..

In addition, you usually should not add lines together, as they are considered non-python and slow. Try something like print ('Hello, %s' % myName)instead print ('Hello, ' + myName).

Python Tutorial

+1
source

Use int(myAge). I always use raw_input, and also you do not need to print your questions. Instead, include this question in your raw_inputs as follows:

myName = raw_input("Whats your name?")
print ('Hello, ' + myName)
myAge = raw_input('How old are you?, ' + myName)
if int(myAge) > ('24'):
    print('You are old, ' + myName)
else:
    print('You will be old before you know it.')
0
source

Source: https://habr.com/ru/post/1657408/


All Articles