









































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!










































































Programming is the process of giving instructions to a computer to perform specific tasks. It involves writing code in a programming language that the computer can understand and execute.
Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in: Web Development (Django, Flask) Data Science and Machine Learning (Pandas, NumPy, TensorFlow) Automation and Scripting Game Development (Pygame) Python has a large community and extensive libraries, making it beginner-friendly.
Download Python:
Visit the official Python website: python.org.
Download the latest version for your operating system (Windows, macOS, or Linux).
Install Python:
Run the installer and ensure you check the box to Add Python to PATH (important for running Python from the command line).
Verify Installation:
Open a terminal or command prompt and type:
This should display the installed Python version (e.g., Python 3.13.5 ).
What is an IDE? An Integrated Development Environment (IDE) is a software application that provides tools for writing, testing, and debugging code. Popular Python IDEs: VS Code: Lightweight, customizable, and supports extensions for Python. (We will use this one as our primary IDE) PyCharm: Powerful IDE with advanced features for professional developers. Jupyter Notebook: Great for data science and interactive coding. IDLE: Comes pre-installed with Python; good for beginners.
Writing Your First Python Program
Open a folder in your VS code and type the following code in a new file named hello.py :
python --version
Whitespace:
Python is sensitive to whitespace. Ensure consistent indentation to avoid errors. Ideally, use 4 spaces for indentation.
Statements:
Each line of code is a statement. You can write multiple statements on one line using a semicolon ( ; ), but this is not recommended.
Comments:
Use # for single-line comments. Use ''' or """ for multi-line comments. Example:
Notes from Instructor
Python is a versatile and beginner-friendly programming language. Setting up Python and choosing the right IDE is the first step to writing code. Python syntax is simple but requires attention to indentation and whitespace. Start with small programs like "Hello, World!" to get comfortable with the basics.
if 5 > 2: print("Five is greater than two!")
''' This is a multi-line comment '''
Variables are used to store data that can be used and manipulated in a program.
A variable is created when you assign a value to it using the = operator.
Example:
Variable names can contain letters, numbers, and underscores. Variable names must start with a letter or underscore. Variable names are case-sensitive. Avoid using Python keywords as variable names (e.g., print , if , else ).
Use descriptive names that reflect the purpose of the variable. Use lowercase letters for variable names. Separate words using underscores for readability (e.g., first_name , total_amount ).
name = "Alice" age = 25 height = 5.
Taking User Input in Python
The input() function allows you to take user input from the keyboard.
By default, input() returns a string. You can convert it to other data types as needed.
Example:
num_str = "10" num_int = int(num_str) print(num_int) # Output: 10
num = 25 num_str = str(num) print(num_str) # Output: "25"
pi = 3. pi_int = int(pi) print(pi_int) # Output: 3
name = input("Enter your name: ") age = int(input("Enter your age: ")) print(f"Hello {name}, you are {age} years old.")
Comments, Escape Sequences & Print Statement
Comments are used to explain code and are ignored by the Python interpreter.
Single-line comments start with #.
Multi-line comments are enclosed in ''' or """.
Escape sequences are used to include special characters in strings.
Common escape sequences:
\n : Newline \t : Tab \ : Backslash " : Double quote ' : Single quote
Example:
The print() function is used to display output.
''' This is a multi-line comment '''
print("Hello\nWorld!") print("This is a tab\tcharacter.")
Assignment Operators:
= , += , -= , *= , /= , %= , **= , //=.
Example:
Membership Operators:
in , not in.
Example:
Identity Operators:
is , is not.
Example:
Summary
Variables store data, and Python supports multiple data types. Typecasting allows you to convert between data types. Use input() to take user input and print() to display output. Comments and escape sequences help make your code more readable. Python provides a variety of operators for performing operations on data.
x = 10 x += 5 # Equivalent to x = x + 5 print(x) # Output: 15
fruits = ["apple", "banana", "cherry"] print("banana" in fruits) # Output: True
x = 10 y = 10 print(x is y) # Output: True
Conditional statements allow you to execute code based on certain conditions. Python uses if , elif , and else for decision-making.
if condition1:
elif condition2:
else:
age = 18
if age < 18: print("You are a minor.") elif age == 18: print("You just became an adult!") else: print("You are an adult.")
The range() function generates a sequence of numbers.
Example:
While Loops in Python
While loops execute a block of code as long as a condition is True. They are useful when the number of iterations is not known in advance.
for item in sequence:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits: print(fruit)
for i in range(5): print(i) # Output: 0, 1, 2, 3, 4
while condition:
Be careful to avoid infinite loops by ensuring the condition eventually becomes False.
Example of an infinite loop:
Break, Continue, and Pass Statements
The break statement is used to exit a loop prematurely.
Example:
The continue statement skips the rest of the code in the current iteration and moves to the next iteration.
count = 0
while count < 5: print(count) count += 1
while True: print("This will run forever!")
for i in range(10): if i == 5: break print(i) # Output: 0, 1, 2, 3, 4
Strings in Python
Strings are one of the most fundamental data types in Python. A string is a sequence of characters enclosed within either single quotes ( ' ), double quotes
( " ), or triple quotes ( ''' or โโโ).
You can create strings in Python using different types of quotes:
Each character in a string has an index:
a = 'Hello, Python!'
b = "Hello, World!"
c = '''This is a multi-line string.'''
text = "Python" print(text[0]) # Output: P print(text[1]) # Output: y print(text[-1]) # Output: n (last character)
You can extract parts of a string using slicing:
Python provides several built-in methods to manipulate strings:
Python offers multiple ways to format strings:
Triple quotes allow you to create multi-line strings:
text = "Hello, Python!" print(text[0:5]) # Output: Hello print(text[:5]) # Output: Hello print(text[7:]) # Output: Python! print(text[::2]) # Output: Hlo Pto!
text = " hello world " print(text.upper()) # Output: " HELLO WORLD " print(text.lower()) # Output: " hello world " print(text.strip()) # Output: "hello world" print(text.replace("world", "Python")) # Output: " hello Python " print(text.split()) # Output: ['hello', 'world']
name = "John" age = 25
print("My name is {} and I am {} years old.".format(name, age))
print(f"My name is {name} and I am {age} years old.")
Slicing allows you to extract a portion of a string using the syntax string[start:stop:step].
Step Parameter
The step parameter defines the interval of slicing.
String slicing is useful in many scenarios: - Extracting substrings - Reversing strings
Indexing allows accessing individual characters. Positive indexing starts from 0, negative indexing starts from -1. Slicing helps extract portions of a string. The step parameter defines the interval for selection.
text = "Hello, Python!" print(text[0:5]) # Output: Hello print(text[:5]) # Output: Hello (same as text[0:5]) print(text[7:]) # Output: Python! (from index 7 to end) print(text[::2]) # Output: Hlo Pto! print(text[-6:-1]) # Output: ython (negative indexing)
text = "Python Programming" print(text[::2]) # Output: Pto rgamn print(text[::-1]) # Output: gnimmargorP nohtyP (reverses string)
text = "Welcome to Python!" print(text[:7]) # Output: Welcome print(text[-7:]) # Output: Python! print(text[3:-3]) # Output: come to Pyt
Using [::-1] reverses a string.
String Methods and Functions
Python provides a variety of built-in string methods and functions to manipulate
and process strings efficiently.
Changing Case
Removing Whitespace
Finding and Replacing
Splitting and Joining
text = "hello world" print(text.upper()) # Output: "HELLO WORLD" print(text.lower()) # Output: "hello world" print(text.title()) # Output: "Hello World" print(text.capitalize()) # Output: "Hello world"
text = " hello world " print(text.strip()) # Output: "hello world" print(text.lstrip()) # Output: "hello world " print(text.rstrip()) # Output: " hello world"
text = "Python is fun" print(text.find("is")) # Output: 7 print(text.replace("fun", "awesome")) # Output: "Python is awesome"
text = "apple,banana,orange" fruits = text.split(",") print(fruits) # Output: ['apple', 'banana', 'orange']