Python Type casting - How to check given string can be converted to number?

Last updated Sep 16, 2021

In Python program to get the the input from user we will use input() method. In python 2x we used raw_input() method. So when we show input prompt the current program execution will stop until user enter the value. When reading the value from the command line using input(), the resulting value is a string even we enter digits also it treats as String.

Example to take inputs from user

def main():
   print("Enter your Name")
   name = input('Your name: ')
   print('Hello ' + name + ', how are you?')

 

main()

 

 

When we run it will prompt user to enter the values

Enter your Name
Your name: Python
Hello Python, how are you?

 

Let's say if we Add numbers entered by the user

def main():
   a = input('First number: ')
   b = input('Second number: ')
   print(a + b)
main()

 

Now when we run the program and enter numbers as

First number: 1

Second number: 2

It will add this two digits as string and give the output as 12 instead of 3, why because we already said every input value treat as string in python, so how we will convert these string values to numbers and add two numbers.

To fix the issue of adding two numbers from python user input prompt, we should have to convert string to numbers.

 

Let's write example add two numbers in Python

def main():
   a = input('First number: ')
   b = input('Second number: ')
   print(int(a) + int(b))
main()

 

This will output like below
 

First number: 1

Second number: 2

3

 

So to convert string to number we can use int(),float() functions in python

 

How can i check the given string can be converted to number in python?

def main():
    val = input("Type in a number: ")
    print(val)
    print(val.isdecimal())
    print(val.isnumeric())

 

    if val.isdecimal():
     num = int(val)
    print(num)

 

main()

 

output

Type in a number: 12
12
True
True
12

 

So in the above example to check the given string is converted to number or not by isdecimal() or isnumaric() functions

 

Converting String to int

def main():
    a = "12"
    print(a
    printtype(a) ) 

 

    b = int(a)
    print(b
    printtype(b) ) 
    a = "Age 18 is Major"
    print(a
    printtype(a) ) 

 

    b = int(a)
    print(b)
    printtype(b) )

 

main()

 

Output

12

12

Age 18 is Major

Traceback (most recent call last):
  File "d:\Blog Notes\python\python-concept\userinput.py", line 18, in
    main()
  File "d:\Blog Notes\python\python-concept\userinput.py", line 14, in main
    b = int(a)
ValueError: invalid literal for int() with base 10: 'Age 18 is Major'

 

Simple Calculator with python

def main():
    a = float(input("Number: "))
    b = float(input("Number: "))
    op = input("Operator (+-*/): ")

 

    if op == '+':
        res = a+b
    elif op == '-':
        res = a-b
    elif op == '*':
        res = a*b
    elif op == '/':
        res = a/b
    else:
        print("Invalid operator: '{}'".format(op))
    return

 

    print(res)
    return
main()

 

 

How to read Command line arguments in Python

import sys;

 

def main():
    print(sys.argv)
    print(sys.argv[0])
    print(sys.argv[1])
    print(sys.argv[2])

 

main()

 

run in terminal by
 

D:\pythonexamples>example.py 1 2 3 4

1

2

3

 

To find length of the command line arguments by len(sys.argv)  method

 

Conclusion: In this python tutorial we covered how to take input from user and convert input string to numbers, python type conversion

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

454 Views