You are viewing a preview of this lesson. Sign in to start learning
Back to Python Programming

Variables & Built-in Functions

Learn variable assignment, naming conventions, and essential built-in functions

Variables and Built-in Functions in Python

Master Python's fundamental building blocks with free flashcards and spaced repetition practice. This lesson covers variable assignment, data types, type conversion, and essential built-in functions—critical concepts for anyone beginning their Python programming journey.

Welcome to Python Fundamentals! 💻

Welcome to one of the most important lessons in your Python journey! Variables and built-in functions form the foundation of every Python program you'll ever write. Think of variables as labeled containers that store data, and built-in functions as pre-packaged tools that Python provides to make your life easier.

🤔 Did you know? Python has over 70 built-in functions that are always available without importing anything! Functions like print(), len(), and type() are so commonly used that Python's creators made them instantly accessible.

By the end of this lesson, you'll understand how to store and manipulate data, convert between different types, and leverage Python's powerful built-in functions to write clean, efficient code.

Core Concepts: Variables in Python 📦

What Are Variables?

A variable is a named location in memory that stores a value. Unlike some programming languages, Python doesn't require you to declare a variable's type before using it—Python figures it out automatically through dynamic typing.

🌍 Real-world analogy: Think of variables like labeled boxes in a warehouse. You can put different items (values) in each box, and the label (variable name) helps you find what you stored.

Variable Assignment

In Python, you create a variable using the assignment operator (=):

age = 25
name = "Alice"
is_student = True
height = 5.9

💡 Tip: The = symbol doesn't mean "equals" in mathematics—it means "assign the value on the right to the variable on the left."

Variable Naming Rules

Python has specific rules for naming variables:

RuleExampleValid?
Start with letter or underscore_score, total
Can contain letters, numbers, underscoresplayer_1, count2
Case-sensitiveAgeage
Cannot start with number2fast
Cannot use Python keywordsclass, if, for
Cannot contain spacesmy score

🧠 Mnemonic for naming conventions: "LUNAS" - Letters, Underscores, Numbers After Start

Best Practices for Variable Names

Python developers follow the snake_case convention for variable names:

# Good - descriptive and clear
user_age = 30
total_price = 99.99
is_logged_in = False

# Bad - unclear or non-descriptive
x = 30
tp = 99.99
flag = False

Python's Basic Data Types

Python has several fundamental data types:

TypeDescriptionExampleType Name
IntegerWhole numbers42, -17int
FloatDecimal numbers3.14, -0.5float
StringText"Hello", 'Python'str
BooleanTrue/False valuesTrue, Falsebool
NoneTypeAbsence of valueNoneNoneType

Core Concepts: Built-in Functions 🔧

What Are Built-in Functions?

Built-in functions are pre-written functions that Python provides automatically. You don't need to import them or define them—they're always ready to use.

Essential Built-in Functions

The print() function displays output to the console:

print("Hello, World!")
print(42)
print(3.14, "pi", True)  # Can print multiple values

💡 Tip: print() automatically adds spaces between multiple arguments and a newline at the end.

2. type() - Check Data Type

The type() function returns the data type of a value:

print(type(42))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("Hello"))     # <class 'str'>
print(type(True))        # <class 'bool'>

3. len() - Get Length

The len() function returns the length of a sequence:

name = "Python"
print(len(name))         # 6

numbers = [1, 2, 3, 4, 5]
print(len(numbers))      # 5

4. Type Conversion Functions

Python provides functions to convert between types:

FunctionPurposeExampleResult
int()Convert to integerint("42")42
float()Convert to floatfloat("3.14")3.14
str()Convert to stringstr(42)"42"
bool()Convert to booleanbool(1)True
# Converting string to integer
age_str = "25"
age_int = int(age_str)
print(age_int + 5)       # 30

# Converting integer to string
count = 100
message = "Count: " + str(count)
print(message)           # Count: 100

5. input() - Get User Input

The input() function reads text from the user:

name = input("Enter your name: ")
print("Hello, " + name)

# Note: input() always returns a string!
age = input("Enter your age: ")  # Returns string
age = int(age)  # Convert to integer

⚠️ Important: input() always returns a string, even if the user types numbers!

6. Mathematical Functions

FunctionPurposeExampleResult
abs()Absolute valueabs(-5)5
round()Round numberround(3.7)4
pow()Power/exponentpow(2, 3)8
max()Maximum valuemax(1, 5, 3)5
min()Minimum valuemin(1, 5, 3)1
sum()Sum of sequencesum([1, 2, 3])6

7. Other Useful Functions

# range() - Generate sequence of numbers
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# sorted() - Return sorted list
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers))  # [1, 1, 3, 4, 5]

# reversed() - Reverse a sequence
letters = ['a', 'b', 'c']
print(list(reversed(letters)))  # ['c', 'b', 'a']

Detailed Examples with Explanations 🎯

Example 1: Variable Reassignment and Type Changes

# Python allows variables to change type
x = 10              # x is an integer
print(type(x))      # <class 'int'>

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

x = 3.14            # Now x is a float
print(type(x))      # <class 'float'>

Explanation: Unlike languages like Java or C++, Python uses dynamic typing. A variable can hold different types of values at different times. The type is determined by the value currently assigned, not by a declaration.

🌍 Real-world analogy: Imagine a box labeled "x". You can put a book in it, then empty it and put a laptop instead. The box doesn't care what type of object it holds.

Example 2: Type Conversion in Practice

