I am trying to make a binary to decimal coverter for a project in my computing class and I get this error with my code: "NameError: name 'z' is not defined" I've looked up answers and they fix one error but give another. Here is the code:
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
Any help would very much be appreciated!
Is this your first programming language? If so, let me introduce you to the concept of Variable Initialization.
When a computer is running code, it is processing bytes between the memory and the CPU. You probably know this already, but what you may not realize is that in your code, you are asking the computer to perform an operation on z, a variable that does not exist yet.
Keep something else in mind. Python does not need to initialize a variable in order to assign to it. So, why do you need to initialize z then before the program will run? The answer is simple: your first reference to z is an operation. Even though Python can automatically (without initialization) assign variables on the fly (different from other programming languages, usually), it still needs said variable to exist before math can be done with it.
The simple solution is to add z = 0 at any point before if bd == 'a': (because if you put it after, every time it goes into the if statement, it will over-write z with 0, ruining the logic for it.
Happy coding!
EDIT: In addition to this issue, the problem you will face with the error:
File "C:/Users/<USERNAME>/Desktop/Task 1.py", line 15, in <module> answer += 1*z**i TypeError: Can't convert 'int' object to str implicitly
Comes from the line:
if answer [ i ] == '1':
You see, when you type '1', you are saying that 1 is a string because you surround it with quotes, just the same as if you had written:
if answer [i] == "1":
What you need, instead, is the line
if answer [i] == 1:
Because that tells it to assign the number 1. Then, in the operation
answer += 1*z**i
You will be telling it to multiply three numbers instead of two numbers and the string "1".
In other languages like C, you must declare variables so that the computer knows the variable type. You would have to write string variable_name = "string text" in order to tell the computer that the variable is a string. In Python, the type casting happens automatically. Python sees variable = "string text" and it knows that because you used "", it is a string-type variable. Unfortunately, this means that you mistakenly made 1 a string.
Understand?
EDIT 2: The Happening
Okay, so you kept running into errors. And when I ran your code, I kept running into different errors. Because the of the tricky syntax and changing in types implicitly, I decided a much easier route to go was to rewrite the code and explain to you how and why it works. So, here is the new code:
bd = raw_input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""").lower()
## ORIGINAL CODE
##
##if bd == 'a':
## answer = input("""
##Please enter a Binary number. Up to, and including, 8 digits of 1 and/or 0
##""")
##
## print answer
## for i in range(8):
## z += 2
## if answer[i] == '1':
## answer += 1*z**i
##NEW CODE
if bd == 'a':
number_original = raw_input("Please enter a Binary number (a string of 1's and 0's)")
j = 0
number_converted = 0
for i in reversed(number):
if i == '1':
number_converted += 2**j
j+=1
print number_converted
From top to bottom, I'll go over what I wrote (I'll skip over your code) and I'll explain what it does and how it does it. Hopefully, this will help you in the decimal->binary conversion, as I assume you still have that to do.
So we begin with a few changes to your opening question. Where before you had bd=input(""), you now have bd=raw_input("").lower().
bd will still be a or b. But there was some shaky type handling in that statement, at least on my end. So, I made use of raw_input() which turns your answer into a string regardless of what it is. If you answer with 101010011 for instance, it will store the variable "101010011" and not the number 101010011 (though this would be wrong anyway-- it would be base 10, so it would actually be 101,010,011)... I also added .lower(), which as you may guess, turns your answer from whAtevErYouWritE to whateveryouwrite. This is an example of data sanitation and is vital in a good program, because people can be stupid and expect a computer to know what they mean. Computers, of course, have no idea what you mean, so you have to be very careful, know what mistakes a user can make, and plan ahead for it (BONUS: Here's a comic on the subject, which you will now definitely get).
So onto the meat of the program. We start by testing the condition for answer a with:
if bd == 'a':
Now, if you put in A, this would still work because of .lower(). If you put b, if wouldn't work (you have yet to put in your decimal->binary code!), and always remember that some day, someone will put in C, just to troll you, so include an elif for b and an else for anything else.
After this we encounter the first signs of it just being my code.
number_original = raw_input("Please enter a bin...
I've named it number_original because in code, it's always best practice to be clear and concise. Remember, the variable name this_is_the_variable_i_use_to_calculate_my_circumference is better than x so long as it explains clearly what it is, and helps other people understand your work. More advanced coders like to be ambiguous in this case, but a lot of the time it's just showing off.
I used raw_input() again because I actually want my number to be stored as a string. Remember when I said that 101010011 would be 101,010,011 to the computer? This would be very difficult to check, because the computer will assume a base 10 number. Thus, I just had it stored as a string, "101010011", and avoided that whole issue. There is also the added bonus to this that strings have manipulating methods that make it easier to work with, easier than the logic you were trying to introduce with range(8). That manipulator can be seen shortly.
Next, we declare our variables:
j = 0 #This 'j' accomplishes the same work done by your 'z' variable.
number_converted = 0 #this will be correctly converted by the end, as we add to it.
As mentioned in my original version of this post, these are initialized because the first time you operate on them inside the loop, you do math to them, and they need to exist as a number before you can do that. Even if they start at 0.
So now we look at the most interesting part, the for loop. Based on your original work, you kind of get how for loops work, but I'll go over them in a lot of detail so that hopefully, it helps you as much as possible when you need to see the big picture.
In a for loop, you are meant to iterate over a range of numbers. In your original code, you generated the range [0,1,2,3,4,5,6,7] to iterate over. I think you did this so you could keep track of which position in the binary number you were at, and I'm doing that as well, but in a different way, and one that I devised slowly in order to help you make the best decimal-to-binary system I could.
First, remember that number is a string now, so `"101010011". Next, realize that strings have indexes that can be accessed like so.
demo_string = "super mario brothers"
print demo_string[0]
print demo_string[1]
print demo_string[2]
print demo_string[3]
print demo_string[4:10]
print demo_string[:10] #if you leave out the first number, it starts at the beginning
print demo_string[10:] #if you leave out the last number, it ends at the end.
The above code will give you the following result:
s
u
p
e
r mari
super mari
o brothers
Take special notice that an index starts at 0, which is why demo_string[1] is u and not s.
Knowing this, you may begin to realize why we left number_original as a string: now we can use its index and iterate over that instead of making our own range with range()! This is why we can type for i in reverse(number_original); because that makes it loop from reverse(number_original)[0] to reverse(number_original)[i], as far as i is able to go. **Note:***We will go over why we are using* reverse() shortly.
It's time for number/computer science and math!
Have you learned yet about expressing every binary digit in the form of a power of two? I know you understand the concept underlying conversion in a binary number. Well, here's another cool trick you may or may not be aware of:
... # # # # # # <--The binary number, eg "101010"
...32 16 8 4 2 1 <--What each digit stands for in decimal form
... 5 4 3 2 1 0 <--The power of two that it stands for (2^5=32, 2^4=16...)
Another thing you'll realize is that typically (not always, but usually, binary numbers are read from right to left. This will come in handy in a moment).
So we're at the for loop. We know now that we can iterate through a string. But binary digits are read right-to-left. So, the binary number 10 = 2, not 10 = 1. This is why we wrote:
for i in reversed(string):
Because now, the for loop will iterate backwards! It will read the string right-to-left for us.
We also know that 2^x = (digit value in decimal).
So what we'll do in each iteration of the for loop is:
Check if i == '1' Note, this time we want it to be a string.
If i == '1', as in, the digit we're highlighting is a '1', then...
Take number_converted and add number_converted + 2^j
Then accumulate once to j, so it's one higher for the next trip.
To put this visually, I'll do two loops on the number 101010011.
Loop 4
j = 4
number_converted = 3 (still being converted)
is reversed(number_original)[3] == '1'? ( 1 1 0 0 1 0 1 0 1, so no)
then add 1 to j (j = 5)
Loop 5
j = 5
number_converted = 3 (still being converted)
is reversed(number_original)[4] == '1'? (1 1 0 0 1 0 1 0 1, so yes!)
then take number_converted (3) and add 2^j (2^5 = 16) to it (number_converted = 25)
then add 1 to j (j = 6)
Loop 6
j = 6
number_converted = 35 (still being converted)
this will continue until end!
So there you have it. Binary to decimal, in python.
If you have any questions about this, please ask. I remember being confused about this stuff when I first started!
And again, Happy Coding.
You need to assign z to a value becore you can use +=
Add z = 0 to the top of your script.
You never initialized z, so if you put z = 0 on the line above the if statement, you'll no longer have the issue
bd = input("""
Would you like to convert a number into:
a) Binary to Decimal
b) Decimal to Binary
""")
z = 0
if bd == 'a':
answer = input("""
Please enter a Binary number. Up to, and including, 8 digits of 1 and 0
""")
z += 2
for i in range(8):
if answer [ i ] == '1':
answer += 1*z**i
You never defined z.Try this code:
z = 0
bd = raw_input("Would you like to convert a number into:\n a) Binary to Decimal\n b) Decimal to Binary")
if bd == 'a':
answer = raw_input("Please enter a Binary number. Up to, and including, 8 digits of 1 and 0")
z += 2
ex = 0
for i in xrange(8):
if answer[i] == '1':
ex += 1*z**i
Related
Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.
For two numbers x and y that are base b, does this work for subtracting them? The numbers are given in string format and 2 <= b <= 10.
def n2b(n, b): # function to convert number n from base 10 to base b
if n == 0:
return 0
d = []
while n:
d.append(int(n % b))
n /= b
return ''.join(map(str,d[::-1]))
x = int(x,b) # convert to integers in base 10
y = int(y,b)
z = x - y
z = n2b(z,b) # convert back to base b, still in integer form
You have some confusion about how integers work in python. As the comments above say: python always stores integers in binary form and only converts them to a base when you print them. Depending on how you get x and y and how you need to give back z the code needs to be different
Situation 1: x, y and z are all integers
In this case you only need to do
z = x - y
And you're done.
Situation 2: x, y and z are all strings
In this case you first need to convert the strings into integers with the right base. I think that's your case, since you already deal with int(x, b) which is correct to transform a string into an integer (e.g. int("11", 2) gives 3 (integer represented in base 10). I would advice you to reform your code into something like this:
x_int = int(x, b)
y_int = int(y, b)
z_str = n2b(x_int - y_int, b)
In your code x is first a string and then an integer, which is bad practice. So e.g. use x_int instead of x.
Now it comes down to if your n2b function is correct. It looks good from the distance, although you're not handling signs and bases bigger than 10. There is a broadly accepted convert integer to base b answer so you might take this to be sure.
This is exactly the problem I just ran into in the google foobar challenge (which I suspect is the same source of ops problem). Granted its years later and op has no use for my answer but someone else might.
The issue
The function op used looked a lot like a copy and paste of this provided by the accepted answer but slightly modified (although I didn't look to closely).
I used the same function and quickly realized that I needed my output to be a string. Op appears to have realized the same thing based on the return statement at the end of the function.
This is why most of the test cases passed. Op did almost everything right.
See, the function begins with
if n==0:
return 0
One of the test cases in the foobar challenge uses 0 as the input. Its an easy line to miss but a very important one.
Solution
When I was presented this problem, I thought about the possible outlier cases. 0 was my first idea (which turned out to be right). I ran the program in vscode and would ya look at that - it failed.
This let me see the error message (in my case it was a list rather than int but op would have received a similar error).
The solution is simply changing return 0 to return '0' (a string rather than int)
I wasn't super excited to write out this answer since it feels a bit like cheating but its such a small detail that can be so infuriating to deal with. It doesn't solve the challenge that foobar gives you, just tells you how to get past a speed bump along the way.
Good luck infiltrating commander lambda's castle and hopefully this helps.
I have a project where i have to translate binary to hex. and decimal
Here is the code, it might not be that pretty any help is greatly appreciated:
the thing is that when i put in a 1 or a 0 it still gives me: There is an error please re-type your binary number. (one's and zero's) from my code
binary = raw_input("What Binary up to 8-bits would you like to use?")
if len(binary) <= 8:
for b in range(1,len(binary)+1):
if b ==2 or b==3 or b==4 or b==5 or b==6 or b==7 or b==8 or b==9:
print "**There is an error please re-type your binary number. (one's and zero's)**"
else:
print "Your code is too long! it needs to be 8 or less characters to
proccess!"
for b in range(1, len(binary)+1):
You're not iterating over the characters in the binary string, you're iterating from 1 to the length of the string. Also, I think your else block is overindented. Use this instead:
for b in binary:
This isn't going to fix all of your problems, though. For one, b will be a one-character string, so b==2 will always be false. I'd suggest changing b to an int and then seeing if it is greater than 1 - int(b) > 1.
However, what you really should be doing is testing each step you're not completely sure about to make sure you're actually getting what you expect. If you inserted a print(b) (or print b for Python 2) line in the for loop, you would have seen that it was not the values you expected.
I just started learning how to code, and I've been assigned a problem that I've been stuck on for many hours now and was hoping I could receive some hints at the very least to solve the problem. The main point of this exercise is to practice division and modulus. We can use basic statements, but nothing fancy like conditionals or anything since we haven't gotten to that point.
I need a user to input a # from 1 - 25, and then my program will let them know which unit and row that number is in. I've managed to get the code working for the rows, but I cannot figure out how to get the unit number.
Here's my code:
shelfNumber = int(raw_input('What is the shelf number? '))
row = int(shelfNumber / 5.1) + 1
unit =
I've tried a lot of things for unit, but none of them worked out, so I left it blank. I would appreciate any hints that anyone can give me. Thank you for any help.
Edit: I realized that I should try and at least show which ideas I've tried. If I do a regular modulo with # % 5, that works for everything but the multiples of 5 all the way on the right. I've also tried implementing the row #'s each # has but haven't gotten anywhere with that either. I've also tried something similar by dividing by a decimal, casting it as an int, then using modulo but failed, etc., etc.\
Edit: Sorry, I realized I uploaded the wrong image.
This problem would be easier if everything were countrd from 0 instead of from 1. That is, if the row and unit numbers were 0 to 4 instead of 1 to 5 and if the input value were 0 to 24 instead of 1 to 25.
In that case, we'd just write:
row = shelfNumber / 5
unit = shelfNumber % 5
Since everything starts ftom 1 ("is one-indexed" in the usual jargon), shelfNumber is one bigger than what that formula needs, and we need to make row and unit one bigger than what we computed.
But there's no trouble fixing that:
row = (shelfNumber - 1) / 5 + 1
unit = (shelfNumber - 1) % 5 + 1
In Python 3, you'd need to write // insted of /, and that will work with a reasonably recent Python 2.
Disclaimer: this problem is purely for fun. There may already be a solution (I've searched, no luck). I have several questions below, I'd appreciate an answer to any of them. RIYL...
I was inspired by a Three Stooges video I saw earlier, where it's shown that 13x7 = 28. You may have seen it. But I started wondering: is there SOME "base" in which this equation is true (I put base in quotations because I'm using the term in the wrong sense..see the final paragraph for what I mean)?
The answer is clearly no, if we define multiplication the same as for integers. If you break up 13 into "base" i, say 13 = 1*i+3, and 28 = 2*i+8, the multiplication factor of 7 ensures equality won't happen.
Okay, but now suppose you want to ask the question, is there some base where two numbers are equal, say 8 = 10 (I'm probably using the term "base" wrong, sorry for that)?
What I mean is, if we write 8 = 008 = 0*8^2+0*8+8, 10 = 010 = 0*8^2+1*8^1+0, then according to my (clearly wrong) usage of base, we have equality. I wrote some simple code, up to 3 digit numbers, to verify this. But my code sucks.
''' We define two numbers, such that n1 > n2...tho I'm flexible'''
n1 = "013"
n2 = "025"
''' Set the numbers as arrays. '''
num1 = list(range(len(n1)))
num2 = list(range(len(n2)))
for i in range(len(n1)):
num1[i] = int(n1[i])
for i in range(len(n2)):
num2[i] = int(n2[i])
''' Now we loop until we find a match, or no match is possible. '''
i = 1
j = 0
while True:
t1=(num1[0]*(i**2)+num1[1]*i+num1[2])
t2=(num2[0]*(i**2)+num2[1]*i+num2[2])
''' We need some way to check if t1 > t2 changes to t1 < t2 at some point
or vise-versa -> then we know no match is possible '''
if(i == 1):
if t1>t2:
j = 0
else: j = 1
if(t1==t2):
print("The numbers are equal in base %d" % i)
break
if(t2 > t1 and j == 0):
print("No base possible! After %d steps" % i)
break
if(t1 > t2 and j == 1):
print("No base possible! After %d steps" % i)
break
i=i+1
if (i > 2**6):
print("your search might be hopeless")
break
Sorry if your eyes hurt from that hideous code. I didn't even use numpy arrays. What I'm wondering is,
Has this problem been solved before, for arbitrary digits? If not..
I wanted to be flexible about the number of digits entered in n1 and n2. Is there a more clever way to define the functions t1 and t2 so that they adaptively expand in base i, depending on the number of digits entered?
Performance-wise I'm sure there's a better way to do my main iteration. This is the fun part for me, combined with the answer to part 2. Any suggestions?
If it happens that t1 and t2 forever remain ordered the same, as in the example from the code, the iteration will play out 2^^6 times. The iteration number was chosen arbitrarily, but one could imagine if we extended to many digits, one might need even more iterations! Surely there's a more clever way to stop the iteration?
Is my stopping condition just wrong?
Thanks so much for reading. This is not a homework assignment and the answers are probably completely useless. I'm just interested in seeing a real coder's take on it. It would be neat if this wasn't an already-solved problem. Much love.
You can make the problem simpler by applying a little bit of number of theory. Taking your first example 13x7=28 we can expand this out into an explicit polynomial over the base: (1n+3)*7=2n+8.
If this solution has real roots then the roots are values of n (bases) for which the equation is true. If you like this sort of problem then you should read Computational Number Theory by Shoup. It's a fun book.