user11761997
user11761997

Reputation:

Python, how to fix if and else statements

The question I am asking is: Write an expression that prints 'You must be rich!' if the variables young and famous are both True.

Sample output with inputs 'True' 'True': You must be rich!

What is wrong with the code below? Output is 'There is always the lottery...' instead of 'You must be rich!'.

young = (input() == 'True')
famous = (input() == 'True')

if (young == 'True') and (famous == 'True'):
    print('You must be rich!')
else:
    print('There is always the lottery...')

Upvotes: 0

Views: 1757

Answers (4)

Gerald Wichmann
Gerald Wichmann

Reputation: 457

Your assignment operators:

young = (input() == 'True')
famous = (input() == 'True')

result in those two variables being set as booleans. However your if statement is comparing them to strings:

if (young == 'True') and (famous == 'True'): 

Drop the single quotes around True in each instance above and it'll work because then the comparison is against the boolean value True, not the string 'True'.

Note that you could have checked this using the type keyword to print what type it is. I.e.:

print(type(young))
print(type('True'))

Upvotes: 0

Josh Sharkey
Josh Sharkey

Reputation: 1038

The first and second lines are actually booleans.

After the input function evaluates you are given either True or False depending on what you typed in.

So the if statement is evaluating

if ({True or False} == 'True') and ({True or False} == 'True'):

This will always evaluate to false as the boolean and the string representation are never equivalent.

Change to this

if input('Are you young?')=='True' and input('Are you famous?')=='True':
  print('you must me rich!')
else:
  print('there is always the lottery')

Upvotes: 0

Edwin Wallis
Edwin Wallis

Reputation: 71

You are checking your values against the strings 'True' when really you need to check them against the boolean value True. Just drop the quotation marks.

if (young == True) and (famous == True): 
    print('You must be rich!') 
else: 
    print('There is always the lottery...')

Upvotes: 2

Zachary Oldham
Zachary Oldham

Reputation: 868

What your code is doing is checking if young is equal to the string 'True' and if famous is equal to the string 'True'. You want

if (young and famous):

or if you want to write it out

if (young == True and famous == True):

Upvotes: 2

Related Questions