6 AnswersNew Answer
coffeeunderrun, which a question, such the answer 😃
Both are not same, Moreover, both are reciprocal on each other, is you will decide either of the answer from 1 , you will get the other answer
We can code an algorithm for the conversion of a binary number to the equivalent decimal number as a Python script. The input to the script is a string of bits, and its output is the integer that the string represents. The algorithm uses a loop that accumulates the sum of a set of integers. The sum is initially 0. The exponent that corresponds to the position of the string’s leftmost bit is the length of the bit string minus 1. The loop visits the digits in the string from the first to the last (left to right), but counts from the largest exponent of 2 down to 0 as it goes. Each digit is converted to its integer value (1 or 0), multiplied by its positional value, and the result is added to the ongoing total. A positional value is computed by using the ** operator. Here is the code for the script, followed by some example sessions in the shell: # frist---------------------------------------- #!/usr/bin/python3 def main(): bitString = input("Enter a string of bits: ") decimal = 0 exponent = len(bitString) - 1 for digit in bitString: decimal = decimal + int(digit) * 2 ** exponent exponent = exponent - 1 print("The integer value is", decimal) if __name__ == '__main__': main() #-End code -------------- Print: #----- Enter a string of bits: 1111 The integer value is 15 Enter a string of bits: 101 The integer value is 5
and the ternary operator or, in layman's terms, the short version of an if/else clause. When the value of a name is to be assigned according to some condition, sometimes it's easier and more readable to use the ternary operator instead of a proper if clause.
#!/usr/bin/python3 def main(): order_total = 247 # GBP# classic if/else form if order_total > 100: discount = 25 # GBPelse: else: discount = 0 # GBP print(order_total, discount) # ternary operator discount = 25 if order_total > 100 else 0 print(order_total, discount) if __name__ == '__main__': main()