2014-11-23 143 views
0

我对Python(和编程)很陌生,只是试着做一个程序来转换小数。我已经定义了一个函数,因为我希望稍后在程序中重用它,但是我有一个问题将函数的结果传递给程序的其余部分。从函数返回值

print "For decimal to binary press B" 
print "For decimal to octal press O" 
print "For decimal to hexadecimal press H" 

def checker(n): 
    choice = n 
    while choice not in ("B", "O", "H"): 
     print "That is not a choice." 
     choice = str.upper(raw_input("Try again: ")) 
    else: 
     return choice 

firstgo = str.upper(raw_input("Enter your choice: ")) 
checker(firstgo) 

if choice == 'B': 
    n = int(raw_input("Enter the number to be converted to binary: ")) 
    f = bin(n) 
    print n, "in binary is", f[2:] 
elif choice == 'O': 
    n = int(raw_input("Enter the number to be converted to octal: ")) 
    f = oct(n) 
    print n, "in octal is", f[1:] 
elif choice == 'H': 
    n = int(raw_input("Enter the number to be converted to hexadecimal: ")) 
    f = hex(n) 
    print n, "in hexadecimal is", f[2:] 
+0

什么是你的问题/问题/堆栈跟踪? – bereal 2014-11-23 19:13:26

回答

1

您需要保存函数返回的值。 做这样的事情:

choice = checker(firstgo) 

然后保存结果从功能回来了。

您声明的每个变量仅在您声明的函数的范围内可用 因此当您在函数检查器外部使用choice时,程序不知道选择是什么,这就是为什么它不会工作。

+0

我在哪里添加该行?在功能内还是外面? – MHogg 2014-11-23 19:18:40

+0

当然功能的一面。这是您保存函数结果并在函数外部使用它的方法。只要你在函数内部使用了东西,你就不能在它之外使用它们。 – Idan 2014-11-23 19:20:28

+0

谢谢你的帮助! – MHogg 2014-11-23 19:26:16

0

相反的:

checker(firstgo) 

您需要:

choice = checker(firstgo) 

当你拥有了它,通过checker返回的值丢失。由checker定义的choice变量与其外部定义的变量不同。您可以对不同的范围中定义的不同变量使用相同的名称。这样你就不用担心同一个名字可能已经在程序的其他地方被使用了。

+0

谢谢你的帮助! – MHogg 2014-11-23 19:41:52