0% found this document useful (0 votes)
15 views8 pages

COS 101 Notes PT Ii_111706

The document provides a comprehensive guide to Python basics, covering key concepts such as variables, conditional statements, functions, loops, lists, and dictionaries, along with examples. It also includes additional topics like string manipulation, list comprehension, exception handling, and the use of break and continue statements in loops. Each section emphasizes important points and practical examples to illustrate the functionality of Python programming.

Uploaded by

zkafsl26
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)
15 views8 pages

COS 101 Notes PT Ii_111706

The document provides a comprehensive guide to Python basics, covering key concepts such as variables, conditional statements, functions, loops, lists, and dictionaries, along with examples. It also includes additional topics like string manipulation, list comprehension, exception handling, and the use of break and continue statements in loops. Each section emphasizes important points and practical examples to illustrate the functionality of Python programming.

Uploaded by

zkafsl26
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
You are on page 1/ 8

COS 101 Notes PT ii

Python Basics: A Comprehensive Guide with Examples


Python is a high-level, interpreted programming language that is widely used for web
development, data science, automation, and more. Below is a detailed explanation of
fundamental Python concepts, along with expanded examples.

1. Variables
Definition
A variable is a named location in memory used to store a value. In Python, variables do not
require explicit declaration; they are created when a value is assigned.

Example

# Assigning values to variables


age = 25
name = "John"
height = 5.9
is_student = False

# Printing variable values


print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is student:", is_student)

Key Points
Variable names should be meaningful.
Python is dynamically typed, meaning you don’t need to specify a data type.
Use lowercase letters with underscores for readability ( user_age instead of userAge ).
2. Conditional Statements
Definition
Conditional statements allow a program to make decisions based on conditions. Python
provides if , elif , and else statements.

Example

age = 18

if age >= 18:


print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")

Key Points
The if block executes if the condition is True .
The elif block is checked if the if condition is False .
The else block runs when all previous conditions are False .

Example: Checking Even or Odd Number

number = 7

if number % 2 == 0:
print("Even number")
else:
print("Odd number")

3. Functions
Definition
A function is a reusable block of code that performs a specific task. Functions improve code
organization and reusability.
Example

def greet(name):
return "Hello, " + name

print(greet("Alice"))

Key Points
Functions start with the def keyword.
Arguments (parameters) are passed inside parentheses.
The return statement sends back a result.
Functions help in modularizing code.

Example: Function with Multiple Parameters

def add_numbers(a, b):


return a + b

result = add_numbers(5, 3)
print("Sum:", result) # Output: Sum: 8

Example: Function with Default Parameters

def greet(name="Guest"):
return "Hello, " + name

print(greet()) # Output: Hello, Guest


print(greet("Mike")) # Output: Hello, Mike

4. Loops and Lists


Definition
Loops allow repetition of code execution, and lists store multiple items in a single variable.

Lists Example
# Defining a list
names = ["Alice", "Bob", "Charlie"]

# Accessing elements
print(names[0]) # Output: Alice
print(names[-1]) # Output: Charlie (last element)

For Loop with Lists

for name in names:


print(name)

While Loop Example

count = 0
while count < 5:
print("Count:", count)
count += 1

Key Points
for loops iterate over sequences (lists, tuples, strings).
while loops run as long as a condition is True .

5. Dictionary
Definition
A dictionary is a data structure that stores key-value pairs.

Example

person = {
"name": "Alice",
"age": 25,
"city": "New York"
}

# Accessing values
print(person["name"]) # Output: Alice

# Adding a new key-value pair


person["job"] = "Engineer"

# Looping through dictionary


for key, value in person.items():
print(key, ":", value)

Key Points
Dictionaries use {} with key-value pairs.
Keys must be unique and immutable (strings, numbers, or tuples).
Use .items() to loop through key-value pairs.

Bonus: Additional Topics


1. String Manipulation

text = "Hello, Python!"


print(text.upper()) # Convert to uppercase
print(text.lower()) # Convert to lowercase
print(text.replace("Python", "World")) # Replace text
print(text.split(",")) # Split string into list

2. List Comprehension

numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
print(squared) # Output: [1, 4, 9, 16, 25]

3. Exception Handling

try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Invalid input! Please enter a valid number.")
Break and Continue in Loops
These statements are used to alter the flow of loops.

1. break Statement
The break statement is used to exit a loop prematurely when a certain condition is met.

Example: Breaking a for Loop

for number in range(10):


if number == 5:
print("Stopping at", number)
break
print(number)

Output:

0
1
2
3
4
Stopping at 5

Explanation: The loop stops completely when number equals 5 .

Example: Breaking a while Loop

count = 0
while count < 10:
if count == 5:
print("Loop stopped at", count)
break
print(count)
count += 1

Output:
0
1
2
3
4
Loop stopped at 5

Explanation: The loop stops when count reaches 5 .

2. continue Statement
The continue statement skips the current iteration and moves to the next one.

Example: Skipping Even Numbers

for number in range(10):


if number % 2 == 0:
continue # Skip even numbers
print(number)

Output:

1
3
5
7
9

Explanation: The loop skips printing even numbers.

Example: Skipping a Specific Number in a While Loop

count = 0
while count < 10:
count += 1
if count == 5:
continue # Skip printing 5
print(count)

Output:

1
2
3
4
6
7
8
9
10

Explanation: The number 5 is skipped.

When to Use break and continue


Use break when you want to stop a loop completely.
Use continue when you want to skip an iteration but continue looping.

Would you like more real-world examples of where break and continue are useful?

You might also like