2013-07-14 3 views
-3

다음은 내 코드입니다. 거리가 있어야하는 장소가 포함 된 목록을 만들어야합니다. 사용자는 두 개의 다른 장소를 선택하여 마일에서 얼마나 멀리 떨어져 있는지 확인해야하며, 킬로미터로 변환 할 수있는 옵션이 제공됩니다. 그러나 일종의 코드를 완성 했으므로 if 문을 추가하여 "사용자가 place1, place2 또는 place 3을 입력하면 사용자에게 두 번째 장소를 입력하라는 요청을 계속합니다. 그렇지 않으면 프로그램을 다시 시작합니다 다시 처음으로. 그러나 if 문이 제대로 작성되지 않고, 지금은 "둘째가 정의되어 있지 않습니다"라고if 문이 예기치 않게 발생하는 이유는 무엇입니까?

print 'The available places to select from are:' 

print 'place1, place2, place3: ' 


place1 = 50 
place2 = 40 
place3 = 30 
Convert = 1.609344 



First = str(raw_input('Please select from the list where you are coming from')) 
if raw_input == 'place1' 'place2' 'place3': 
    Second = str(raw_input('Please select where you are going to: ')) 
else: 
    print 'please press any key to restart' 

Distance = First + Second 

print "the distance between the two places are", Distance, "miles" 



Kilometres = bool(input('Would you like to convert to Kilometres? please type True to convert or False to exit: ')) 
if True: 
     print 'The distance in Kilometres is',First + Second/Convert, 'Kilometres' 

else: 
     print 'press any ket to terminate' 
+5

오류가 자체적으로 표시되지 않습니까? 'if' 문에 들여 쓰기가 잘못되었다고합니다. if-else 블록을 왼쪽으로 4 칸 이동해야합니다. –

+1

들여 쓰기가 중요합니다 - 당신의'if' /'else'는 들여 쓰일 수 없습니다 –

+0

다른 오류는 First와 Second가 설정되기 전에 "거리"를 정의하고있는 것입니다. –

답변

7

들여 쓰기하지 마십시오 if 문.

First = int(input('Please select from the list where you are coming from')) 
if answer in ['place1', 'place2', 'place3']: 
    Second = int(input('Please select where you are going to: ')) 
else: 
    print 'please press any key to restart' 

대신

First = int(input('Please select from the list where you are coming from')) 
    if answer in ['place1', 'place2', 'place3']: 
     Second = int(input('Please select where you are going to: ')) 
    else: 
     print 'please press any key to restart' 

편집 :

도움이 필요하십니까? 나는 코드를 수정하고 희망 사항을 정리하기 위해 몇 가지 코멘트를 추가했다.

#using a dictionary allows us to associate, or hash, a string with a value 
place_dict = {"place1":50,"place2":40,"place3":30} 

convert = 1.609344 

def run_main(): 
    #placing the bulk of the program inside of a function allows for easy restarting 
    print 'The available places to select from are:' 
    print 'place1, place2, place3: ' 

    first = raw_input('Please select from the list where you are coming from: ') 
    second = raw_input('Please select where you are going: ') 
    #the values the user puts in are now stored in variables called 'first' and 'second', so if the user inputs "one", then first == "one" 

    if first not in place_dict or second not in place_dict: 
     #check to ensure that both first and second are in the place place dictionary 
     #if not, then return none to the main program 
     raw_input('Press any key to restart...') 
     return None 

    #an else is not needed here, because if the if statement executes, then we will not reach this point in the program 

    #this returns the dictionary value of the first value that the user inputs + the second. 
    return place_dict[first] + place_dict[second] 


if __name__ == "__main__": 
    #this line says that if we are running the program, then to execute. This is to guard against unwanted behavior when importing 

    distance = None 
    #set an initial variable to None 

    while distance is None: 
     #run the main program until we get an actual value for distance 
     distance = run_main() 

    print "the distance between the two places are", distance, "miles" 


    kilometres = bool(input('Would you like to convert to Kilometres? please type True to convert or False to exit: ')) 
    if kilometres == True: 
     print 'The distance in Kilometres is',distance/convert, 'Kilometres' 

    else: 
     print 'press any key to terminate'  
+0

답장을 보내 주셔서 감사합니다.하지만이 작업을 수행 할 때 제대로 작동하지 않는 것처럼 보였습니다. 예를 들어 들여 쓰기를 제거한 다음 place1이나 place2 또는 place3 이외의 다른 형식을 고의로 입력합니다. 다만 else 문을 출력하는 대신 충돌이 발생하여 place5가 출력되지 않습니다. 나는 그것이 정의되지 않았지만 내 else 문장에있는 것을 인쇄하기로되어 있다고 알고있다. 어떤 아이디어? – Daniel

+0

몇 가지 ... 지금 당장 당신은 다른 문장을 사용하여 프로그램을 다시 시작하지 않습니다. else 문을 쳤다가 코드가 실행을 계속하면 다시 시작되지 않습니다.이 문제를 해결하는 함수를 사용할 수 있습니다. 둘째로, 값을 First로 취한 상태로 저장하고 있지만 액세스는 답변입니다 (First in 인 경우에는 ...). 세 번째로, First에 대한 입력을 int로 변환 한 다음 문자열과 비교합니다. 당신은 그것을 던질 필요가 없습니다. – Schiem

+0

죄송합니다 Schiem 일종의 나를 당황하게하고, 나는 else 문장이 프로그램을 재시작하지 않는 방법을 이해할 수 있습니다.하지만 문제 2에 대해서는 이것을 교정하는 방법을 잘 모르겠습니다 :// 예, 세 번째는 모두입니다. 그 생각이 들었을 때, 나는 얼마 전에 그들이 거리를 나타내는 숫자를 가진 장소 이름을 포함하는 목록을 만들었지 만, 그들이 어떻게 그 일을 내 머리 꼭대기에서 어떻게했는지 기억하지 못했습니다. & 몇 가지 다른 소스를 사용하려고했는데 누군가가 리터럴과 관련된 문자열을 사용하여 목록을 만드는 예제를 찾을 수 없습니다. – Daniel

관련 문제