Binary Math
Binary Math Code
Popcorn Hacks
Popcorn Hack 1
Problem:
What will be the result of this expression?
True or False and False
Answer:
- According to operator precedence,
and
is evaluated beforeor
. False and False
evaluates toFalse
.True or False
evaluates toTrue
.
Final Result:
True
Popcorn Hack 2
Problem:
What will be the result of this expression?
not True and False
Answer:
not True
evaluates toFalse
.False and False
evaluates toFalse
.
Final Result:
False
Popcorn Hack 3
Problem:
What will be the result of this expression?
True or False and not False
Answer:
not False
evaluates toTrue
.False and True
evaluates toFalse
.True or False
evaluates toTrue
.
Final Result:
True
# Homework Hack 1: Binary Converter
## Decimal to Binary Converter Function:
```python
def decimal_to_binary(decimal):
if decimal == 0:
return "0"
is_negative = decimal < 0
decimal = abs(decimal)
binary = ""
while decimal > 0:
binary = str(decimal % 2) + binary
decimal = decimal // 2
if is_negative:
return "-" + binary
return binary
# Example
print(decimal_to_binary(10)) # Output: 1010
print(decimal_to_binary(-5)) # Output: -101
1010
-101
Binary to Decimal Converter Function:
def binary_to_decimal(binary_str):
is_negative = binary_str.startswith("-")
if is_negative:
binary_str = binary_str[1:]
decimal = 0
for index, digit in enumerate(reversed(binary_str)):
if digit == "1":
decimal += 2 ** index
if is_negative:
return -decimal
return decimal
# Example
print(binary_to_decimal("1010")) # Output: 10
print(binary_to_decimal("-101")) # Output: -5
10
-5
Homework Hack 2: Difficulty Level Checker
Corrected Code:
import time
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
# Corrected logic: use 'and' instead of 'or'
while difficulty not in ["easy", "medium", "hard"]:
print("Please enter a valid difficulty level.")
difficulty = input("Enter difficulty (easy, medium, hard): ").lower().strip()
time.sleep(0.5)
print("Difficulty set to:", difficulty)
Difficulty set to: hard
Explanation of Fix:
The original while
condition was wrong because it used or
.
Using not in
with a list correctly checks if the entered difficulty is not one of the valid options.