Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cleaner way to write this boolean comparison in Python? [closed]

The instructions for this assignment are:

We pass in 2 boolean inputs, cold and rainy.

You should output a single string: ('cold' or 'warm') ' and ' ('rainy' or 'dry') based on these inputs.

('cold' or 'warm') means you should use on of the two words, depending on the input boolean value.

for example False, True = 'warm and rainy'

The code I have put is:

# Get our boolean values from the command line
import sys
isCold= sys.argv[1] == 'True'
isRainy= sys.argv[2] == 'True'

# Your code goes here

condition = ""
if (isCold):
  condition += "cold"
else:
  condition += "warm"

if (isRainy):
  condition += " and rainy"
else:
  condition += " and dry"

print(condition)

The code is correct and outputs what it is supposed to, but I'm wondering is there a cleaner way to write this? I feel like there is but I can't quite figure it out.

like image 810
CodyT96 Avatar asked Jan 31 '26 04:01

CodyT96


1 Answers

You can combine conditional expressions with Python 3.6's f-strings to build the string with a single line of code:

condition = f"{'cold' if isCold else 'warm'} and {'rainy' if isRainy else 'dry'}"

In Python 2, the % string formatting operator can work as well:

condition = "%s and %s" % (
    'cold' if isCold else 'warm',
    'rainy' if isRainy else 'dry'
)
like image 69
cdhowie Avatar answered Feb 01 '26 18:02

cdhowie