2014-03-01 3 views
1

내 프로그램 askTheUser()도 내가 원하는 방식으로 작동하지만 어떻게 든 "for"또는 "while"루프를 포함하도록 변경해야합니다. 어떤 제안? 결말 결과는 0과 1의 목록으로되어 있습니다. 예를 들어, [1,1,1,1,1]은 모든 주사위를 다시 굴리려는 것입니다.코드를 작성했지만 잠시 또는 루프를 사용해야합니다

import random 
def askTheUser(): 
    userList = [] 
    choice = input("Would you like to re-roll dice 1? If so, enter 'Yes'. If not, enter 'No'.") 
    if choice == str("Yes"): 
     userList.append(1) 
    else: 
     userList.append(0) 
    choice2 = input("Would you like to re-roll dice 2? If so, enter 'Yes'. If not, enter 'No'.") 
    if choice2 == str("Yes"): 
     userList.append(1) 
    else: 
     userList.append(0) 
    choice3 = input("Would you like to re-roll dice 3? If so, enter 'Yes'. If not, enter 'No'.") 
    if choice3 == str("Yes"): 
     userList.append(1) 
    else: 
     userList.append(0)  
    choice4 = input("Would you like to re-roll dice 4? If so, enter 'Yes'. If not, enter 'No'.") 
    if choice4 == str("Yes"): 
     userList.append(1) 
    else: 
     userList.append(0)  
    choice5 = input("Would you like to re-roll dice 5? If so, enter 'Yes'. If not, enter 'No'.") 
    if choice5 == str("Yes"): 
     userList.append(1) 
    else: 
     userList.append(0) 
    return userList 

답변

0
def askTheUser(): 
    userList = [] 
    for i in range(5): 
     choice = raw_input("Would you like to re-roll dice "+str(i)+"? If so, enter 'Yes'. If not, enter 'No'.") 
     if choice == str("Yes"): 
      userList.append(1) 

     else: 
      userList.append(0) 

    return userList 

이를 확인하시기 바랍니다!

+0

나는'break' 또는'continue' 문이 필요 없다고 생각합니다. 'continue'는 단순히 불필요한 반면'break'는 코드가 언 롤링 된 원고와 다르게 동작합니다. – Blckknght

+0

옵션이 '아니오'이면 다음 루프에 사용하지 않습니다. na ?? – rajpython

+1

코드는 각 다이를 다시 롤링할지 여부를 묻는 의미입니다.나는 주사위 1-3을 다시 굴리지 않고도 4 번 주사위를 굴릴 수 있다고 생각합니다. – poke

0
def askTheUser(): 
    userList=[] 
    for i in range(5): 
     choice = input("Would you like to re-roll dice %d? If so, enter 'Yes'. If not, enter 'No'."%(i+1)) 
     userList.append(1 if choice == 'Yes' else 0) 
    return userList 
+0

@poke는이를 알지 못했습니다. 업데이트 됨;) – zhangxaochen

0

이렇게하면됩니다.

def askTheUser(): 
    userList = [] 
    for i in range(1,6): 
     question = "Would you like to re-roll dice " + str(i) + "? If so, enter 'Yes'. If not, enter 'No'." 
     choice = input(question) 
     if choice == str("Yes"): 
      userList.append(1) 
     else: 
      userList.append(0) 
    return userList 
+0

무엇인가의 이유로, 주사위를 다시 굴리고 싶을 때만 묻습니다. 그리고 대답 할 때, 대신 나에게 [0] 또는 [1] 중 하나를줍니다. [1,1,0,1,0] – user3367018

+0

@ user3367018 Python 2 또는 3을 실행하고 있습니까? – erdekhayser

5

같은 코드를 반복해서 작성한다는 사실을 알게 되 자마자이를 자동화하는 방법에 대해 생각해야합니다. 귀하의 경우 5 부분에서 실제로 변경되는 유일한 것은 텍스트의 주사위 숫자와 결과가 할당되는 변수입니다.

그래서 첫 번째 단계는 입력 텍스트에 가변 주사위 번호를 적용하는 것입니다. 우리는 서식 문자열을 사용할 수 있습니다

"Would you like to re-roll dice {}? If so, enter 'Yes'. If not, enter 'No'.".format(i) 

지금 i의 값은 문자열의 {}의 위치에 삽입됩니다.

다음으로 우리는 변수 들인 choice에 대해 생각해야합니다. 당신이 그것에 대해 생각한다면 실제로하는 일을 위해 별도의 것들이 필요하지 않습니다. 결국, 그들은 사용자 입력을 포착하고 값을 평가 한 직후에 값을 잊어 버립니다. 그래서 우리는 단지 그 모든 것을 입력 할 때마다 choice으로 겹쳐 쓸 수 있습니다.

choice = input("Would you like to re-roll dice {}? If so, enter 'Yes'. If not, enter 'No'.".format(i)) 
if choice == "Yes": 
    userList.append(1) 
else: 
    userList.append(0) 

지금 변경 유일한 것은 i의 가치,해야이다 :

그래서 주사위 숫자 i, 우리는이 관련 코드 (도 str("something") 그냥 "something"에 해당합니다 참고)로이 1에서 5으로 이동하십시오. 그래서 우리는 루프를 사용합니다. 그게 전부입니다. 그게 전부입니다 :

def askTheUser(): 
    userList = [] 
    for i in range(1, 6): 
     choice = input("Would you like to re-roll dice {}? If so, enter 'Yes'. If not, enter 'No'.".format(i)) 
     if choice == "Yes": 
      userList.append(1) 
     else: 
      userList.append(0) 
    return userList 

Btw. 개별 주사위를 재 작성할지의 여부와 상관없이 "결정"을 수집 할 때 실제로 10 대신 부울 값 TrueFalse을 저장하는 것이 더 적합합니다.

if choice == "Yes": 
    userList.append(True) 
else: 
    userList.append(False) 

을 그리고 그 경우에, 당신은 그럼 그냥 대신 직접 비교의 결과를 추가 할 수 있습니다 : 그래서 당신은 대신 True 또는 False를 추가 할

userList.append(choice == "Yes") 

와 다음, 나중에 값을 검사 할 때 if decision == 1을 확인하는 대신 if decision을 사용해도됩니다.

+0

해 주신 모든 것에 대해 설명해 주셔서 감사합니다. 정말 감사합니다. 그것은 확실히 자신과 같은 초보자 코더에 도움이됩니다! – user3367018

+0

더 자세한 설명이 도움이 될 것 같았습니다. 다행이었습니다. 환영합니다. :) Btw. 이 질문을 해결 된 것으로 표시하도록 질문을 해결 한 경우 [답변 수락] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235)을 기억하십시오. . – poke

관련 문제