2012-03-13 6 views
0

정수에서 2 진수로의 변환을 잘못 계산하고 있다고 생각합니다. 정수 6을 입력하고 이진수 0을 얻었습니다. 이것은 틀 렸습니다. 너희들도 도와 줄 수 있니? 여기에 새로운 코드가 있습니다.이 구문 오류를 이해하지 못합니다.

def ConvertNtoBinary(n): 

    binaryStr = '' 
    if n < 0: 
     print('Value is a negative integer') 

    if n == 0: 
     print('Binary value of 0 is 0') 
    else: 
     if n > 0: 
      binaryStr = str(n % 2) + binaryStr 
      n = n > 1 
    return binaryStr 

def main(): 
    n = int(input('Enter a positive integer please: ')) 
    binaryNumber = ConvertNtoBinary(n) 
    print('n converted to a binary number is: ',binaryNumber) 

main() 
+1

Windows와 어떻게 관련이 있습니까? 그리고 언제부터'ValueError'가'SyntaxError'입니까? – ThiefMaster

답변

3

raw_input()을 잊어 버렸습니다. 지금은 프롬프트 메시지를 작동하지 않는 정수로 변환하려고합니다.

n = int(raw_input('Enter a positive integer please: ')) 

물론 그 라인 주위에 try..except 좋은 생각이 될 것이다 : n = int('Enter a positive integer please: ')에서

try: 
    n = int(raw_input('Enter a positive integer please: ')) 
except ValueError: 
    n = 0 # you could also exit instead of using a default value 
+0

고마워요, 나는 그걸 잊어 버렸다고 믿을 수 없어요, 그 후에 바로 바이너리 단어에 유효하지 않은 문법 오류가 생깁니다. 나는 왜 변수를 정의하는지, 왜 이해가 안된다. – NateBUProgrammer

+1

@NateBUProgrammer : 어쩌면 당신은')'을 잊었을까요? –

+0

실제 오류 mesasge를 보지 않고 대답 할 수 없습니다. 어쩌면 괄호가 맞지 않을 수 있습니다. – ThiefMaster

0

, 당신은 문자열에서 int를 만들기 위해 노력하고있다 '는 긍정적 인 입력 ...'. raw_input()을 잊었다 고 가정합니다. 당신은

n = int(raw_input('Enter a positive integer please: '))

또는

n = raw_input('Enter a positive integer please: ') 
n = int(n) 
0

당신은 int로 리터럴 arbitratry 문자열을 캐스팅 할 수 할 수있는 중. 나는 사용자로부터 입력을받는 일종의 즉석 메서드를 호출하는 것이 무엇을 의미하는지 생각합니다.

관련 문제