Python Basics: Variables and Data Types
Description
In this chapter, you will learn how to declare variables and work with different data types in Python. Understanding how variables work and the types of data they can store is crucial for building more advanced programs. You will also explore how to convert data types, check types, and perform basic input and output operations.
Variables and Assignment
A variable is used to store a value, and the value can be changed during the execution of a program. In Python, you don't need to declare a variable’s type explicitly; Python automatically assigns a type based on the value you assign to the variable.
x = 5 # Here, 'x' is a variable assigned with an integer value
name = "John" # 'name' is a variable holding a string value
Numbers, Strings, Booleans
Python supports several basic data types: numbers, strings, and booleans.
- Numbers: These can be integers or floating-point numbers.
- Strings: Strings are sequences of characters enclosed in single or double quotes.
- Booleans: Booleans represent one of two values: True or False.
age = 25 # Integer
height = 5.9 # Floating-point number
is_active = True # Boolean value
message = "Hello, Python!" # String
Type Casting (Conversion)
Type casting is the process of converting one data type into another. You can use Python's built-in functions to convert data types.
num_str = "123" # String representation of a number
num_int = int(num_str) # Convert string to integer
num_float = float(num_int) # Convert integer to float
print(num_float) # Output: 123.0
Checking Types with type()
You can check the type of a variable using the type() function.
print(type(age)) # Output: int>
print(type(message)) # Output: string>
Basic Input/Output
In Python, you can get input from the user using the input() function, and you can display output using the print() function.
user_name = input("Enter your name: ") # Takes input from the user
print("Hello, " + user_name + "!") # Prints a greeting message