사용한다
당신은 모든 문자열 테스트를 해결하고, 또한 실제로 계산의 결과를 저장해야 is
대신 ==
이 표시됩니다. is
은이 경우에 수행한다고 생각하지 않습니다. 그것에 대한 자세한 내용은 here입니다.
을 사용하면 사용자가 Dollars
을 입력해도 성공할 수 있습니다.
사용자가 잘못된 정보를 입력 한 경우 처리 할 수 있기를 원합니다. 당신은 확실히 사용자가 정확한 입력을위한 사용자 요구에 계속 루프 while True
currency_input
사용하기 위해 숫자 만 입력 할 수있는 try
except
블록을 사용한다. 그들이 정확한 입력을 입력하면 break
성명서로 질문하는 것을 멈 춥니 다.
사전을 사용하면 통화 이름과 관련 값을 쉽게 저장할 수 있습니다.
또한 수학은 모든 통화에 대해 매우 동일합니다. 변경 사항은 통화 (달러, 유로 ...)의 가치이기 때문에 사용자가 선택한 것을 검색하고 그 시간을 곱하기 만 할 수 있습니다 the currency_input
def calculate():
# we only want the user to input numbers
while True:
try:
currency_input = float(input('Insert value: ')) # input always returns a str, we need to type cast
break # if input is valid we break out of the loop and move on
except TypeError: # handle the error when the input is not a number
print('Please enter a number.')
# use a dictionary because it is easier to read
currency_dict = {
'dollar': 34,
'euro': 36,
'pound': 52}
# get the type of currency and do the math
while True:
select_currency = input('Insert currency(dollar,euro or pound): ').lower()
if select_currency not in currency_dict: # if the users enter something that is not in the dict
print('Invalid currency') # oops, try again
else:
money = currency_input * currency_dict[select_currency] # we do the math
return money # return allows us to further manipulate that variable if we so desire
print(calculate())
두 가지 개선 사항을 지적 해 주신 Martijn Pieters에게 감사드립니다.
이것은 작동하지만 유로 또는 달러 또는 파운드를 입력하면 곧바로 진행됩니다. 왜 그럴까요? 나는 소문자 "달러"... 또는 유로 또는 어떤 선택으로 정확하게 타자를 쳤다 ...? – Victor
'print (repr (select_currency))'출력은 무엇입니까? –