0% found this document useful (0 votes)
307 views11 pages

Python Notes

Python relies on proper indentation to structure code and define code blocks. Indentation helps Python identify the beginning and end of blocks of code. For example, in an if/else statement, the indented blocks after if and else will execute depending on whether the condition is true or false. Proper indentation ensures the code is visually organized and Python understands the logical structure of the program.

Uploaded by

Saleha Yasir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
307 views11 pages

Python Notes

Python relies on proper indentation to structure code and define code blocks. Indentation helps Python identify the beginning and end of blocks of code. For example, in an if/else statement, the indented blocks after if and else will execute depending on whether the condition is true or false. Proper indentation ensures the code is visually organized and Python understands the logical structure of the program.

Uploaded by

Saleha Yasir
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 11

Syntax

o Syntax refers to the set of rules and structure that define how Python code should be written.
o It includes things like the order of statements, the use of punctuation, and the indentation of code
blocks.
o In Python, the syntax is designed to be readable and easy to understand.
o It uses indentation (usually four spaces) to define code blocks instead of using braces or keywords
like other programming languages. This indentation is important as it helps Python identify the
beginning and end of blocks of code.
o For example, consider the following code snippet:
# Example of syntax in Python
x=5
if x > 0:
print("Positive number")
else:
print("Non-positive number")
In this code, the syntax is as follows:
- The variable `x` is assigned the value of `5`.
- The `if` statement checks if `x` is greater than `0`.
- The subsequent indented block of code executes if the condition is true, printing "Positive number".
- The `else` statement is followed by another indented block of code, which executes if the condition is false,
printing "Non-positive number".
o Python relies heavily on indentation to structure code and make it readable.
o Proper indentation ensures that the code is visually organized and helps Python understand the
logical structure of the program.
o Practice problem:
Write a Python program that asks the user to enter two numbers and calculates their sum.
o Here's a possible solution:

# Practice problem: Sum of two numbers


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

sum = num1 + num2


print("The sum of", num1, "and", num2, "is", sum)
In this program, the `input()` function is used to prompt the user to enter two numbers. The `float()` function
is used to convert the input to floating-point numbers. The sum of the two numbers is calculated and stored
in the variable `sum`. Finally, the result is displayed using the `print()` function.
Basic concepts in python
Variables, data types, operators, control structures (if statements, loops), and functions.
Variables:
o In Python, a variable is a name that represents a value stored in the computer's memory.
o It acts as a container to hold data that can be used and manipulated throughout a program.
o Variables allow us to store and access information, making our code more dynamic and flexible.
o To use a variable in Python, you need to assign a value to it using the assignment operator `=`.
o The value can be of any data type, such as numbers, strings, or even more complex objects like lists
or dictionaries.
o Unlike some other programming languages, you don't need to explicitly declare the variable type in
Python.
o For example, consider the following code snippet:
# Example of variables in Python
message = "Hello, Python!"
number = 42
pi = 3.14
print(message)
print(number)
print(pi)
In this code, we have three variables: `message`, `number`, and `pi`. Each variable is assigned a specific
value. The `print()` function is used to display the values of these variables.
o Variables can also be reassigned to new values as the program progresses:
# Reassigning variables
x=5
print(x) # Output: 5
x = 10
print(x) # Output: 10
In this example, the variable `x` is initially assigned the value `5`. However, we can reassign a new value to
`x`, in this case `10`. The new value replaces the previous one, and when we print `x`, it displays the
updated value.
o Practice problem:
Write a Python program that calculates the area of a rectangle. The length and width of the rectangle
should be stored in variables, and the result should be displayed.
o Here's a possible solution:
# Practice problem: Calculating the area of a rectangle
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print("The area of the rectangle is:", area)
In this program, the `input()` function is used to prompt the user to enter the length and width of the
rectangle. The `float()` function is used to convert the input to floating-point numbers. The area is
calculated by multiplying the length and width, and the result is stored in the variable `area`. Finally, the
area is displayed using the `print()` function.
Data types:
In Python, the following are some of the built-in data types:
1. Numeric Types:
 int: Integer values, e.g., 10, -3, 0.
 float: Floating-point values, e.g., 3.14, -2.5, 0.0.
 complex: Complex numbers, e.g., 1 + 2j, -3j.
