0% found this document useful (0 votes)
7 views10 pages

Python Variables and Data Types Guide

The document explains the concepts of variables and data types in Python, emphasizing how variables act as containers for data and how Python automatically detects data types. It covers the four fundamental data types: integers, floats, strings, and booleans, along with dynamic typing and type conversion. Additionally, it explores string operations such as concatenation, slicing, and essential string methods for manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views10 pages

Python Variables and Data Types Guide

The document explains the concepts of variables and data types in Python, emphasizing how variables act as containers for data and how Python automatically detects data types. It covers the four fundamental data types: integers, floats, strings, and booleans, along with dynamic typing and type conversion. Additionally, it explores string operations such as concatenation, slicing, and essential string methods for manipulation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Variables and Data Types in

Python
Discover how Python stores and manages information with variables and data
types
What is a Variable?
Think of a variable as a labeled container that holds information in your
x=5
program. You can store different types of data and retrieve them
name = "Alice"
whenever you need.
is_student = True
Variables give your data a meaningful name, making your code easier to
read and maintain. When you assign a value to a variable, Python # Use variables
remembers it for you. print(x)
print(name)

Key concept: Variables are created the moment you assign a


value to them using the equals sign (=). The variable x stores the number 5, while name stores the
text "Alice".
The Four Fundamental Data Types
Python organizes information into different categories. Here are the essential building blocks you'll use every day:

Integer (int) Float (float)


Whole numbers without decimals Numbers with decimal points

age = 25 price = 19.99


count = -10 temperature = -3.5
year = 2024 pi = 3.14159

String (str) Boolean (bool)


Text enclosed in quotes True or False values

greeting = "Hello" is_active = True


letter = 'A' has_license = False
message = "Welcome!" is_valid = True
Dynamic Typing: Python's Smart
Feature
Python Figures It Out # Python detects types
Automatically automatically
x = 10 # int
Unlike some programming languages,
x = 10.5 # now it's float
Python automatically detects what type
x = "Hello" # now it's string
of data you're storing. You don't need to
declare the type in advance!
# Check the type
print(type(x)) #
This makes Python incredibly flexible
and beginner-friendly. The interpreter The same variable x can hold different
analyzes the value you assign and types at different times!
determines the appropriate data type.
Type Conversion Made Easy
Sometimes you need to convert data from one type to another. Python makes this simple with built-in functions:

Convert to Integer Convert to Float Convert to String

x = int("42") x = float("3.14") x = str(42) # "42"


y = int(3.9) #3 y = float(5) # 5.0 y = str(3.14) # "3.14"
z = int(True) # 1 z = float(True) # 1.0 z = str(False) # "False"

Pro tip: Use type() to check a variable's data type, and conversion functions when you need to change it.
Working with Strings
Strings are one of the most versatile data types in Python. Let's explore the
powerful operations you can perform with text.
String Concatenation and Repetition
Joining Strings Together Repeating Strings

Concatenation means combining multiple strings into one using the Use the multiplication (*) operator to repeat a string multiple times.
plus (+) operator. This is perfect for building messages and dynamic This creates patterns quickly and efficiently.
text.

# Repeat a string
first_name = "John" stars = "*" * 10
last_name = "Doe" print(stars) # **********

# Concatenate strings divider = "-=" * 20


full_name = first_name + " " + last_name print(divider) # -=-=-=-=-=-=-=-=-=-=
print(full_name) # John Doe
laugh = "ha" * 3
# Build a greeting print(laugh) # hahaha
greeting = "Hello, " + full_name + "!"
print(greeting) # Hello, John Doe!
String Slicing: Extracting Parts of Text
Slicing lets you extract specific portions of a string using index positions. Remember: Python counts from 0!

01 02 03

Basic Slicing Syntax Slicing Shortcuts Using Step Values

text = "Python" text = "Programming" text = "Hello World"


# string[start:end] print(text[:4]) # Prog (from start) print(text[::2]) # HloWrd (every 2nd)
print(text[0:3]) # Pyt print(text[4:]) # ramming (to end) print(text[::-1]) # dlroW olleH (reverse)
print(text[2:5]) # tho print(text[-3:]) # ing (last 3 chars)
Essential String Methods
Python strings come with built-in methods that make text manipulation effortless. Here are the most useful ones:

Changing Case Finding and Replacing

text = "Hello World" message = "I love cats"


print([Link]()) # HELLO WORLD print([Link]("cats", "Python"))
print([Link]()) # hello world # I love Python
print([Link]()) # Hello World
print([Link]("love")) # 2

Splitting and Joining Removing Whitespace

sentence = "Python is amazing" text = " hello "


words = [Link]() # ['Python', 'is', 'amazing'] print([Link]()) # "hello"
print([Link]()) # "hello "
new = " ".join(words) # Python is amazing print([Link]()) # " hello"
Practice: Variable Assignment Examples
Let's put everything together! Here are practical examples combining variables, data types, and string operations:

# Store user information # Working with calculations


username = "student_123" price = 49.99
age = 20 quantity = 3
gpa = 3.85 total = price * quantity
is_enrolled = True
# Create a receipt
# Combine different types item = "Python Book"
status = username + " is " + str(age) + " years old" receipt = f"""
print(status) Item: {item}
Price: ${price}
# String formatting (modern way) Quantity: {quantity}
info = f"GPA: {gpa}, Enrolled: {is_enrolled}" Total: ${total}
print(info) """
print(receipt)

Challenge yourself: Try creating variables for your favorite movie, its rating, and year released. Then combine them into a formatted message!

You might also like