cast to int python code example

Example 1: check if string can be converted to int python

# CHECKING IF INT
variable='3'
try:
    int(variable)
    # this will execute if it is integer
    print('You typed an int')
except ValueError:
  	# otherwise this will execute
    print('You did not type an int')

# CHECKING IF FLOAT
variable='3'
try:
    float(variable)
    print('You typed a float')
except ValueError:
    print('You did not type a float')

Example 2: python string to int

# Use the function int() to turn a string into an integer
string = '123'
integer = int(string)
integer
# Output:
# 123

Example 3: convert float to int python

# convert float to int 
x=3.1415
y=int(x)
print(y) #outputs 3

Example 4: python cast to float

float('1.234')

Example 5: python string to int

print(int("12"))

Example 6: python cast to int

x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Tags:

Sql Example