2. Sequence Types:
 str: Strings of characters, e.g., "Hello", 'Python'.
 list: Ordered, mutable sequences, e.g., [1, 2, 3], ['a', 'b', 'c'].
 tuple: Ordered, immutable sequences, e.g., (1, 2, 3), ('a', 'b', 'c').
3. Mapping Type:
 dict: Key-value pairs, also known as dictionaries, e.g., {'name': 'John', 'age': 25}.
4. Set Types:
 set: Unordered collections of unique elements, e.g., {1, 2, 3}, {'a', 'b', 'c'}.
 frozenset: Immutable versions of sets, e.g., frozenset({1, 2, 3}).
5. Boolean Type:
 bool: Represents either True or False.
6. None Type:
 None: Represents the absence of a value.
These are the commonly used built-in data types in Python. Additionally, Python allows you to create your
own custom data types using classes.
Operators:
o In Python, operators are symbols or special characters that perform various operations on operands.
o Operands can be variables, values, or expressions.
o Python provides a wide range of operators to handle different types of operations, such as arithmetic,
comparison, logical, assignment, and more.
o Let's look at some commonly used operators in Python:
1. Arithmetic Operators:
- Addition (`+`): Adds two operands.
- Subtraction (`-`): Subtracts the second operand from the first.
- Multiplication (`*`): Multiplies two operands.
- Division (`/`): Divides the first operand by the second.
- Modulus (`%`): Returns the remainder of the division.
- Exponentiation (`**`): Raises the first operand to the power of the second.
- Floor Division (`//`): Performs integer division, discarding the remainder.
2. Comparison Operators:
- Equal to (`==`): Checks if two operands are equal.
- Not equal to (`!=`): Checks if two operands are not equal.
- Greater than (`>`): Checks if the first operand is greater than the second.
- Less than (`<`): Checks if the first operand is less than the second.
- Greater than or equal to (`>=`): Checks if the first operand is greater than or equal to the
second.
- Less than or equal to (`<=`): Checks if the first operand is less than or equal to the second.
3. Logical Operators:
- And (`and`): Returns `True` if both operands are `True`.
- Or (`or`): Returns `True` if either operand is `True`.
- Not (`not`): Returns the opposite of the operand's value (`True` becomes `False`, and vice
versa).
4. Assignment Operators:
- Assignment (`=`): Assigns a value to a variable.
- Add and assign (`+=`): Adds the right operand to the left operand and assigns the result to the
left operand.
- Subtract and assign (`-=`): Subtracts the right operand from the left operand and assigns the
result to the left operand.
- Multiply and assign (`*=`): Multiplies the left operand by the right operand and assigns the
result to the left operand.
- Divide and assign (`/=`): Divides the left operand by the right operand and assigns the result
to the left operand.
o Practice problem:
Write a Python program that converts a temperature from Fahrenheit to Celsius. Prompt the user to
enter the temperature in Fahrenheit, perform the conversion, and display the result in Celsius.
o Here's a possible solution:
# Practice problem: Fahrenheit to Celsius conversion
fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5 / 9
print("The temperature in Celsius is:", celsius)
In this program, the `input()` function is used to prompt the user to enter the temperature in Fahrenheit. The
`float()` function is used to convert the input to a floating-point number. The conversion from Fahrenheit to
Celsius is performed using the formula `(F - 32) * 5/9`, and the result is stored in the variable `celsius`.
Finally, the temperature in Celsius is displayed using the `print()` function.
Control structures:
o In Python, control structures refer to the constructs that allow you to control the flow and execution
of your program.
o They determine the order in which statements are executed and provide mechanisms for making
decisions and repeating actions.
o There are three main types of control structures in Python:
1. Conditional Statements (if-elif-else):
 The `if` statement allows you to execute a block of code only if a certain condition is true.
 The `elif` statement (short for "else if") allows you to check additional conditions after the initial
`if` statement.
 The `else` statement is used to specify a block of code that should be executed if none of the
preceding conditions are true.
 Example:
# Control structure: if-elif-else
x=5
if x > 0:
print("Positive number")
elif x < 0:
print("Negative number")
else:
print("Zero")
2. Loops:
 The `for` loop is used to iterate over a sequence (such as a list, tuple, or string) or any iterable object.
 The `while` loop repeatedly executes a block of code as long as a specified condition is true.
 Example of a `for` loop:
