2015-02-04 3 views
0

저는 Python을 처음 사용하며 제 대학에서 계산 과정을 소개하고 배우고 있습니다. 우리의 숙제는 1-99까지의 숫자 만 받아들이고 +, -, *, /, //, %, ** 연산자 만 수락하는 계산기 알고리즘을 만드는 것이 었습니다. 현재 현재 방정식에서 문자열로 지정한 연산자를 올바르게 사용하는 방법을 찾으려는 끝에 막혀 있습니다. int 형의 문자열을 정수형 또는 부동 소수점 형으로 변경하는 것과 비슷하다고 가정합니다. 그러나 그것은 제가 얻은 것입니다. 코드 전체가 아래에 있으며 굵은 선은 모두 코드의 주석으로 지정되어 있습니다. 어떤 해답을 주셔서 감사합니다. 비평을 해 주시길 바랍니다. 그러나 그것에 관해서는 좋을 것입니다. 이것은 주제에 대한 제 2 과제 일뿐입니다.Python 방정식에서 문자열로 지정된 연산자를 사용하는 방법

#Welcome and Rules 
 

 
print("Welcome to calculator.py") 
 
print("Valid numbers are 1 through 99") 
 
print("Valid operators are +, -, *, /, //, %, **") 
 

 
#Take in first integer that is between 0 and 100. 
 

 
firstInt = int (input ("Enter the first number: ")) 
 
    
 
#Take in an operator to operate on the integers. 
 

 
opStr = input ("Enter a valid operator: ") 
 

 
#Take in second integer that is between 0 and 100. 
 

 
secondInt = int (input ("Enter the second number: ")) 
 
       
 
#Prints the first error encountered then does not continue execution 
 
#Errors include: values not between 0 and 100, or the operator is not 
 
#of the type: +, -, *, /, //, %, **.     
 

 
if (firstInt <= 1 or firstInt >= 100): 
 
    print ("Your first integer is invalid.") 
 
        
 
elif (opStr != "+" or opStr != "-" or opStr != "*" or opStr != "/" or \ 
 
    opStr != "//" or opStr != "%" or opStr != "**"): 
 
    print ("You entered an invalid operator.") 
 
        
 
elif (secondInt <= 1 or secondInt >= 100): 
 
    print ("Your second integer is invalid.") 
 

 
#Calculates the answer 
 

 
answer = (firstInt opStr secondInt) 
 

 

 
#Print the answer to screen 
 

 
else: 
 
    print(answer)

답변

0

당신은 아마 운영자를 기반으로하는 경우 - 다른 진술을하고 싶은 것입니다. 예를 들면 :

if opStr = "+": 
    answer = firstInt + secondInt 
elif opStr = "-": 
    answer = firstInt - secondInt 
elif opStr = "*": 
    answer = firstInt * secondInt 

등 ...

이 더 함께했다, 나는/다시 코드를 단순화하기 위해 일부 기능을 사용하는 것이 좋습니다 것입니다.

관련 문제