2010-10-20 19 views
9

Wyjście Dostaję do mojego małego przykład aplikacji jest następująca:Jak przekonwertować ciąg na int w Pythonie?

Welcome to the Calculator! 
Please choose what you'd like to do: 
0: Addition 
1: Subtraction 
2: Multiplication 
3: Division 
4: Quit Application 
0 
Enter your first number: 1 
Enter your second number: 1 
Your result is: 
11 

To dlatego, że metoda dodawania() bierze input() jako ciągi, a nie liczbami. Jak mogę wykorzystać je jako liczby?

Tu jest mój cały skrypt:

def addition(a, b): 
    return a + b 

def subtraction(a, b): 
    return a - b 

def multiplication(a, b): 
    return a * b 

def division(a, b): 
    return a/b 

keepProgramRunning = True 

print "Welcome to the Calculator!" 

while keepProgramRunning:  
    print "Please choose what you'd like to do:" 

    print "0: Addition" 
    print "1: Subtraction" 
    print "2: Multiplication" 
    print "3: Division" 
    print "4: Quit Application" 



    #Capture the menu choice. 
    choice = raw_input()  

    if choice == "0": 
     numberA = raw_input("Enter your first number: ") 
     numberB = raw_input("Enter your second number: ") 
     print "Your result is:" 
     print addition(numberA, numberB) 
    elif choice == "1": 
     numberA = raw_input("Enter your first number: ") 
     numberB = raw_input("Enter your second number: ") 
     print "Your result is:" 
     print subtraction(numberA, numberB) 
    elif choice == "2": 
     numberA = raw_input("Enter your first number: ") 
     numberB = raw_input("Enter your second number: ") 
     print "Your result is:" 
     print multiplication(numberA, numberB) 
    elif choice == "3": 
     numberA = raw_input("Enter your first number: ") 
     numberB = raw_input("Enter your second number: ") 
     print "Your result is:" 
     print division(numberA, numberB) 
    elif choice == "4": 
     print "Bye!" 
     keepProgramRunning = False 
    else: 
     print "Please choose a valid option." 
     print "\n" 
+0

ja już stwierdzono, że system pisał kwestię dwukrotnie, sprawdzić czas postu. Naprawdę nie moja wina i nie mogę też usunąć tego pytania. –

+0

Link "zamknij" nie jest dla Ciebie obecny? –

+0

To jednak nie zamyka natychmiast pytania. –

Odpowiedz

15

Skoro piszesz kalkulator, który przypuszczalnie również przyjąć pływaki (1.5, 0.03), A bardziej niezawodnym sposobem byłoby użycie tej prostej funkcji pomocniczej:

def convertStr(s): 
    """Convert string to either int or float.""" 
    try: 
     ret = int(s) 
    except ValueError: 
     #Try float. 
     ret = float(s) 
    return ret 

W ten sposób, jeśli konwersja int nie będzie działać, otrzymasz powracający float.

Edytuj: Twoja funkcja division może również powodować pojawianie się smutnych twarzy, jeśli nie jesteś w pełni świadomy how python 2.x handles integer division.

W skrócie, jeśli chcesz 10/2 równa 2.5 i nie2, trzeba zrobić from __future__ import division lub rzucić jeden lub oba argumenty do pływaka, tak:

def division(a, b): 
    return float(a)/float(b) 
+0

Hej, to całkiem miłe, dzięki! –

+1

'convertStr = float', działa prawie tak samo. –

11
>>> a = "123" 
>>> int(a) 
123 

Oto niektóre freebie Kod:

def getTwoNumbers(): 
    numberA = raw_input("Enter your first number: ") 
    numberB = raw_input("Enter your second number: ") 
    return int(numberA), int(numberB) 
+0

Więcej wbudowanych funkcji: http://docs.python.org/library/functions.html –

0

Być może następujące, wówczas można użyć dowolnego kalkulator numer bazy (np hex, binarne, podstawę 7 itp!): (niesprawdzone)

def convert(str): 
    try: 
     base = 10 # default 
     if ':' in str: 
      sstr = str.split(':') 
      base, str = int(sstr[0]), sstr[1] 
     val = int(str, base) 
    except ValueError: 
     val = None 

    return val 

val = convert(raw_input("Enter value:")) 
# 10  : Decimal 
# 16:a : Hex, 10 
# 2:1010 : Binary, 10 
0