# Control structure: for loop
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
 Example of a `while` loop:
# Control structure: while loop
count = 0
while count < 5:
print(count)
count += 1
3. Control Statements:
 `break` statement: Terminates the current loop and transfers control to the next statement after the
loop.
 `continue` statement: Skips the rest of the current iteration and moves to the next iteration of the
loop.
 `pass` statement: Acts as a placeholder, indicating that no action should be taken at a specific point
in the code.
 Example:
# Control structure: break, continue, pass
for num in range(1, 10):
if num == 5:
break
elif num % 2 == 0:
continue
else:
pass
print(num)
if statements:
o Conditional statements, often referred to as "if statements," allow you to execute different blocks of
code based on specific conditions.
o They help your program make decisions and choose different paths of execution depending on
whether certain conditions are true or false.
o In Python, conditional statements are typically written using the `if`, `elif` (short for "else if"), and
`else` keywords.
o Here's a breakdown of their usage:
1. `if` statement:
 The `if` statement is used to check a condition. If the condition is true, the block of code
indented below the `if` statement is executed.
 If the condition is false, the code block is skipped, and the program moves on to the next
statement.
2. `elif` statement:
 The `elif` statement allows you to check additional conditions after the initial `if` statement.
 It is used when you have multiple conditions to evaluate and execute different blocks of code
depending on which condition is true.
 You can have multiple `elif` statements, but only one block of code will be executed—the
one corresponding to the first true condition encountered.
3. `else` statement:
 The `else` statement is used to specify a block of code that should be executed if none of the
preceding conditions (if or elif) are true.
 It provides a fallback option when none of the previous conditions are satisfied.
o Here's an example to illustrate the usage of conditional statements

# Example of conditional statements


