web-dev-qa-db-ja.com

Pythonで文字列をintに変換するにはどうすればよいですか?

私の小さなサンプルアプリの出力は次のとおりです。

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

これは、addition()メソッドがinput()を数値ではなく文字列として受け取るためです。どうすれば数字として使用できますか?

これが私のスクリプト全体です:

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"
12
delete

おそらく浮動小数点数も受け入れる計算機を書いているので(1.5, 0.03)より堅牢な方法は、この単純なヘルパー関数を使用することです。

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

そうすれば、int変換が機能しない場合、floatが返されます。

編集: 方法python 2.xが整数除算を処理する方法 を完全に認識していない場合、division関数はいくつかの悲しい顔をする可能性があります。

簡単に言うと、10/2と等しい2.5およびnot2、あなたがする必要がありますfrom __future__ import divisionまたは、次のように一方または両方の引数を浮動小数点にキャストします。

def division(a, b):
    return float(a) / float(b)
16
Aphex
>>> a = "123"
>>> int(a)
123

ここにいくつかの無料のコードがあります:

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

おそらく次の場合、計算機は任意の数値の基数(16進数、2進数、基数7など)を使用できます:(unested)

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
Nick

簡単!

    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
Richard

def add(a、b):a + bを返す

def subtraction(a、b):a-bを返します

def multiplication(a、b):a * bを返す

def Division(a、b):a/bを返します

keepProgramRunning = True

「電卓へようこそ!」

keepProgramRunning:
print "実行する操作を選択してください:"

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
Munst

HTMLで直接str()メソッドを使用せず、代わりにy = x | string()を使用します

<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>
0

メイン関数からサブ関数を呼び出すときに、変数をintに変換して呼び出すことができます。以下のコードを参照してください:

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

ここで私がしたことは、入力されたパラメーターをintに変換しながら、各関数を呼び出しました。これがお役に立てば幸いです。

あなたの場合、次のように変更できます:

 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))
0
Chippy