łatwy!

if option == str(1): 
     numberA = int(raw_input("enter first number. ")) 
     numberB= int(raw_input("enter second number. ")) 
     print " " 
     print addition(numberA, numberB) 
    etc etc etc 
0

def dodawanie (a, b) zwrócić + b

def odejmowania (a, b) powrotu a - b

def mnożenia (a, b) powrotu a * b

def podziału (a, b) powrotu a/b

keepProgramRunning = True

print "Witamy w kalkulatorze!"

podczas keepProgramRunning:
print „Proszę wybrać to, co chcesz zrobić:”

print "0: Addition" 
print "1: Subtraction" 
print "2: Multiplication" 
print "3: Division" 
print "4: Quit Application" 



#Capture the menu choice. 
choice = raw_input()  

if choice == "0": 
    numberA = input("Enter your first number: ") 
    numberB = input("Enter your second number: ") 
    print "Your result is: " + str(addition(numberA, numberB)) + "\n" 
elif choice == "1": 
    numberA = input("Enter your first number: ") 
    numberB = input("Enter your second number: ") 
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n" 
elif choice == "2": 
    numberA = input("Enter your first number: ") 
    numberB = input("Enter your second number: ") 
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n" 
elif choice == "3": 
    numberA = input("Enter your first number: ") 
    numberB = input("Enter your second number: ") 
    print "Your result is: " + str(division(numberA, numberB)) + "\n" 
elif choice == "4": 
    print "Bye!" 
    keepProgramRunning = False 
else: 
    print "Please choose a valid option." 
    print "\n" 
+0

Co powiesz na małe wyjaśnienie? – djv

-1
def addition(a, b): return a + b 

def subtraction(a, b): return a - b 

def multiplication(a, b): return a * b 

def division(a, b): return a/b 

keepProgramRunning = True 

print "Welcome to the Calculator!" 

while keepProgramRunning: 
print "Please choose what you'd like to do:" 
0

Podczas nazywając swoje funkcje podrzędne z głównych funkcji można konwertować zmienne w int a następnie połączenie.Proszę zapoznać się z poniższym kodem:

import sys 

print("Welcome to Calculator\n") 
print("Please find the options:\n" + "1. Addition\n" + "2. Subtraction\n" + 
"3. Multiplication\n" + "4. Division\n" + "5. Exponential\n" + "6. Quit\n") 

def calculator(): 
    choice = input("Enter choice\n") 

    if int(choice) == 1: 
     a = input("Enter first number\n") 
     b = input("Enter second number\n") 
     add(int(a), int(b)) 

    if int(choice) == 2: 
     a = input("Enter first number\n") 
     b = input("Enter second number\n") 
     diff(int(a), int(b)) 

    if int(choice) == 3: 
     a = input("Enter first number\n") 
     b = input("Enter second number\n") 
     mult(int(a), int(b)) 

    if int(choice) == 4: 
     a = input("Enter first number\n") 
     b = input("Enter second number\n") 
     div(float(a), float(b)) 

    if int(choice) == 5: 
     a = input("Enter the base number\n") 
     b = input("Enter the exponential\n") 
     exp(int(a), int(b)) 

    if int(choice) == 6: 
     print("Bye") 
     sys.exit(0) 



def add(a, b): 
    c = a+b 
    print("Sum of {} and {} is {}".format(a, b, c)) 

def diff(a,b): 
    c = a-b 
    print("Difference between {} and {} is {}".format(a, b, c)) 

def mult(a, b): 
    c = a*b 
    print("The Product of {} and {} is {}".format(a, b, c)) 

def div(a, b): 
    c = a/b 
    print("The Quotient of {} and {} is {}".format(a, b, c)) 

def exp(a, b): 
    c = a**b 
    print("The result of {} to the power of {} is {}".format(a, b, c)) 

calculator() 

Oto, co zrobiłem, nazwałem każdą z funkcji podczas konwersji parametrów wprowadzonych do int. Mam nadzieję, że było to pomocne.

W twoim przypadku może to być zmienione tak:

if choice == "0": 
     numberA = raw_input("Enter your first number: ") 
     numberB = raw_input("Enter your second number: ") 
     print "Your result is:" 
     print addition(int(numberA), int(numberB))