age = 18
if age < 18:
print("You are underage.")
elif age == 18:
print("You just turned 18!")
else:
print("You are an adult.")
In this code, the program checks the value of the variable `age`. Depending on the value, it executes a
specific block of code:
- If `age` is less than 18, it prints "You are underage."
- If `age` is exactly 18, it prints "You just turned 18!"
- If none of the above conditions are true, it prints "You are an adult."
o Practice problem:
Write a Python program that determines whether a given number is positive, negative, or zero.
Prompt the user to enter a number, evaluate the condition, and display the appropriate message.
o Here's a possible solution:
# Practice problem: Positive, negative, or zero
number = float(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
In this program, the `input()` function is used to prompt the user to enter a number. The number is then
evaluated using conditional statements:
- If the number is greater than 0, it prints "The number is positive."
- If the number is less than 0, it prints "The number is negative."
- If the number is neither greater nor less than 0, it must be 0, so it prints "The number is zero."
loops:
o Loops in Python allow you to repeatedly execute a block of code until a certain condition is met.
o They provide a way to automate repetitive tasks and iterate over collections of data.
o There are two main types of loops in Python:
1. `for` loop:
 The `for` loop is used to iterate over a sequence (such as a list, tuple, or string) or any
iterable object.
 It allows you to perform a specific action for each item in the sequence.
 The loop variable takes on each value in the sequence one by one, and the indented block of
code below the `for` loop is executed for each iteration.
2. `while` loop:
 The `while` loop repeatedly executes a block of code as long as a specified condition is true.
 It allows you to perform a certain action repeatedly until the condition becomes false.
 The condition is evaluated before each iteration. If it is true, the indented block of code
below the `while` loop is executed. If it becomes false, the program moves on to the next
statement after the `while` loop.
o Here's an example to illustrate the usage of loops:
# Example of loops
fruits = ["apple", "banana", "orange"]
# Using a for loop
for fruit in fruits:
print(fruit)
# Using a while loop
count = 0
while count < 5:
print(count)
count += 1
In this code, we have two examples of loops:
- The `for` loop iterates over each item in the `fruits` list and prints each item (fruit) on a new line.
- The `while` loop starts with a `count` of 0 and prints the value of `count` on each iteration until it reaches
5. After each iteration, the `count` is incremented by 1 using the `+=` shorthand operator.
o Practice problem:
Write a Python program that calculates the sum of numbers from 1 to a given number (inclusive).
Prompt the user to enter a number, perform the calculation, and display the result.
o Here's a possible solution:
# Practice problem: Sum of numbers
number = int(input("Enter a number: "))
sum = 0
for num in range(1, number + 1):
sum += num
print("The sum of numbers from 1 to", number, "is:", sum)
In this program, the `input()` function is used to prompt the user to enter a number. The number is then used
to calculate the sum of numbers from 1 to that number using a `for` loop. The loop iterates over the range of
numbers from 1 to `number + 1` (inclusive) and adds each number to the `sum` variable. Finally, the sum is
displayed using the `print()` function.
Break
 In Python, the `break` statement is used to prematurely exit a loop before its normal completion.
 When encountered, the `break` statement immediately terminates the innermost loop (such as a `for`
or `while` loop) and transfers control to the next statement following the loop.
 Here are some key points about the `break` statement:
 It is typically used within a loop when a specific condition is met, and there is no need to
continue iterating.
 When the `break` statement is executed, the program jumps out of the loop entirely,
bypassing any remaining iterations.
 The `break` statement can be used in both `for` and `while` loops.
 Here's an example to demonstrate the usage of the `break` statement:
# Example of break statement
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number == 3:
break
print(number)
print("Loop ended.")
In this code, the `for` loop iterates over the `numbers` list. Inside the loop, there is an `if` statement that
checks if the current number is equal to 3. If the condition is true, the `break` statement is executed, and the
loop is terminated immediately. As a result, the number 3 is never printed, and the program jumps to the
line after the loop, which prints "Loop ended."
 The `break` statement is useful when you want to stop iterating through a loop prematurely based on
a specific condition. It allows you to control the flow of your program and exit the loop when
necessary.
Functions:
o In Python, a function is a reusable block of code that performs a specific task or a set of tasks.
o It allows you to group related code together and execute it multiple times without having to rewrite
the same code again and again.
o Functions help in organizing and modularizing your code, making it more readable, maintainable,
and reusable.
o Functions in Python have the following characteristics:
1. Function Definition:
 A function is defined using the `def` keyword, followed by the function name and
parentheses. Any input parameters (arguments) are specified within the parentheses.
 The code block of the function is indented below the function definition.
2. Function Call:
 To execute a function, you need to call it by using its name followed by parentheses.
 If the function accepts arguments, you pass the necessary values within the parentheses.
3. Return Statement:
 A function can optionally return a value using the `return` statement.
 The `return` statement is used to send a value back to the caller of the function.
 If the `return` statement is omitted, the function will still execute the code but won't return
any value explicitly.
o Here's an example to illustrate the usage of functions:
# Example of a function
def greet(name):
"""This function greets the person with the given name."""
print("Hello,", name)
# Calling the function
greet("Alice")
greet("Bob")
In this code, we have a function named `greet()` that takes an argument `name`. The function simply prints a
greeting message along with the given name. The docstring enclosed in triple quotes provides a brief
description of what the function does.The function is called twice with different names as arguments:
"Alice" and "Bob". Each time the function is called, it executes the code within its block, printing the
corresponding greeting message.
o Practice problem:
Write a Python function that calculates and returns the area of a rectangle. The function should
accept the width and height of the rectangle as arguments, perform the calculation, and return the
area.
o Here's a possible solution:
# Practice problem: Area of a rectangle
def calculate_area(width, height):
"""This function calculates the area of a rectangle."""
area = width * height
return area
# Calling the function
width = float(input("Enter the width of the rectangle: "))
height = float(input("Enter the height of the rectangle: "))
result = calculate_area(width, height)
print("The area of the rectangle is:", result)
In this code, the `calculate_area()` function accepts two arguments: `width` and `height`. Inside the
function, the area is calculated by multiplying the width and height. The result is returned using the `return`
statement. The function is called after prompting the user to enter the width and height of the rectangle. The
returned area is stored in the `result` variable and displayed using the `print()` function.
Data structures
In Python, data structures are used to store, organize, and manipulate collections of data. They provide a
way to efficiently store and retrieve data and perform various operations on it. Python offers several built-in
data structures, each with its own characteristics and use cases. Here's a brief explanation of some
commonly used data structures in Python:
1. Lists:
 Lists are ordered collections of items enclosed in square brackets ([]).
 They can store elements of different data types and allow duplicates.
 Lists are mutable, meaning you can modify the elements after creation.
 Elements in a list can be accessed using indexing and various list methods are available for
manipulation.
2. Arrays:
 In Python, arrays are a type of data structure that allows you to store and manipulate a fixed-size
collection of elements of the same data type.
 Arrays provide a more memory-efficient way to store and access elements compared to other
dynamic data structures like lists.
 Key points about arrays in Python:
a. Importing the Array Module:
 To use arrays in Python, you need to import the `array` module from the standard library.
b. Array Creation:
 Arrays are created using the `array` function from the `array` module.
 You need to specify the data type code representing the type of elements the array will hold.
 Example: `import array` and `my_array = array.array('i', [1, 2, 3, 4, 5])`
c. Accessing Elements:
 Elements in an array can be accessed using zero-based indexing, similar to lists.
 Example: `element = my_array[0]` (accesses the first element)
d. Modifying Elements:
 Arrays are mutable, meaning you can change the values of individual elements.
 Example: `my_array[1] = 10` (modifies the second element to 10)
e. Array Methods:
 The `array` module provides various methods to perform common operations on arrays, such
as adding elements, removing elements, and more.
 Example: `my_array.append(6)` (adds an element to the end of the array)
 Practice problem:
Write a Python program that takes a list of numbers as input and creates an array with the same
elements. Then, prompt the user to enter a number and check if it exists in the array. Display an
appropriate message.
 Here's an example solution:
import array
# Creating an array from a list of numbers
numbers = [1, 2, 3, 4, 5]
my_array = array.array('i', numbers)
# Prompting the user to enter a number
target = int(input("Enter a number to check: "))

# Checking if the number exists in the array


if target in my_array:
print("The number exists in the array.")
else:
print("The number does not exist in the array.")

In this code, we start by creating an array `my_array` using the `array` function from the `array` module.
The elements of the array are initialized from a list of numbers.Then, the user is prompted to enter a number
to check. The input is stored in the `target` variable. We use the `in` operator to check if the `target` exists
in the array, and an appropriate message is displayed based on the result.
3. Tuples:
 Tuples are similar to lists but are immutable, meaning their elements cannot be changed after
creation.
 They are defined using parentheses ().
 Tuples are typically used to store related pieces of data together and protect them from being
modified accidentally.

4. Dictionaries:
 Dictionaries are unordered collections of key-value pairs enclosed in curly braces ({key: value}).
 They are used to store and retrieve data based on unique keys instead of numerical indices.
 Dictionaries are mutable, and values can be modified, added, or deleted based on their keys.
 They are useful for representing structured data and mapping relationships between different
pieces of information.

5. Sets:
 Sets are unordered collections of unique elements enclosed in curly braces ({element1, element2}).
 They can be used to perform mathematical set operations like union, intersection, and difference.
 Sets do not allow duplicates, and their elements are not accessed using indices.
 Sets are mutable, and elements can be added or removed.

6. Strings:
 While not strictly a data structure, strings are sequences of characters and can be treated as a
collection of individual elements.
 Strings have their own set of methods for manipulation, searching, and formatting.
Practice problems
Easy-Level Problems:
1. Problem: Write a Python function that takes a string as input and prints each character of the string on a
separate line.
2. Problem: Write a Python program that prompts the user to enter a positive integer and checks if it is a
prime number. Display an appropriate message.
3. Problem: Write a Python program that calculates and displays the sum of all odd numbers from 1 to 100.
Intermediate-Level Problems:
1. Problem: Write a Python function that takes a list of numbers as input and returns a new list containing
only the even numbers from the original list.
2. Problem: Write a Python program that prompts the user to enter a sentence and counts the occurrences of
each word in the sentence. Display the word count for each unique word.
3. Problem: Write a Python program that generates and prints the Fibonacci sequence up to a given number.
Prompt the user to enter the maximum number.
Hard-Level Problems:
1. Problem: Write a Python function that takes a list of integers as input and returns the two numbers with
the smallest absolute difference. If multiple pairs have the same smallest difference, return any one of them.
2. Problem: Write a Python program that prompts the user to enter a sentence and finds the longest word in
the sentence. If multiple words have the same length, return any one of them.
3. Problem: Write a Python program that simulates the game of Tic-Tac-Toe between two players. Prompt
the players for their moves and determine the winner or if the game ends in a draw.

You might also like