2010-10-20 22 views
9

Kết quả tôi nhận được cho ít ví dụ ứng dụng của tôi như sau:Làm cách nào để chuyển đổi chuỗi thành int trong Python?

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 

Điều này là do phương pháp bổ sung() được dùng đầu vào() như dây đàn và không phải là số. Làm thế nào tôi có thể sử dụng chúng làm số?

Dưới đây là toàn bộ kịch bản của tôi:

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

Tôi đã tuyên bố rằng hệ thống đăng các câu hỏi hai lần, kiểm tra thời gian đường bưu điện. Không thực sự là lỗi của tôi và tôi cũng không thể xóa câu hỏi. –

+0

Liên kết 'close' không có sẵn cho bạn? –

+0

Điều đó không ngay lập tức đóng câu hỏi. –

Trả lời

15

Kể từ khi bạn đang viết một máy tính đó sẽ có lẽ cũng chấp nhận nổi (1.5, 0.03), một cách mạnh mẽ hơn là sử dụng chức năng trợ giúp đơn giản này:

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

Bằng cách đó, nếu chuyển đổi int không hoạt động, bạn sẽ nhận được một phao trả về.

Chỉnh sửa: Chức năng division của bạn cũng có thể dẫn đến một số gương mặt buồn nếu bạn không nhận thức đầy đủ về how python 2.x handles integer division.

Nói tóm lại, nếu bạn muốn 10/2 để bằng 2.5không2, bạn sẽ cần phải làm from __future__ import division hoặc đúc một hoặc cả hai trong những lập luận nổi, như vậy:

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

Xin chào, cảm ơn bạn! –

+1

'convertStr = float', hoạt động gần như giống nhau. –

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

Dưới đây là một số mã freebie:

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

Các hàm được tạo sẵn khác: http://docs.python.org/library/functions.html –

0

Có lẽ sau, sau đó máy tính của bạn có thể sử dụng cơ sở số tùy ý (ví dụ như hex, nhị phân, cơ sở 7 vv!): (chưa được kiểm tra)

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

dễ dàng!

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 Ngoài (a, b): trở lại a + b

def trừ (a, b): trở lại a - b

def nhân (a, b): trở lại a * b

phận def (a, b): trở a/b

keepProgramRunning = True

in "Chào mừng bạn đến với Máy tính!"

khi keepProgramRunning:
print "Hãy chọn những gì bạn muốn làm:"

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

Làm thế nào về một chút giải thích? – 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

Trong khi gọi chức năng phụ của bạn từ các chức năng chính của bạn, bạn có thể chuyển đổi các biến vào int và sau đó gọi điện.Vui lòng tham khảo mã bên dưới:

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() 

Ở đây, tôi đã gọi cho mỗi hàm trong khi chuyển đổi các tham số được nhập vào int. Tôi hy vọng điều này đã được hữu ích.

Trong trường hợp của bạn nó có thể được thay đổi như thế này:

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)) 
Các vấn đề liên quan