2011-10-24 3 views
0
def subtract(num): 
    string = str(num) 
    a = string[0] 
    b = string[1] 
    c = string[2] 
    large = max(a, b, c) 
    small = min(a,b,c) 
    summation = int(a) + int(b) + int(c) 
    mid = summation - int(large) - int(small) 
    mid2 = str(mid) 
    ascend = large + mid2 + small 
    descend = small + mid2 + large 
    print('The digits in ascending order are', ascend) 
    print('The digits in descending order are', descend) 
    value = int(descend) - int(ascend) 
    return value 
def main(): 
    dummy = input('Type a three digit integer, please.\n') 
    if not len(dummy) == 3: 
     print('Error!') 
     main() 
    elif not dummy.isdigit(): 
     print('Error!') 
     main() 
    if len(dummy) == 3 and dummy.isdigit(): 
     subtract(dummy) 
     print('The value of the digits in descending order minus the digits in ascending order is', value) 
main() 

내가 입력 AA 번호는 (123)처럼, 내가 얻을 때 :어떻게이 반품/글로벌 오류를 수정합니까?

Type a three digit integer, please. 
123 
The digits in ascending order are 321 
The digits in descending order are 123 
Traceback (most recent call last): 
File "/Users/philvollman/Documents/NYU/Freshman /Fall Semester/Intro to Computer Programming/Assignments/Homework5PartA.py", line 29, in <module> 
main() 
File "/Users/philvollman/Documents/NYU/Freshman /Fall Semester/Intro to Computer Programming/Assignments/Homework5PartA.py", line 28, in main 
print('The value of the digits in descending order minus the digits in ascending order is', value2) 
NameError: global name 'value2' is not defined 
>>> 

내가 문에 해당하는 경우로 반환 된 값이해야하는 경우 내 첫 번째 기능은 실행되기 때문에 나는이 무엇입니까 왜 확실하지 않다 if 문 내에서 반환됩니다. 당신이 main에 정의되지 않은 value라는 이름의 변수를 참조 main의 끝에 print에 대한 호출에서

+0

붙여 넣은 코드에 'value2'가 전혀 없으므로 실제로 실행중인 코드와 동일하지 않습니다. – Useless

답변

4

. 따라서 오류. 아마 당신은 subtract로 호출에서 반환 된 값을 유지하기 위해 의미 :

value = subtract(dummy) 
print('The value ... is', value) 
난 당신이 게시 된 오류 메시지가 당신을 아주 게시 된 코드와 일치하지 않습니다하지 적어도 때문에, 따라 조금 어려운 코드를 찾는 것을 인정해야

.


기본 오해는 함수가 값을 반환하는 방식과 관련이 있다고 생각합니다. 값을 반환하는 함수를 호출 할 때는 해당 값을 호출 범위의 네임 스페이스에있는 값에 할당해야합니다.

그래서 당신은 값이 반환

subtract(dummy) 

을 썼다 그러나 당신은 아무것도에 할당하지 않았기 때문에, 그 값은 잊어 버린 때.

대신에 당신은 그것을

value = subtract(dummy) 
+0

감사! (이것은 바보 같은 실수입니다 ...>. <) –

0

함수 subtract의 끝에 선 return value이 호출자에게 가능한 값 , 그것은 마술 주입하지 않는하게 사용하기 위해서는 무언가에 할당해야 호출자의 네임 스페이스에 추가합니다. BTW (주의 범위에 정의되지 않은

value2 = subtract(dummy) 

을 시도하고 거기에서 이동 ...

0

당신은 이름 (값)에 의해 변수를 참조하기 때문에 당신이지고있다 게시 된 코드가 오류 메시지와 일치하지 않습니다. 거기에 값 2가 없습니다.).

그래서 하나는 일반 아닌 값이 함수 내에서 정의 된 변수의 이름을 반환하는 함수에서 값을 반환

value = subtract(dummy) 
print('The value of the digits in descending order minus the digits in ascending order is', value) 

print('The value of the digits in descending order minus the digits in ascending order is', subtract(dummy)) 

또는

을한다.

관련 문제