Can anyone please give me instruction how to write the program using this algorithm?
To convert binary integer to decimal, start from the left. Take your current total, multiply it by two and add the current digit. Continue until there are no more digits left.
First need to input the binary number as a string then select one by one digits of binary number
num=input("Enter the binary integer Number: ")
num=str(num)
decimal=''
rem=0
i=0
i=int(i)
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
decimal=int(rem)
print(decimal)
This code only calculate 4 digits of binary numbers. How can i add a while loop in this code?
Yes, you can put that in a loop:
binary = input("Enter the binary integer Number: ")
decimal = 0
for dig in binary:
decimal = decimal*2 + int(dig)
print(decimal)
Note that in Python 3, input already returns a string type value, so you don't need to convert it with str().
You can use the int() function:
binary_string = input('Please input a binary number: ')
print(int(binary_string, 2))
A one liner, just because it is possible:
print(int(input('Please input a binary number: '), 2))
But if you really want to do this with a loop, you can do:
binary_string = input('Please input a binary number: ')
result = 0
multiplier = 1
for digit in binary_string[::-1]:
result += int(digit) * multiplier
multiplier *= 2
print(result)
Related
I am trying get floating point number from user input with for loop in python 3.6.7:
for _ in range(int(input())):
foo = float(input())
Input:
1
12.3
No error, But when it is more than one value Error shows up:
for _ in range(int(input())):
foo = float(input())
Input:
2
2.5 3.1
ValueError: Could not convert string to float: '2.5 3.1'
any thoughts? thanks in advance.
When you input something and press Enter, input treats that data as a single string. So, 3.141<hit Enter> is a single string "3.141", and it can be converted to a floating-point number with float.
However, 3.141 5926<hit Enter here> is a single string "3.141 5926". Is that a representation of a single (floating-point) number? It's not (there are two numbers), so float can't convert that to a single number because of the space.
If you want to treat these numbers separated by a space as individual numbers, split the string and then convert each number:
data = input().split() # gives ['3.141', '5926']
for x in data:
print(float(x)) # converts each string to a number
decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
d_b(decimal//2,binary)
else :
print (binary)
return (binary)
print ("Decimal to Binary : ", d_b(decimal,binary = ''))
Output for input 34:
010001
Decimal to Binary : None
The function prints the answer but doesn't return it and then starts going back to function and starts deleting characters one by one from the string and finally returns none instead of the binary string.
Correct Code :
decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
if decimal > 0:
binary = d_b(int(decimal)//2,binary)
binary = binary + str(decimal % 2)
return (binary)
print ("Decimal to Binary :",d_b(decimal,binary = ''))
Try this, your welcome:
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
binary = d_b(int(decimal/2), binary) # <-- this is the line you should change
return binary
Or even shorter with the ternary operator:
return decimal > 1 ? d_b(int(decimal/2), binary): binary
I'm trying to make a program that will tell the user if the inputted number is either a prime number or not. I would like to know how to format it to where it will return the remainder. I have the following .py file that I made, but I keep getting error "not all arguments converted during string formatting":
i = 2
x = input("Input your proposed prime number now:\n")
number = x % i
print (number)
#Rishav had incorrect formatting, try:
x = int(input(Input your proposed prime number now:\n"))
if you are working with decimals, you can use:
y = float(input("Input a decimal > "))
input returns a string in Python3. Use :
x = int(input("Input your proposed prime number now:\n")
how to convert decimal to binary by using repeated division in python?
i know i have to use a while loop, and use modulus sign and others {%} and {//} to do this...but i need some kind of example for me to understand how its done so i can understand completely.
CORRECT ME, if I'm wrong:
number = int(input("Enter a numberto convert into binary: "))
result = ""
while number != 0:
remainder = number % 2 # gives the exact remainder
times = number // 2
result = str(remainder) + result
print("The binary representation is", result)
break
Thank You
Making a "break" without any condition, makes the loop useless, so the code only executes once no matter what.
-
If you don't need to keep the original number, you can change "number" as you go.
If you do need to keep the original number, you can make a different variable like "times".
You seem to have mixed these two scenarios together.
-
If you want to print all the steps, the print will be inside the loop so it prints multiple times.
If you only want to print the final result, then the print goes outside the loop.
while number != 0:
remainder = number % 2 # gives the exact remainder
number = number // 2
result = str(remainder) + result
print("The binary representation is", result)
-
The concatenation line:
Putting the print inside the loop might help you see how it works.
we can make an example:
the value in result might be "11010" (a string, with quotes)
the value in remainder might be 0 (an integer, no quotes)
str(remainder) turns the remainder into a string = "0" instead of 0
So when we look at the assignment statement:
result = str(remainder) + result
The right side of the assignment operator = is evaulated first.
The right side of the = is
str(remainder) + result
which, as we went over above has the values:
"0" + "11010"
This is string concatenation. It just puts one string on the end of the other one. The result is:
"0 11010"
"011010"
That is the value evaluated on the right side of the assignment statement.
result = "011010"
Now that is the value of result.
B_Number = 0
cnt = 0
while (N != 0):
rem = N % 2
c = pow(10, cnt)
B_Number += rem * c
N //= 2
# Count used to store exponent value
cnt += 1
return B_Number
Guys heres my problem:
I am trying to read an integer from the user(e.g. 12345)
How can i check if the pattern "34" exists in the first integer?
My constraint is that i cannot convert it to string and cannot use arrays.
Here is what i managed to write to print some of the patterns that exists in 12345:
import math
int1 = int(input("input an integer: "))
#I used this to find out how many digits are in the integer
count = math.ceil(math.log10(int1))
for i in range(count):
print (int1 % (10 ** (i+1)))
for i in range(count):
print (int1 // (10 ** (i+1)))
Since this seems to be homework, I won't provide an answer, but only a rough hint.
Hint: extract each digit of the number using divmod(n, 10), which returns n without the last digit and the last digit of n. Hold the current digit and the previous digit in variables and compare them with the pattern, 34, each time a new a digit is extracted.