0

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:

  1. 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
  2. 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("\nDecimal 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

Community
  • 1
  • 1
  • The question tagged as duplicate wasn't really. That was how to find the type of objects in a list -- not the type that a string could be converted into. – dawg Oct 21 '16 at 21:42

3 Answers3

1

Use exceptions! The int and float functions throw a ValueError exception when they can't convert the value passed.

while search == "d2b":
    dec2bin = input("\nDecimal Value: ")
    try:
        dec2bin = int(dec2bin)
    except ValueError:
        pass
    else:
        print("Binary Value: " + "{0:b}".format(dec2bin))
        continue

    try:
        dec2bin = float(dec2bin)
    except ValueError:
        pass
    else:
        #code for float to binary goes here
        continue

    if dec2bin == "back":
        search = 0

The order in which you try the conversions is important, since every value passed to int is valid with float, and every value passed to float is a valid to be passed to str

Francisco
  • 10,918
  • 6
  • 34
  • 45
  • This seems to work correctly in my code, thanks. If you don't mind- can floats be formatted to binary in similar ways to how ints can? I'm doing some experimenting now with what I know about formatting and getting errors. – Charlie Webb Oct 21 '16 at 21:40
  • @CharlieWebb Depends on what you mean by converting a `float` to binary, maybe [this](https://stackoverflow.com/questions/16444726/binary-representation-of-float-in-python-bits-not-hex) answers your question. – Francisco Oct 21 '16 at 21:57
  • So currently the code formats ints into binary as per: dec2bin = input("\nDecimal Value: ") try: dec2bin = int(dec2bin) except ValueError: pass else: print("Binary Value: " + "{0:b}".format(dec2bin)) continue Is something similar possible at the end of the float section of the code? Will I need to convert the float to a str or int? In terms of my own python knowledge reading that thread you linked is a bit of a no go at the moment- I don't understand most of the code in the replies. – Charlie Webb Oct 21 '16 at 22:10
0

You can use str.isalpha() and str.isdigit() to achieve this. Hence your code will be as:

while search == "d2b":
    dec2bin = input("\nDecimal Value: ")
    if dec2bin.lstrip("-").isdigit():
        print("Binary Value: " + "{0:b}".format(int(dec2bin))) # OR, simply bin(int(dec2bin))
    elif dec2bin.isalpha():  # OR, isalnum() based on the requirement
        if dec2bin == "back":
            search = 0
    else:
        try:
            _ = float(dec2bin)
        except:
            pass
        else:
            #code for float to binary goes here

Here, I am using str.lstrip() to remove - from the start of the string as .isdigit() can not check for negative number string.

Refer Python 3: String Methods for complete list of methods available with str objects.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

using ast.literal_eval() you can do a similar operation. here is a sample code of converting input() str to str, float, and int.

import ast  
def input_conv(strr):
   try:
      base = ast.literal_eval(strr)
      return base
   except:
      return strr

>>> b = input()
hi
>>> input_conv(b)
'hi'
>>> type(input_conv(b))
<class 'str'>
>>> b = input()
1
>>> type(input_conv(b))
<class 'int'>
>>> b = input()
1.222
>>> type(input_conv(b))
<class 'float'>