2016-06-29 3 views
0
#Write a short program that will do the following 
#Set a value your favorite number between 0 and 100 
#Ask the user to guess your favorite number between 0 and 100 
#Repeat until they guess that number and tell them how many tries it took 
#If the value they guessed is not between 0 and 100 
#tell the user invalid guess and do not count that as an attempt 

내 문제는 사용자가 0에서 100 사이의 숫자를 추측하더라도 "잘못된 추측. 다시 시도하십시오"라는 내용을 계속 인쇄합니다. 허용되는 입력 (1-100)이면 반복문을 제어하여 print 문을 건너 뛰고 반복 질문을합니까? 미리 감사드립니다!Python에서 입력이 유효한 경우 조건부 if 루프가 실행되지 않도록하려면 어떻게해야합니까?

favoriteNumber = 7 
attempts = 0 

guess = raw_input("Guess a number between 0 and 100: ") 

if (guess < 0) or (guess > 100): 
    print "Invalid guess. Try again" 
    guess = raw_input("Guess a number between 0 and 100: ") 

attempts1 = str(attempts) 
print "it took " + attempts1 + "attempts." 
+1

무엇 루프를 반환 raw_input을? 코드에는 아무 곳이나 반복 할 필요가 없습니다. 루프가 아닌 경우 – kindall

+0

입니다. –

답변

0

사용 입력이 숫자에 > 100 캐스트가 항상하고 raw_input을하지 문자열, 그리고 문자열

favoriteNumber = 7 
attempts = 0 


while True: 
    guess = input("Guess a number between 0 and 100: ") 
    if (guess < 0) or (guess > 100): 

     attempts=attempts+1 
     print "Invalid guess. Try again" 
    else: 
     attempts=attempts+1 
     break 

attempts1 = str(attempts) 
print "it took " + attempts1 + " attempts." 
+0

모두에게 많은 감사를 표하지만 가장 도움이되었습니다. – Ben

0

문자열을 정수로 변환하지 않으면 허용하지만 숫자에 적용되는 모든 규칙은 false를 반환합니다.

favoriteNumber = 7 
attempts = 0 

guess = raw_input("Guess a number between 0 and 100: ") 

if (int(guess) < 0) or (int(guess) > 100): 
    print "Invalid guess. Try again" 
    guess = raw_input("Guess a number between 0 and 100: ") 

attempts1 = str(attempts) 
print "it took " + attempts1 + " attempts." 

파이썬 3.4에서 원래의 코드가 대신 정수의 문자열이 있음을 알려주는 오류를 얻을 : 다음은 작업 예입니다. 하지만 Paul이 말했듯이 raw_input은 int() 명령 안에 넣을 수 있습니다.

0

당신은 당신이 정수를 얻을 수 있도록, int(raw_input())

관련 문제