Loading...
Loading...
1pythonvariables

Python Variables Tutorial

Variables are fundamental building blocks in Python programming. They allow you to store and manipulate data in your programs. In this tutorial, you'll learn how to create, use, and manage variables in Python, including their naming conventions, data types, and scope.

By the end of this tutorial, you'll understand how to work with variables effectively in Python and use them to build dynamic and flexible programs.

What is a Variable?

A variable is a named location in memory used to store data. In Python, you don't need to declare a variable's type explicitly; it is dynamically inferred based on the value assigned to it.

  • Key Features:
    • Variables store data that can be used and modified throughout the program.
    • Python variables are dynamically typed, meaning their type can change during runtime.
  • Example:
    # Assigning values to variables
    x = 10
    name = "Alice"
    is_active = True

Quick Quiz: Variables Basics

How does Python determine a variable's type?

  • You must declare it explicitly (e.g., int x = 10)
  • It is inferred from the assigned value
  • Python variables have no types

Can a Python variable change its type after assignment?

  • Yes (e.g., x = 10x = "Hello")
  • No, once set, the type is fixed

Variable Naming Rules

Python has specific rules for naming variables:

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • Variable names can only contain letters, numbers, and underscores.
  • Variable names are case-sensitive (myVar and myvar are different).
  • Avoid using Python keywords (e.g., if, for, while) as variable names.
# Valid variable names
my_var = 10
user_name = "Alice"
total_amount = 100.50

# Invalid variable names
2var = 5  # Cannot start with a number
my-var = 10  # Cannot contain hyphens

Test Your Naming Knowledge!

Which of these is a valid variable name?

  • 2nd_place
  • user_age
  • while (Python keyword)

Are variable names case-sensitive in Python?

  • Yes (Ageage)
  • No

Data Types in Python

Python supports various data types, and variables can hold values of any type. Here are some common data types: Read More About

  • Integer: Whole numbers (e.g., 10, -5).
  • Float: Decimal numbers (e.g., 3.14, -0.001).
  • String: Text data (e.g., "Hello", 'Python').
  • Boolean: True or False values (e.g., True, False).
  • List: Ordered, mutable collection of items (e.g., [1, 2, 3]).
  • Tuple: Ordered, immutable collection of items (e.g., (1, 2, 3)).
  • Dictionary: Key-value pairs (e.g., {"name": "Alice", "age": 25}).
# Examples of different data types
age = 25  # Integer
price = 19.99  # Float
name = "Alice"  # String
is_student = True  # Boolean
fruits = ["apple", "banana", "cherry"]  # List
coordinates = (10.0, 20.0)  # Tuple
person = {"name": "Alice", "age": 25}  # Dictionary

Data Types Quiz

Which data type is immutable (cannot be changed after creation)?

  • List
  • Tuple
  • Dictionary

What is the type of price = 19.99?

  • Integer
  • Float
  • String

Variable Scope

Variable scope determines where a variable can be accessed in a program. Python has two main types of scope:

  • Global Scope: Variables defined outside of any function or block. They can be accessed anywhere in the program.
  • Local Scope: Variables defined inside a function or block. They can only be accessed within that function or block.
# Global variable
x = 10

def my_function():
    # Local variable
    y = 20
    print("Local y:", y)
    print("Global x:", x)

my_function()
# print(y)  # This will cause an error because y is local to my_function

Scope Quiz

Where can a global variable be accessed?

  • Anywhere in the program
  • Only inside functions

What happens if you try to access a local variable outside its function?

  • An error occurs
  • It becomes a global variable

Dynamic Typing

Python is dynamically typed, meaning you can change the type of a variable by assigning a new value of a different type.

# Dynamic typing example
x = 10  # x is an integer
print(type(x))  # Output: <class 'int'>

x = "Hello"  # x is now a string
print(type(x))  # Output: <class 'str'>

Dynamic Typing Quiz

What is the output of type(x) after x = 3.14?

  • <class 'int'>
  • <class 'float'>

Can a variable hold a string first and later a number?

  • Yes, Python allows this
  • No, once set, the type is fixed

Best Practices for Using Variables

Follow these best practices to write clean and maintainable code:

  • Use descriptive variable names (e.g., user_age instead of u).
  • Avoid using single-letter variable names unless they are used in short loops or mathematical contexts.
  • Use constants (variables that don't change) in uppercase (e.g., PI = 3.14159).
  • Keep variable scope in mind to avoid unintended side effects.

Best Practices Quiz

Which variable name follows Python best practices?

  • a = 10 (too vague)
  • max_speed = 100

How should you name a constant (unchangeable) variable?

  • maxSpeed
  • MAX_SPEED

This tutorial covered the basics of variables in Python, including naming conventions, data types, scope, and dynamic typing. Practice using variables to store and manipulate data in your Python programs.

0 Interaction
1.6K Views
Views
38 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home