2014-12-17 2 views
0

그래서 지난 1 시간 동안이 작업을 수행했습니다. 나는 숫자가 아닌 무언가를 입력 할 때 시작 시간으로 사용자를 되돌아 가게하는 while 루프를 추가하려고합니다. 그러나 나는 이것에 관해 어디에서 시작해야하는지 전혀 모른다. 나는 많은 것을 시도해 왔지만 아무것도 나를 위해 일하는 것 같지 않습니다.Python은 입력에 따라 while 루프를 생성합니다.

try: 
    length=float(raw_input("Insert Length of room")) 
except ValueError: 
    print "That's not a number try again" 
try: 
    width=float(raw_input("Insert Width of room")) 
except ValueError: 
    print "That's not a number try again" 
else: 
    cost=(width*length)*3.99 
print cost 
+0

당신은 while 'while True :'내부의 전체 논리를 들여 쓰고 잠시 다시 할 때'continue' 문을 추가하고 루프를 종료 할 때'break' 문을 ... ? –

+0

누가 모든 답변을 다운 받습니까? – nbro

답변

0

당신은 whilebreak를 사용할 수 있습니다

length = 0 
while True: 
    try: 
     length = float(raw_input("Insert Length of room: ")) 
     break 
    except ValueError: 
     print "That's not a number try again" 

# You'll have a valid float in length at this point 
print(length) 
+0

고맙지 만 작동하지만 어떻게 다른 사람을 추가 할 수 있습니까? –

+0

신경 쓰지 마라 :) 나는 단지 다른 것을 제거해야한다고 생각했다. –

+0

@noelpearce 당신은 함수 안에 miku의 답을 넣고, while 루프의 조건에 따라 참/거짓을 리턴 할 수 있습니다. 이것은 width * height else 문에 대한 것이라고 가정합니다. – CyanogenCX

0

당신은 이런 식으로 뭔가를 할 수 :

dimensions = ['Length', 'Width'] 
values = [] 

for dimension in dimensions: 
    while True: 
     try: 
      v = float(raw_input("Insert {} of room: ".format(dimension))) 
      values.append(v) 
      break 
     except ValueError: 
      print "That's not a number try again" 

length, width = values 

cost = (width * length) * 3.99 
print cost 

편집 업데이트 요구 사항.

+0

그 문제를 해결하려면 폭에 대한 유효한 부동 소수점을 얻지 못하면 길이를 다시 시작하지 않아야합니다. –

-1

다음과 같이 수행 할 수 있습니다

while True: 
    try: 
     length = float(raw_input("Insert Length of room: ")) 
    except ValueError: 
     print "That's not a number try again" 
    else: 
     break 

여러 질문이있을 경우 다음과 같이 할 수있다 : 여러 입력을위한 검사를 수행하려는 경우

in_data = { 
      'length': ['Insert Length of room: ', -1], # the -1 is placeholder for user input 
      'width': ['Insert Width of room: ', -1], 
      } 


for k,v in in_data.items(): 
    while True: 
     try: 
      user_data = float(input(v[0]))    
     except ValueError: 
      print("That's not a number try again") 
     else: 
      v[1] = user_data 
      break 

print(in_data) 
# example output: {'width': ['Insert Width of room: ', 7.0], 'length': ['Insert Length of room: ', 8.0]} 
0

것은, 당신이 정의 할 수 있습니다 함수는 입력을 얻고 그것을 확인 : 다음

def numeric_input(message, numeric_type=float): 
    while True: 
     try: 
      return numeric_type(raw_input(message)) 
     except ValueError: 
      print "That isn't a valid number! Try again." 

:

length = numeric_input("Insert Length of room") 
width = numeric_input("Insert Width of room") 
cost = (width*length)*3.99 
print cost 

그런 식으로 사용자가 길이에 숫자를 제공하지만 너비에 대해 숫자가 아닌 입력을하면 프로그램은 사용자에게 너비 만 다시 입력하도록 요청하지 않습니다.

관련 문제