python进制转换用if语句怎么写
时间: 2024-05-31 08:04:41 浏览: 109
在Python中,可以使用if语句来实现进制转换。以下是一个示例代码,演示了如何将一个十进制数转换为二进制、八进制和十六进制:
```python
decimal_num = 10
binary_num = ""
octal_num = ""
hexadecimal_num = ""
# 转换为二进制
if decimal_num == 0:
binary_num = "0"
else:
while decimal_num > 0:
binary_num = str(decimal_num % 2) + binary_num
decimal_num = decimal_num // 2
# 转换为八进制
if decimal_num == 0:
octal_num = "0"
else:
while decimal_num > 0:
octal_num = str(decimal_num % 8) + octal_num
decimal_num = decimal_num // 8
# 转换为十六进制
if decimal_num == 0:
hexadecimal_num = "0"
else:
while decimal_num > 0:
remainder = decimal_num % 16
if remainder < 10:
hexadecimal_num = str(remainder) + hexadecimal_num
else:
hexadecimal_num = chr(ord('A') + remainder - 10) + hexadecimal_num
decimal_num = decimal_num // 16
print("二进制:", binary_num)
print("八进制:", octal_num)
print("十六进制:", hexadecimal_num)
```
阅读全文