Understanding Python Variables, Data Types, and Type Conversion

Markdown

View as Markdown

      Variables and data types are essential concepts in Python. Variables allow you to store information, while data types define what kind of information is being stored. This article explains how to create variables, identify data types, and convert data between different types.

What is a Variable?

A variable is a name used to store data in a Python program.

Example

name = "John"

age = 25

In this example:

  • name stores text

  • age stores a number

You can display variable values using the print() function.

print(name)

print(age)

Output

John

25

Variable Naming Rules

When creating variables, follow these guidelines:

Valid Examples

student_name = "John"

age = 25

course_name = "Python"

Invalid Examples

2name = "John"

student-name = "John"

Best Practices

  • Use meaningful names

  • Use lowercase letters and underscores

  • Avoid spaces and special characters

  • Do not use Python keywords

Understanding Python Data Types

Python automatically assigns a data type based on the value stored in a variable.

Common Data Types

Data Type

Description

Example

str

Text

"Python"

int

Whole numbers

100

float

Decimal numbers

99.5

bool

True or False values

True

String (str)

A string is used to store text.

Integer (int)

Integers store whole numbers.

Float (float)

Floats store decimal values.

Boolean (bool)

Boolean values represent either True or False.

Checking a Variable's Data Type

Use the type() function to determine the data type of a variable.

Understanding Type Conversion

Type conversion changes a value from one data type to another.

Python provides built-in functions such as:

  • int()

  • float()

  • str()

  • bool()

Convert String to Integer

Convert Integer to String

Convert Integer to Float

Convert Float to Integer

Note: Converting a float to an integer removes the decimal portion.

Using Type Conversion with User Input

The input() function always returns a string. If you need to perform calculations, convert the value first.

Common Errors

Mixing Strings and Numbers

Incorrect:

age = 25

print("Age: " + age)

This produces a TypeError.

 

Correct:

age = 25

print("Age:", age)

     

       Variables store information in a Python program, while data types define the kind of data being stored. Common data types include strings, integers, floats, and Boolean values. Python also provides built-in functions such as int(), float(), and str() to convert values between different data types when needed.

Was this article helpful?

Still need help?

Contact us