oeno3era
oeno3era

Reputation: 21

Formatting floats using an f-string in a conditional statement while checking if the user input is an integer

I'm working on a program that

  1. receives a positive integer as an input
  2. multiplies the input by a certain number
  3. returns the result so that it has 2-decimal places

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

Answers (3)

Gergely Szerovay
Gergely Szerovay

Reputation: 159

There is two problems with the 'f-string' part of your code:

  • For nested expression, you need additional brackets
  • You can't escape the quote character (in Why don't you check...) inside an f-string

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

Mayank Porwal
Mayank Porwal

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

azro
azro

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

Related Questions