2

How can a turn this code into a shorthand line of code? is it possible at all?

I would like the same purpose of the code, but with the least amount of lines possible

 inpt = input('Age: ')
    age = int(inpt)


if age <= 10:
    print('Kid')
elif age > 10 <= 20:
    print('Teen')    
elif age > 20:
    print('Adult')
1
  • 1
    age >10 <=20 doesn't do what you think. It expands to the equivalent of age > 10 and 10 <= 20. Which means your Adult case is never reached, you only print Kid or Teen. You want 10 < age <= 20. Commented Dec 23, 2017 at 0:27

4 Answers 4

4

Let's try:

text = 'kid' if age <= 10 else 'teen' if age <= 20 else 'adult'

Example:

age = 4
text = 'kid' if age <= 10 else 'teen' if age <= 20 else 'adult'
print(text)
age = 12
text = 'kid' if age <= 10 else 'teen' if age <= 20 else 'adult'
print(text)
age = 25
text = 'kid' if age <= 10 else 'teen' if age <= 20 else 'adult'
print(text)

Output:

kid
teen
adult
Sign up to request clarification or add additional context in comments.

Comments

1

It's possible to shorten it to:

age = int(input('Age: '))

print('Kid' if age <= 10 else 'Teen' if age <= 20 else 'Adult')

That said, unless you're doing one-liners for fun, I'd stick to your original code, after fixing the test for Teen and just making the Adult case a plain else (no need to retest > 20 since the previous cases eliminated the other possibilities).

Comments

0

This may not be that suggested but you can try out something using short circuiting. I personally think this is more readable(not for your example) but at the cost of extra comparisons.

input = input('Age: ')
age = int(input)


age <= 10 and print('Kid')

age > 10 and age <= 20 and print('Teen')

age > 20 and print('Adult')

Comments

0

What about:

age = int(input('Age: '))
print('Adult' if age > 20 else 'Kid' if age <= 10 else 'Teen')

In Python you have a ternary operator:

a if condition else b

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.