我对这件事很陌生,请容忍我。我正在设计一个带有菜单的转换器,该菜单允许用户选择使用哪种数据类型(从数据类型到数据类型)来转换(例如)二进制到十进制(反之亦然)。任何帮助都将不胜感激。
到目前为止,当我运行程序时,代码会执行并显示菜单,询问我想要转换的内容,但这是我目前所能掌握的。
这是我迄今所做的代码..。
# introductory menu
print ("What are you converting from?");
def menu ():
print ("\n1. Decimal")
print ("2. Binary")
print ("3. Octal")
print ("4. Hexadecimal")
print ("5. Exit")
pick = int(input("Please enter an option: "))
return pick
def toBinary (b):
return bin(b)
def toDecimal (d):
return int(d)
def toOctal (o):
return oct(o)
def toHexadecimal (h):
return hex(h)
def main():
choice=menu()
while choice !=5:
if choice == 1:
#convert Decimal to ?
d = eval(input("What is your Decimal Value?: "))
print(int(toDecimal (d)))
elif choice == 2:
#convert Binary to ?
b = eval(input("What is your Binary Value?: "))
print(str(toBinary (b)))
elif choice == 3:
#convert Octal to ?
o = eval(input("What is your Octal Value?: "))
print(str(toOctal (o)))
elif choice == 4:
#convert Hexadecimal to ?
h = eval(input("What is your Hexadecimal Value?: "))
print(str(toHexadecimal (h)))
else:
print ("Whoops!!! That is an Invalid Entry")
main()以下是正在运行的节目的截图。
正如你所看到的,它并没有做我真正想做的事情。
发布于 2019-12-21 15:45:49
您需要将menu()方法包含在while循环中,否则选择值将始终是相同的,并且永远不会从2中更改(就像您共享的屏幕截图一样)。
choice=0
while choice !=5:
choice=menu()此外,如果希望转换程序正常工作,则需要添加另一个方法来选择要转换输入值的方式:
def transform_to(value):
print("Transform to ")
choice = menu()
if choice == 1:
print(int(toDecimal (value)))
choice=5
elif choice == 2:
print(str(toBinary (value)))
choice=5
elif choice == 3:
print(str(toOctal (value)))
choice=5
elif choice == 4:
print(str(toHexadecimal (value)))
choice=5所以你的最后剧本是:
# introductory menu
print ("What are you converting from?");
def menu ():
print ("\n1. Decimal")
print ("2. Binary")
print ("3. Octal")
print ("4. Hexadecimal")
print ("5. Exit")
pick = int(input("Please enter an option: "))
return pick
def toBinary (b):
return bin(b)
def toDecimal (d):
return int(d)
def toOctal (o):
return oct(o)
def toHexadecimal (h):
return hex(h)
def transform_to(value):
print("Transform to ")
choice = menu()
if choice == 1:
print(int(toDecimal (value)))
choice=5
elif choice == 2:
print(str(toBinary (value)))
choice=5
elif choice == 3:
print(str(toOctal (value)))
choice=5
elif choice == 4:
print(str(toHexadecimal (value)))
choice=5
def main():
choice=0
while choice !=5:
choice=menu()
if choice == 1:
#convert Decimal to ?
d = eval(input("What is your Decimal Value?: "))
transform_to(d)
print(int(toDecimal (d)))
elif choice == 2:
#convert Binary to ?
b = eval(input("What is your Binary Value?: "))
transform_to(b)
elif choice == 3:
#convert Octal to ?
o = eval(input("What is your Octal Value?: "))
transform_to(o)
elif choice == 4:
#convert Hexadecimal to ?
h = eval(input("What is your Hexadecimal Value?: "))
transform_to(h)
main()https://stackoverflow.com/questions/59334185
复制相似问题