# Getting two numbers from user and adding them
num1 = input("Enter first number: ")   # User types: 5
num2 = input("Enter second number: ")  # User types: 3

# This would concatenate strings!
wrong_result = num1 + num2
print(wrong_result)  # "53" (string concatenation)

# Correct approach - convert to integers first
num1 = int(num1)
num2 = int(num2)
correct_result = num1 + num2
print(correct_result)  # 8 (mathematical addition)

Explanation: The + operator behaves differently based on data types:

  • For strings: concatenation ("5" + "3" = "53")
  • For numbers: addition (5 + 3 = 8)

This is why type conversion is crucial when working with user input!

Example 3: Using Multiple Built-in Functions Together

# Calculate average of numbers
numbers = [85, 92, 78, 90, 88]

total = sum(numbers)          # sum() adds all elements
count = len(numbers)          # len() counts elements
average = total / count       # Calculate average

print("Numbers:", numbers)
print("Total:", total)
print("Count:", count)
print("Average:", round(average, 2))  # round to 2 decimals

# Output:
# Numbers: [85, 92, 78, 90, 88]
# Total: 433
# Count: 5
# Average: 86.6

Explanation: This example chains multiple built-in functions:

  1. sum() calculates the total
  2. len() counts how many items
  3. Division / computes the average
  4. round() formats the result to 2 decimal places

🔧 Try this: Modify the code to also display the minimum and maximum values using min() and max().

Example 4: Boolean Conversion and Truthiness

# Different values convert to True or False
print(bool(1))        # True
print(bool(0))        # False
print(bool(-5))       # True (any non-zero number)
print(bool(""))       # False (empty string)
print(bool("Hello"))  # True (non-empty string)
print(bool([]))       # False (empty list)
print(bool([1, 2]))   # True (non-empty list)
print(bool(None))     # False

Explanation: In Python, certain values are considered "falsy" (convert to False):

  • Zero numbers: 0, 0.0
  • Empty sequences: "", [], ()
  • None
  • False itself

Everything else is "truthy" (converts to True).

🧠 Mnemonic: "ZONE" - Zero, nOne (None), Null sequences, Empty strings are falsy

Common Mistakes ⚠️

Mistake 1: Using Reserved Keywords as Variable Names

# WRONG - 'class' is a Python keyword
class = "Math 101"  # SyntaxError!

# CORRECT
class_name = "Math 101"
course = "Math 101"

Mistake 2: Forgetting to Convert Input

# WRONG - causes TypeError
age = input("Enter age: ")  # Returns string
next_year = age + 1  # TypeError: can't add int to string

# CORRECT
age = input("Enter age: ")
age = int(age)  # Convert to integer first
next_year = age + 1

Mistake 3: Mixing Up Print and Return

# print() displays but doesn't return a value
result = print(5 + 3)  # Displays 8
print(result)          # None

# Variables store values directly
result = 5 + 3
print(result)  # 8

Explanation: print() displays output but returns None. Don't confuse displaying a value with storing it.

Mistake 4: Invalid Type Conversions

# WRONG - can't convert non-numeric string to int
number = int("hello")  # ValueError!

# WRONG - can't convert empty string to int
number = int("")  # ValueError!

# CORRECT - validate before converting
text = "123"
if text.isdigit():
    number = int(text)

Mistake 5: Using type() Incorrectly in Comparisons

# WRONG - comparing to string
if type(x) == "int":  # This doesn't work!
    print("It's an integer")

# CORRECT - compare to actual type
if type(x) == int:
    print("It's an integer")

# BETTER - use isinstance()
if isinstance(x, int):
    print("It's an integer")

Key Takeaways 🎓

Variables are named containers that store values in memory

✅ Python uses dynamic typing—variables can change type

✅ Variable names must follow specific rules: start with letter/underscore, no spaces, no keywords

Built-in functions are always available without imports: print(), type(), len(), input(), etc.

Type conversion functions (int(), float(), str(), bool()) convert between data types

input() always returns a string—convert to other types as needed

✅ Use type() to check a variable's data type

✅ Different operators behave differently based on data types (+ concatenates strings but adds numbers)

✅ Empty values and zero are falsy; most other values are truthy

✅ Always validate and convert user input before performing operations

📚 Further Study

  1. Python Official Documentation - Built-in Functions: https://docs.python.org/3/library/functions.html - Complete reference for all Python built-in functions

  2. Real Python - Variables in Python: https://realpython.com/python-variables/ - In-depth guide to Python variables and naming conventions

  3. Python.org - Type Conversion Tutorial: https://docs.python.org/3/tutorial/introduction.html - Official tutorial covering basic data types and conversions

📋 Quick Reference Card

ConceptSyntaxExample
Variable Assignmentname = valueage = 25
Check Typetype(var)type(42)int
Display Outputprint(value)print("Hi")
Get User Inputinput(prompt)input("Name: ")
Convert to Integerint(value)int("42")42
Convert to Floatfloat(value)float("3.14")3.14
Convert to Stringstr(value)str(42)"42"
Get Lengthlen(sequence)len("Hi")2
Absolute Valueabs(number)abs(-5)5
Round Numberround(number, digits)round(3.7)4
Maximummax(a, b, c...)max(1, 5, 3)5
Minimummin(a, b, c...)min(1, 5, 3)1

Naming Rules: Start with letter/underscore, use snake_case, no keywords

Falsy Values: 0, 0.0, "", [], None, False