Home > Blockchain >  Can't get a secondary if/else question to work
Can't get a secondary if/else question to work

Time:11-23

I am brand new to coding and I am trying to get some basics down, and I think I have made a mistake in the code below, for the second if/else statement (asking are you sure?) the if statement is coming back as always true regardless of the input.

def age_calc():
    target_year= input('What future year do you want to know your age?')
    born_year = input ('what year were you born?')
    target_year = int(target_year)
    born_year = int(born_year)
    age = target_year - born_year
    print('In the year', target_year, 'you will be', age)

question=input('Do you want to know how old you be in a certain year?').lower()
if [question.startswith('y'), 'sure', 'ok',]:
    age_calc()
else:
    y_or_n =input('Are you sure?').lower()
    if [y_or_n.startswith('y'), 'definitely', 'I am']:
        print ('ok then')
    else:
        age_calc()

This is a little frustrating as this previous version works fine:

if [question.startswith('y'), 'sure'.lower, 'ok'.lower]:
     target_year= input('What future year do you want to know your age?')
     born_year = input ('what year were you born?')
     target_year = int(target_year)
     born_year = int(born_year)
     age = target_year - born_year
     print('In the year', target_year, 'you will be', age)
else:
     print('ok then')

The if/else statement in this code works correctly so I'm guessing I've used the wrong wording in the first code.

CodePudding user response:

[question.startswith('y'), 'sure', 'ok',] is always true, since a non-empty list is truthy (https://docs.python.org/3/library/stdtypes.html#truth). Because of this your else part is never reached.

You might instead want:

if question.startswith('y') or question in ('sure', 'ok'):

CodePudding user response:

as j1-lee said, you are evaluating the wrong thing. In your code, the if statement only checks if the list is not empty, which never is the way you wrote it.

and also you got confused evaluating the elements in the list itself

Here is another of the many ways you could do it:

#you can pack the affirmations in a list, above the code so you don't write it twice for both if/elses

affirmation_prefixes = ["y","ok", "sure"] # etc, you get the idea

#and then you use it like this

if any( [y_or_n.lower().startswith( x.lower() ) for x in affirmation_prefixes] ):

i mean, you can do a lot of different approaches with it, just remember if [not, empty, list] is True, you actually will use this a lot in the future to check if data is empty

  • Related