Problem Part A

Change the first if statement in the following script to an equivalent one-line if-expression. Test the resulting new script, and make sure it behaves like the original,

#!/usr/bin/env python

abbr = input ("What is the three-letter abbreviation of this course? ")

answer_status = 'wrong'
if abbr == 'DSP':
    answer_status = 'correct'

if answer_status=='correct':
    print('You answer is correct!')
else:
    print("wrong buddy...try again")

Problem Part B

Can you achieve the same goal as in (A) without if-expression or block, but instead using only tuple notation? Explain why your solution works.

Problem Part C

Modify the if block and the print statements that are only in the last part of the code,

if answer_status=='correct':
    print('You answer is correct!')
else:
    print("wrong buddy...try again")

to write a single-line Python statement that only uses print and tuple or list notations, to perform the same task as the original print and if-block statement.

Solution Part A

#!/usr/bin/env python

abbr = input ("What is the three-letter abbreviation of this course? ")

answer_status = 'correct' if abbr == 'DSP' else 'wrong'

if answer_status=='correct':
    print('You answer is correct!')
else:
    print("wrong buddy...try again")

Solution Part B

#!/usr/bin/env python

abbr = input ("What is the three-letter abbreviation of this course? ")

answer_status = ('wrong','correct')[abbr=='DSP']

if answer_status=='correct':
    print('You answer is correct!')
else:
    print("wrong buddy...try again")

Solution Part C

#!/usr/bin/env python

abbr = input ("What is the three-letter abbreviation of this course? ")

answer_status = ('wrong','correct')[abbr=='DSP']

print( ('wrong buddy...try again','You answer is correct!')[answer_status=='correct'] )

Comments