Python beginner here. I'm writing a program that uses an infinite loop and allows the user to enter key terms to access different 'tools' or 'modules'.
Within one of these 'modules', the user can enter a value and convert it to binary. I want to:
- Allow the program to recognize if the value is either an int or a
float and then run code that converts the value to binary
- Allow the program to recognize if the value entered is a str and the str says 'back', in which the current loop will be exited.
As far as I know this issue is occurring as input() converts whatever is entered to a str automatically (due to: http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html "First it prints the string you give as a parameter").
How can I make the code below recognize if the input is a str, float, or int and then execute the relevant if statements? Currently, this part of my code can accept 'back' to exit out of the loop but will take any int or float value as a str, making the program prompt the user to enter a decimal value once more.
#decimal to binary
while search == "d2b":
dec2bin = input("
Decimal Value: ")
if type(dec2bin) == int:
print("Binary Value: " + "{0:b}".format(dec2bin))
elif type (dec2bin) == str:
if dec2bin == "back":
search = 0
elif type (dec2bin) == float:
#code for float to binary goes here
Edit: not the same as this thread (Python: Analyzing input to see if its an integer, float, or string), as a list is used there over input()
E2: cannot seem to use suggested duplicate as a solution to issue. However, a comment in this thread by Francisco has the solution
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…