2017-10-02 5 views
1

저는 Python을 배우고 있으며 프로젝트에 붙어 있습니다. 프로젝트의 주요 부분은 문제가되지 않는 collatz 시퀀스를 코딩하는 것이 었습니다. 다음 부분 만들기 위해, 시도 및 제외를 사용하여 사용자 입력의 유효성을 검사 할 수 있는지 만 정수 값에 나와 지금까지, 나는 다음과 같은 코드가 있습니다.Python : 조건이 충족 될 때까지 try/except 문을 반복하십시오.

def collatz(number): 
    if number % 2 == 0: 
     return number // 2 
    elif number % 2 == 1: 
     return (3*number) + 1 


print('Please enter a number:') 
number = '' 
try: 
    number = int(input()) 
except ValueError: 
    print('Incorrect type of data entered.\nPlease enter an integer!') 
    while number is not int: 
     try: 
      number = int(input()) 
     except ValueError: 
      print('Incorrect type of data entered.\nPlease enter an integer!') 

output = number 

while output != 1: 
    output = collatz(output) 
    print(output) 

내 문제는 난입니다 try/except 문을 반복하는 방법을 모르면 사용자로부터 정수를 얻을 수 있습니다. 정수 대신 문자열을 입력하면 프로그램은 루프에 들어가서 정수를 입력하면 나중에 도움이되지 않습니다. 나는 주제에 대해 꽤 많은 글을 읽었지 만, 앞서 말한 문제에 관해서는 밝히지 않았다.

어디서 잘못 가고 있는지 정말 알고 싶습니다.

+0

주어진 숫자가 정수인 경우에만 3 회만 확인하면 좋을 것입니다. 당신은'isinstance' 함수로 타입을 확인할 수 있습니다. – user1767754

+0

'number is not int'는 사실이 아닙니다. 'type (number) is int '가 작동하지 않지만 isinstance (number, int)가 아닌'을 사용하는 것이 더 좋습니다. 더 나은 방법은'true '를 사용하고 예외가 발생하지 않으면'break'를 사용하는 것입니다. –

+0

당신은 물론 맞습니다. 그건 내 바보 같은 실수 였어. 나는 타입()을 놓쳤다. 나는 체크 아웃 할 것이다 instance (number, int) - 나는 함수를 알지 못한다. 그러나 팁을위한 많은 감사합니다!! 대단히 감사합니다. – sar91

답변

0

당신은 사용할 수 있습니다 : x는 입력이고

valid=False 
while not valid: 
    try: 
     number=int(input()) 
     valid=True 
    except ValueError: 
     print('Incorrect type of data entered.\nPlease enter an integer!') 
+0

'while while'및 'break'입니다. –

0

그냥 isinstance(x, int)를 사용합니다.

x가 int이면 True를 반환합니다. 다른 해결책을 찾고 있습니다. 다른 방법을 찾고있는 경우에 대비하십시오!

+0

코멘트를 주셔서 감사합니다. isinstance 함수를 살펴 보겠습니다. 지금까지는 알지 못했습니다. 팁 고마워!! – sar91

관련 문제