Introduction to Python
Programming
Welcome to the exciting world of Python! This comprehensive guide will take you
from complete beginner to confident Python programmer. Python has become one
of the most popular programming languages in the world, and for good reason4it's
powerful, versatile, and surprisingly easy to learn. Whether you're interested in
building websites, analyzing data, creating artificial intelligence, or automating
everyday tasks, Python is your gateway to making it happen. Let's embark on this
coding journey together!
What is Python?
Python is a high-level, interpreted programming language that has revolutionized
how we approach software development. Created by Guido van Rossum in 1991,
Python was designed with one core philosophy: code should be readable and simple.
Unlike languages that look like cryptic mathematical formulas, Python reads almost Easy to Learn
like plain English, making it the perfect first language for beginners.
Clear, readable syntax that resembles natural
What makes Python truly special is its interpreted nature4you write code and see language
results immediately, without the lengthy compilation process required by other
languages. This instant feedback loop accelerates learning and makes debugging
much more intuitive. Python's philosophy of "batteries included" means it comes with
extensive standard libraries right out of the box, so you can accomplish complex tasks
without reinventing the wheel.
Open Source
Today, Python powers everything from Instagram's backend to NASA's data analysis
Completely free with active community support
tools, from Netflix's recommendation algorithms to Spotify's playlist generation. Its
versatility knows no bounds, making it an essential skill for anyone entering the tech
industry.
Highly Portable
Write once, run anywhere4Windows, Mac, Linux
Rich Libraries
Thousands of pre-built tools for any task
imaginable
Python Keywords and Identifiers
Before we start writing code, we need to understand Python's vocabulary. Just like English has words you can't redefine (try making "the" mean
something else!), Python has reserved keywords that serve specific functions in the language.
Python Keywords Python Identifiers
Keywords are reserved words that have special meaning in Identifiers are the names you create for variables, functions,
Python. They're the building blocks of Python's syntax and cannot classes, and other objects in your programs. They're your creative
be used as variable names, function names, or any other labels that make code meaningful and self-documenting. Good
identifiers. Think of them as Python's sacred vocabulary4words identifier names can make the difference between code that's a
the language needs to function properly. joy to read and code that's a nightmare to maintain.
Common Keywords: if, else, elif, for, while, break, continue, def, Naming Rules:
class, import, return, True, False, None, and, or, not, in, is, try,
Must start with a letter (a-z, A-Z) or underscore (_)
except, finally, with, as, lambda, pass, yield
'
' Can contain letters, digits (0-9), and underscores
When you try to use a keyword as a variable name, Python will
Case-sensitive (age and Age are different)
immediately throw an error. This protective behavior helps
'
prevent confusing bugs and keeps your code readable. o Cannot start with a digit
o No spaces or special characters (!, @, #, $, %, etc.)
o Cannot be a Python keyword
Valid Examples: student_name, age1, _private_var, calculateTotal,
PI_VALUE
Invalid Examples: 1student (starts with number), student-name
(contains hyphen), for (keyword), my variable (contains space)
Pro Tip: Use descriptive names that explain what the variable represents. Writing total_price is much better than tp or x. Your future
self (and your teammates) will thank you!
Variables and Data Types
Variables are like labeled containers that hold information in your program. In Python, creating a variable is beautifully simple4just choose a name
and assign it a value. No need to declare types beforehand; Python figures it out automatically through a feature called dynamic typing.
Working with Variables Python Data Types
Unlike some languages that require formal declarations, Python lets Python supports several built-in data types, each designed for
you create variables on the fly. Simply use the assignment operator (=) different purposes:
to give a name to a value:
name = "Harshika" int (Integer)
age = 17
Whole numbers: 10, -5, 1000, 0
height = 5.6
is_student = True
Python automatically determines that name is a string, age is an float (Floating Point)
integer, height is a float, and is_student is a boolean. This flexibility
Decimal numbers: 12.5, -0.001, 3.14159
makes Python incredibly beginner-friendly, though you should always
be mindful of what type of data you're working with.
Variables can change their values (that's why they're called str (String)
"variables"!) and even change types during program execution:
Text values: "Hello", 'Python', "123"
x = 10 # x is an integer
x = "hello" # now x is a string
x = 3.14 # now x is a float bool (Boolean)
Logical values: True or False
list
Ordered, changeable: [1, 2, 3, "mix"]
tuple
Ordered, unchangeable: (1, 2, 3)
dict (Dictionary)
Key-value pairs: {"name": "Riya", "age": 16}
Input and Output Operations
Programs become truly interactive when they can communicate with users. Python provides straightforward functions for both receiving input
from users and displaying output to them. These fundamental operations are the gateway to creating engaging, responsive programs.
Getting Input Displaying Output
The input() function pauses your program and waits for the user to The print() function displays information to the console. It's your
type something, then returns that text as a string. You can provide a primary tool for showing results, debugging, and communicating
prompt message to guide the user: with users:
name = input("Enter your name: ") print("Hello, World!")
age = input("Enter your age: ") print("Your name is:", name)
print("Sum:", 5 + 3)
Important: The input() function always returns a string! If you need
a number, you must convert it: You can print multiple items separated by commas, and Python will
add spaces between them automatically. You can also use f-strings
for elegant formatting:
age = int(input("Enter your age: "))
height = float(input("Enter height: "))
print(f"Hello {name}, you are {age} years old")
print(f"Next year you'll be {age + 1}!")
A Complete Example
# Interactive greeting program
name = input("What's your name? ")
age = int(input("How old are you? "))
city = input("Where do you live? ")
print(f"\nNice to meet you, {name}!")
print(f"At {age} years old in {city}, you're in a great place to learn Python!")
print(f"In 5 years, you'll be {age + 5}. Imagine what you'll build by then!")
Operators in Python
Operators are special symbols that perform operations on values and variables. They're the mathematical and logical tools that let you manipulate
data, make comparisons, and build complex logic into your programs. Understanding operators is crucial for writing effective Python code.
Arithmetic Operators Relational Operators Logical Operators
Perform mathematical calculations: Compare values (return True or False): Combine boolean conditions:
+ Addition: 5 + 3 = 8 == Equal to: 5 == 5 ³ True and Both must be True
- Subtraction: 10 - 4 = 6 != Not equal: 5 != 3 ³ True or At least one must be True
* Multiplication: 6 * 7 = 42 > Greater than: 10 > 5 ³ True not Inverts the boolean value
/ Division: 15 / 4 = 3.75 < Less than: 3 < 7 ³ True Example:
// Floor Division: 15 // 4 = 3 >= Greater or equal: 5 >= 5 ³ True
% Modulus (remainder): 15 % 4 = 3 <= Less or equal: 4 <= 6 ³ True age = 20
has_license = True
** Exponentiation: 2 ** 3 = 8
can_drive = age >= 18 and
has_license
Assignment Operators Membership Operators
Assign and modify values efficiently: Check if a value exists in a sequence:
x = 10 # Basic assignment fruits = ["apple", "banana", "mango"]
x += 5 # Same as x = x + 5 (x becomes 15) print("apple" in fruits) # True
x -= 3 # Same as x = x - 3 (x becomes 12) print("grape" in fruits) # False
x *= 2 # Same as x = x * 2 (x becomes 24) print("grape" not in fruits) # True
x /= 4 # Same as x = x / 4 (x becomes 6.0)
x //= 2 # Same as x = x // 2 (x becomes 3.0) text = "Python programming"
x %= 2 # Same as x = x % 2 (x becomes 1.0) print("Python" in text) # True
print("Java" not in text) # True
Making Decisions with Conditional Statements
Programs need to make decisions based on different conditions. Conditional statements allow your code to execute different actions depending on
whether certain conditions are true or false. This is where your programs start to feel intelligent and responsive!
The if Statement 01
The most basic decision-making structure checks a single condition: Evaluate Condition
Python checks if the condition is True or False
age = 18
if age >= 18: 02
print("You are eligible to vote!")
Execute if True
print("Don't forget to register!")
Runs the indented code block under the if statement
The if-else Statement
03
Provides an alternative action when the condition is false:
Skip if False
temperature = 25 Moves to elif or else blocks, or continues past the statement
if temperature > 30:
print("It's hot! Stay hydrated.")
else: Indentation Matters! Python uses indentation
print("Weather is pleasant.") (spaces or tabs) to define code blocks. All code that
should execute when a condition is true must be
The if-elif-else Statement indented at the same level. This is not just style4it's
syntax!
Handles multiple conditions in sequence:
score = 85 Nested Conditions
if score >= 90:
You can place if statements inside other if statements:
grade = "A"
elif score >= 80:
age = 20
grade = "B"
has_license = True
elif score >= 70:
grade = "C"
if age >= 18:
elif score >= 60:
if has_license:
grade = "D"
print("You can drive!")
else:
else:
grade = "F"
print("Get a license first.")
print(f"Your grade is: {grade}")
else:
print("Too young to drive.")
Loops: Repeating Actions
Loops are one of programming's most powerful features4they let you execute the same code multiple times without writing it repeatedly.
Imagine having to write print("Hello") 100 times versus just looping 100 times! Loops make your code efficient, elegant, and scalable.
For Loops While Loops
Use for loops when you know exactly how many times you want to Use while loops when you want to repeat something until a
repeat something, or when you want to iterate through a certain condition becomes false. The loop continues as long as the
sequence (like a list or string). condition remains true.
Basic Range Loop Basic While Loop
for i in range(5): count = 1
print(f"Count: {i}") while count <= 5:
# Output: 0, 1, 2, 3, 4 print(f"Count: {count}")
count += 1
Custom Range
User Input Loop
for num in range(1, 11):
print(num) password = ""
# Prints 1 through 10 while password != "secret":
password = input("Enter password: ")
Step Range print("Access granted!")
for n in range(0, 20, 3): Infinite Loop (be careful!)
print(n)
# Output: 0, 3, 6, 9, 12, 15, 18 while True:
answer = input("Continue? (y/n): ")
Iterating Through Lists if [Link]() == "n":
break
fruits = ["apple", "banana", "mango"] print("Continuing...")
for fruit in fruits:
print(f"I love {fruit}!") Loop Control Statements
break - Exit the loop immediately
Iterating Through Strings
continue - Skip to next iteration
pass - Do nothing (placeholder)
word = "Python"
for letter in word:
print(letter) for i in range(10):
if i == 3:
continue # Skip 3
if i == 7:
break # Stop at 7
print(i)
Lists and Strings: Working with Sequences
Lists and strings are two of Python's most versatile data structures. They both represent sequences of elements, but with different characteristics
and use cases. Mastering these structures will dramatically expand what you can accomplish in Python.
Lists: Flexible Collections Strings: Text Processing
Lists are ordered, mutable (changeable) collections that can hold any Strings are sequences of characters that are immutable (cannot be
type of data. They're incredibly versatile and one of Python's most changed after creation). Python provides powerful tools for
commonly used data structures. manipulating text.
Creating and Accessing Lists String Creation and Access
fruits = ["apple", "banana", "mango", "orange"] message = "AI is fun!"
print(fruits[0]) # "apple" (first item) print(message[0]) # "A" (first character)
print(fruits[-1]) # "orange" (last item) print(message[-1]) # "!" (last character)
print(fruits[1:3]) # ["banana", "mango"] (slicing) print(message[0:2]) # "AI" (slicing)
print(message[::2]) # "A sfn" (every 2nd char)
Modifying Lists
String Methods
[Link]("grape") # Add to end
[Link](1, "kiwi") # Insert at position text = "Python Programming"
[Link]("banana") # Remove by value print([Link]()) # "PYTHON PROGRAMMING"
popped = [Link]() # Remove and return last item print([Link]()) # "python programming"
fruits[0] = "blueberry" # Change by index print([Link]()) # "Python Programming"
print([Link]("P", "J")) # "Jython Jrogramming"
Useful List Methods print([Link]()) # ["Python", "Programming"]
print([Link]("m")) # Count 'm' occurrences
numbers = [3, 1, 4, 1, 5, 9, 2] print([Link]("gram")) # Find substring position
[Link]() # Sort in place
[Link]() # Reverse in place String Formatting
print(len(numbers)) # Length of list
print([Link](1)) # Count occurrences # Old style
print([Link](4)) # Find index of value name = "Riya"
age = 16
List Operations print("My name is %s" % name)
list1 = [1, 2, 3] # Modern f-strings (preferred)
list2 = [4, 5, 6] print(f"My name is {name}")
combined = list1 + list2 # [1, 2, 3, 4, 5, 6] print(f"Next year I'll be {age + 1}")
repeated = list1 * 3 # [1, 2, 3, 1, 2, 3, 1, 2, 3] print(f"Calculation: {5 * 10}")
print(2 in list1) # True (membership)
# format() method
print("Hello {}, you are {}".format(name, age))
String Checking
text = "Python123"
print([Link]()) # False (has numbers)
print([Link]()) # False (has letters)
print([Link]()) # True (alphanumeric)
print([Link]("P")) # True
print([Link]("3")) # True
Functions and Python's Role in AI
Functions: Reusable Code Blocks Python's Dominance in AI
Functions are named blocks of code that perform specific tasks. Python has become the undisputed champion of artificial intelligence
They're one of the most important concepts in programming because and machine learning. Its simplicity, combined with powerful libraries,
they help you write organized, reusable, and maintainable code. makes it the perfect tool for both learning and building production AI
Instead of repeating the same code everywhere, you write it once in a systems.
function and call it whenever needed.
Defining Functions
Rich AI Ecosystem
def greet(name):
TensorFlow, PyTorch, and Keras make deep learning accessible
"""Welcome message function"""
print(f"Hello, {name}!")
print("Welcome to Python!")
greet("Riya") Data Processing
greet("Harshika") NumPy, Pandas excel at manipulating massive datasets efficiently
Functions with Return Values
def calculate_area(length, width):
Visualization Tools
"""Calculate rectangle area"""
area = length * width Matplotlib, Seaborn create stunning data visualizations
return area
result = calculate_area(5, 10)
print(f"Area: {result} square units") ML Frameworks
Scikit-learn provides ready-to-use machine learning algorithms
Default Parameters
def power(base, exponent=2):
"""Raise base to exponent"""
return base ** exponent
print(power(5)) # 25 (default exponent)
print(power(5, 3)) # 125 (custom exponent)
Multiple Return Values
def get_stats(numbers):
"""Return min, max, and average"""
return min(numbers), max(numbers),
sum(numbers)/len(numbers)
data = [10, 20, 30, 40, 50]
minimum, maximum, average = get_stats(data)
print(f"Min: {minimum}, Max: {maximum}, Avg:
{average}")
Why Python for AI?
Simple syntax lets you focus on algorithms, not language
complexity
Vast libraries mean you don't build everything from scratch
Community support provides endless tutorials and resources
Industry adoption makes Python skills highly valuable
Research friendly enables rapid prototyping and
experimentation
Your Python Journey: What's Next?
Congratulations on completing this introduction to Python! You've learned the fundamentals that form the foundation of all Python programming:
variables, data types, operators, conditionals, loops, lists, strings, and functions. These concepts are your building blocks for creating everything
from simple scripts to sophisticated AI systems.
Python's beauty lies in its scalability4the same principles you've learned here will serve you whether you're building a personal automation script,
analyzing scientific data, developing web applications, or training neural networks. The path from beginner to AI/ML engineer starts exactly where
you are now. Keep practicing, stay curious, and remember: every expert programmer once started by printing "Hello, World!" Your journey in
Python and AI has just begun4and the possibilities are limitless!