Skip to content

Casting

Amin Zamani edited this page Mar 22, 2023 · 1 revision

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

int() constructs an integer number from an integer literal, a float literal (by removing all decimals), or string literal (providing the string represents a whole number).

float() constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer).

str() constructs a string from a wide variety of data types, including strings, integer literals and float literals.

# Integers:
int_casting1 = int(1)  # x will be 1
int_casting2 = int(2.8)  # y will be 2
int_casting3 = int("3")  # z will be 3

# Floats:
float_casting1 = float(1)  # x will be 1.0
float_casting2 = float(2.8)  # y will be 2.8
float_casting3 = float("3")  # z will be 3.0
float_casting4 = float("4.2")  # w will be 4.2

# Strings:
string_casting1 = str("s1")  # x will be 's1'
string_casting2 = str(2)  # y will be '2'
string_casting3 = str(3.0)  # z will be '3.0'

Python

Python Essentials 1 (PCEP)

Introduction to Python and computer programming

Data types, variables, basic I/O operations, and basic operators

Boolean values, conditional execution, loops, lists and list processing, logical and bitwise operations

Clean Code

Algorithms

Django

Django Rest Framework

API

pip

SQLAlchemy

FastAPI

Pytest

TDD

Git

Linux

Docker

Python Testing

Interview Questions

Clone this wiki locally