+ 1
How do I recognise strings.
I have a calculator and it expects a float input. (num1 = float(input("""Multiplier:""", )) I would lake to make it that it can accept the string "pi" and recognise that the user want to use pi which is stored in a variable. How do I do that?
3 ответов
+ 8
num1 = input("Multiplier:")
try:
if num1.lower() == 'pi':
num1 = 3.1415926535
else:
num1 = float(num1)
except:
num1 = 0.0
# checks for π, if not then converts to float, if fails then assigns 0.0
+ 1
These are great solutions however, my code already runs in a loop with if statement for each operations. But I found this to help me: float(input().replace("pi", 3.14.......))
0
def checkPi(x):
p=float(3.14)
num=str(x)
if num == "pi":
return p
else:
return num
num1=input("Multiplier:")
num1=checkPi(num1)
print(num1)
might be a better way, but this takes the input and runs it thru a function. if the function reads the string of pi it returns the number pi and if the function reads a number it returns the float