LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Simple Python program using bin (https://www.linuxquestions.org/questions/programming-9/simple-python-program-using-bin-823294/)

eveningsky339 07-31-2010 05:52 PM

Simple Python program using bin
 
I am exploring the Python 3 standard library and am currently attempting to test the bin function. It converts an integer into a binary string.

I believe the module I wrote is flawed somehow. Here's the source code:

Code:

#!/usr/bin/python3.1

#This module tests the bin() function.

import sys

def get_input():
        x = input("Enter an integer:  ")

def use_bin():
        print("The binary form of this integer is ", bin(x))

get_input()
use_bin()

And here's the output in the interpreter:

Code:

Enter an integer:  9000
The binary form of this integer is  0b10111
>>>
Enter an integer:  2
The binary form of this integer is  0b10111
>>>

As you can see, the binary form given is always 0b10111. I'm no expert on binary code (or hexadecimal notation), but surely 9000 and two would have different results?


EDIT: Added a line in the module to repeat back what integer the user entered, and then the binary form. It would appear that no matter what integer the user enters, Python thinks it's "23".

Example output:

Code:

>>>
Enter an integer:  1
You entered  23
The binary form of this integer is  0b10111
>>>


Berhanie 07-31-2010 07:26 PM

Code:

#!/usr/local/bin/python3.1


def get_input():
        # don't put the result in a local variable
        return input("Enter an integer:  ")

def use_bin(x):
        print("The binary form of this integer is ", bin(int(x)))

n = get_input()
use_bin(n)


paulsm4 07-31-2010 07:28 PM

Hi -

I happen to have Python 2.x and, as you're aware, "bin()" is new to Python 3.

BUT ....

1. You APPEAR to be doing everything right

2. I suspect the actual problem is with "input()", not "bin()"

SUGGESTIONS:
1. Declare "x" as global, initialize it, and print "x" before and after calling the function.

2. Try casting:
Code:

x = int(input("enter an integer: "))
'Hope that helps .. PSM

eveningsky339 07-31-2010 07:46 PM

Thank you both. I caught the local variable and fixed it, and also tried Berhanie's code. Everything appears to be in order. :)


All times are GMT -5. The time now is 12:41 PM.