Ad space (banner)
🐍Python Lessons
Lesson 32 / 69

Type Conversion (casting) Basics

This lesson covers the basics of type conversion (casting) in Python, so you can correctly convert between strings and numbers. It's written for anyone searching "Python type conversion tutorial" or "Python int str conversion".

Converting a string to a number, or a number to a string — type conversion (casting) — is a basic programming operation. You use int(), str(), float(), and similar functions. Whatever input() returns always arrives as a string, so it always needs converting before you can use it in a calculation.

The sample code converts the string "123" to a number with int() for use in a calculation, and converts the number 45 to a string with str() so it can be joined with the word "yen." Remember that if you want to handle decimals rather than just integers, you need float() instead of int().

A common beginner mistake is passing a string that can't be converted to int(), which raises an error. Passing an unconvertible string, like int("abc"), raises a ValueError — when handling user input, it's important to validate beforehand or pair the conversion with try...except. Forgetting this is a common source of unexpected errors.

In real development, input from forms or data read from a file always arrives as a string, so proper type conversion is essential before doing amount calculations or date arithmetic. Type-aware code is fundamental to building stable applications with fewer bugs.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)