2016-07-16 8 views
-1

Dieser Rechner funktioniert in Python 2:Einfacher Rechner funktioniert in Python 2, aber nicht mehr als 3

print ("First calculator!") 

print ("") 

firstnum=input ("Insert the first number: ") 
print ("") 
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n") 
operation=input ("Insert the number of operation: ") 
if int(operation) >4: 
     print ("You mistyped") 
     exit(0) 
print ("") 
secondnum=input ("Insert the second number: ") 

if operation == 1: 
    print ("The result is:", firstnum+secondnum) 
if operation == 2: 
    print ("The result is:", firstnum-secondnum) 
if operation == 3: 
    print ("The result is:", firstnum*secondnum) 
if operation == 4: 
    print ("The result is:", firstnum/secondnum) 

Aber in Python 3 das Skript tut nichts nach Eingabe akzeptieren.

--UPDATE--

Nach dank der Hilfe von @ moses-koledoye Festsetzung, ich werde die endgültige Quellcode veröffentlichen, könnte es Hilfe für einen anderen Neuling sein.

print ("First calculator!") 
print ("") 

firstnum=input ("Insert the first number: ") 
print ("") 
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n") 
operation=input ("Insert the number of operation: ") 
if int(operation) >4: 
     print ("You mistyped") 
     exit(0) 
print ("") 
secondnum=input ("Insert the second number: ") 

firstnum=int(firstnum) 
secondnum=int(secondnum) 

print ("") 
if operation == "1": 
    print ("The result is:", firstnum+secondnum) 
elif operation == "2": 
    print ("The result is:", firstnum-secondnum) 
elif operation == "3": 
    print ("The result is:", firstnum*secondnum) 
elif operation == "4": 
    print ("The result is:", firstnum/secondnum) 

Antwort

1

Du vergleichst Strings mit ganzen Zahlen:

if operation == 1 # '1' == 1 

immer False sein wird, so dass keiner der if Blöcke ausgeführt wird.

Führen Sie eine String-string Vergleich statt:

if operation == '1' 

Und wenn die if Block Bedingungen festgelegt sind, werden andere Fehler auftauchen:

firstnum + secondnum 

Dies wird concat Ihre Zeichenketten und führen Sie keine numerische Operation wie Sie beabsichtigen, während Operation -, * und / erhöht TypeError. Sie sollten werfen Ihre Operanden, firstnum und secondNum in den entsprechenden Typ: float oder int.


Außerdem könnten Sie die Kette auch alle if Klauseln in eine if-elif Klausel

+0

wirklich viel Dank !! I löste. – Sperly1987