USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Type Casting and Basic Input/Output

Lesson 6/35 | Study Time: 40 Min

When writing Python programs, you often need to convert data from one type to another, or interact with the user by taking input and displaying output. These two concepts, type casting and input/output are fundamental to building even the simplest programs.

What is Type Casting?

Type casting means converting a value from one data type to another. Python is dynamically typed, but there are moments when you need to manually change a variable's type. For example, converting a string to an integer before performing a calculation.


There are two kinds of type casting in Python:


1. Implicit Casting: Python converts the type automatically.

2. Explicit Casting: You manually convert the type using built-in functions.

Implicit Type Casting

Python handles this automatically when there is no risk of data loss.

Here, Python automatically converts x from int to float before adding.

Explicit Type Casting

You control the conversion using Python's built-in functions.

Examples:

Common Casting Errors to Watch Out For

Not all conversions are valid. Trying to cast incompatible types will raise an error.


Always make sure the value is compatible before casting.


Basic Input and Output

Input and output allow your program to communicate with the user. Python makes this very straightforward with just two built-in functions.

Output — print()

The print() function displays information on the screen.



You can also format output cleanly using f-strings (recommended):



Input — input()

The input() function takes data from the user during program execution. It always returns the value as a string.



Since input() returns a string, you must cast it if you need a number:



Or in a single line:




Quick Comparison: input() vs print()


Sales Campaign

Sales Campaign

We have a sales campaign on our promoted courses and products. You can purchase 1 products at a discounted price up to 15% discount.