Untitled
unknown
plain_text
2 years ago
1.8 kB
2
Indexable
import random "P1" def pow_of_two(num): count = 1 while count <= num: count = count * 2 return count // 2 # print (f"pow_of_two(1) -> {pow_of_two(1)}") # print (f"pow_of_two(12) -> {pow_of_two(12)}") # print (f"pow_of_two(20) -> {pow_of_two(20)}") # print (f"pow_of_two(256) -> {pow_of_two(256)}") "P2" def decimal_to_binary(num): """ input: int return: str calculates the binary in string given a positive number """ output = "" p = pow_of_two(num) while p > 0: if p <= num: num -= p output += "1" else: output += "0" p //= 2 return f'"{output}"' # print(f"\ndecimal_to_binary(1) -> {decimal_to_binary(1)}") # print(f"decimal_to_binary(3) -> {decimal_to_binary(3)}") # print(f"decimal_to_binary(4) -> {decimal_to_binary(4)}") # print(f"decimal_to_binary(15) -> {decimal_to_binary(15)}") "P3" def user_input(n): """ input: int return: int asks the user for a binary equivalent and returns the input """ binary_input = int(input(f"Do you know the binary equivalent of {n}?\n")) return binary_input # print(user_input(12345)) def main(): score = 0 n = random.randint(1,128) binary_input = int(input(f"Welcome to the Power Quiz game!\n Enter 'stop' to quit\nDo you know the binary equivalent of {n}?\n> ")) decimal = decimal_to_binary(n) while True: if binary_input != "quit": if (int(binary_input)) == decimal: score += 1 print(f"Correct answer! Your current score is {score}") else: print(f"Wrong answer! The correct answer is {decimal}") break else: print(f"Your final score is {score}/10. Hope you enjoyed the quiz.") break if __name__ == "__main__": main() main()
Editor is loading...