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.
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'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With