Reputation: 21
I'm working on a program that
This is how the program currently functions:
// Enter a positive integer...: 1
// [Expected Outcome] Result: 1.00
// [Actual Outcome] ValueError: Invalid format specifier
There seems to be a problem with the say I'm formatting the f-string when printing the result. Could you please check what's wrong with the syntax?
rand_num = 1.0
value = int(input('Enter a positive integer...: '))
result = rand_num * value
print(f'Result: {result:.2f if value > 0 else "Why don't you check your input value again?"}')
Upvotes: 2
Views: 1176
Reputation: 159
There is two problems with the 'f-string' part of your code:
I added the brackets and moved the message to a separate variable, now it works:
rand_num = 1.0
value = int(input('Enter a positive integer...: '))
result = rand_num * value
input_check_msg = 'Why don\'t you check your input value again?'
print(f"Result: {result:{'.2f' if value > 0 else input_check_msg}}")
Upvotes: 0
Reputation: 34046
You can un-complicate your loop like this:
In [600]: if value > 0:
...: print(f'Result: {result:.2f}')
...: else:
...: print("Why don't you check your input value again?")
...:
Result: 1.00
Upvotes: 0
Reputation: 54148
Do not put the if/else
inside the f-string
, just
print(f'Result: {result:.2f}' if value > 0 else "Why don't you check your input value again?")
Upvotes: 1