Python Unit 1 notes
Python Unit 1 notes
Python programming has several notable features that make it a popular choice among developers. Here are
some key features:
1. Easy to use: python is designed to be easy to read and write, making it a programmer-friendly
language suitable for beginners.
2. Expressive language: python allows developers to write code that is clear and understandable,
enhancing readability and maintainability.
3. Interpreted language: python is an interpreted language, meaning that the code is executed line by
line. This feature simplifies debugging and is particularly beneficial for beginners.
4. Cross-platform language: python can run on various platforms, including windows, linux, unix, and
macintosh, making it a portable language.
5. Free and open source: python is freely available, and its source code can be accessed and modified,
which encourages community contributions and collaboration.
6. Object-oriented language: python supports object-oriented programming, allowing the use of classes
and objects, which helps in organizing code and promoting reuse.
7. Extensible: python can be extended with other programming languages like c and c++, allowing for
the integration of existing code and libraries.
8. Large standard library: python comes with a vast standard library that provides many modules and
functions, facilitating various programming tasks without the need for additional installations.
9. Gui programming: python supports the development of graphical user interfaces (guis), enabling the
creation of user-friendly applications.
10. Integrated: python can be easily integrated with other languages such as c, c++, and java, allowing for
versatile application development.
These features contribute to python's popularity and effectiveness in various programming domains, from web
development to data science.
In Python, loops are used to execute a block of code repeatedly based on a condition or over a sequence. The
two primary types of loops are the for loop and the while loop.
For Loop
A for loop iterates over a given sequence (like a list, tuple, or string) or a range of numbers. It is commonly
used when the number of iterations is known beforehand.
for i in range(5):
print(i)
Output:
In this example, the for loop iterates over the range of numbers from 0 to 4 and prints each number.
While Loop
A while loop continues to execute as long as a specified boolean condition is true. It is useful when the number
of iterations is not known in advance and depends on a condition.
count = 0
print(count)
Output:
In this example, the while loop continues to execute as long as count is less than 5. The count variable is
incremented by 1 in each iteration, ensuring that the loop eventually terminates.
In python, operators are special symbols that perform operations on variables and values. Here are the
different types of operators along with suitable examples:
1. Arithmetic operators
• A = 10
• B=5
• Print(a + b) # output: 15
• Print(a - b) # output: 5
• Print(a * b) # output: 50
• Floor division (//): divides and returns the largest integer less than or equal to the result.
• Print(a // b) # output: 2
• Print(a % b) # output: 0
• Exponentiation (**): raises the first operand to the power of the second.
2. Comparison operators
These operators compare two values and return a boolean result (true or false).
• Greater than (>): checks if the left operand is greater than the right.
• Less than (<): checks if the left operand is less than the right.
• Greater than or equal to (>=): checks if the left operand is greater than or equal to the right.
• Less than or equal to (<=): checks if the left operand is less than or equal to the right.
3. Logical operators
4. Assignment operators
• Simple assignment (=): assigns the value on the right to the variable on the left.
• C = a + b # c is now 15
• Add and assign (+=): adds the right operand to the left operand and assigns the result to the left
operand.
• C += 5 # c is now 20
• Subtract and assign (-=): subtracts the right operand from the left operand and assigns the result to
the left operand.
• C -= 5 # c is now 15
5. Bitwise operators
• Print(a | b) # output: 15
• Print(a ^ b) # output: 15
In python, errors can occur during the execution of a program, and they can be categorized into three main
types: syntax errors, runtime errors, and semantic errors. Here’s a detailed explanation of each type along with
examples:
1. Syntax errors
Syntax errors occur when the python parser encounters code that does not conform to the language's syntax
rules. These errors are detected at compile time, and the program will not run until they are fixed.
Example:
In this example, the closing parenthesis is missing, which leads to a syntax error.
2. Runtime errors
Runtime errors occur during the execution of a program, after it has successfully passed the syntax check.
These errors can happen due to various reasons, such as invalid operations, accessing non-existent variables, or
dividing by zero.
Example:
# division by zero
A = 10
B=0
In this case, the program attempts to divide by zero, which is not allowed, resulting in a runtime error.
3. Semantic errors
Semantic errors occur when the code is syntactically correct but does not produce the expected result. These
errors are often logical errors in the program, where the code runs without crashing but produces incorrect
output.
Example:
# incorrect logic
Def calculate_area(radius):
Area = calculate_area(5)
# if the expected area was calculated using a different formula, it would be a semantic error.
In this example, the formula used is correct for calculating the area of a circle, but if the intention was to
calculate the circumference instead, it would be a semantic error.
Conditional statements in Python allow you to execute certain blocks of code based on specific
conditions. The primary conditional statements are if, if-elif, and nested if statements. Here’s an
explanation of each, along with examples:
1. if Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
Example:
age = 18
In this example, the program checks if the variable age is greater than or equal to 18. If true, it prints
"You are eligible to vote."
2. if-elif Statement
The if-elif statement allows you to check multiple conditions. If the first condition is false, it checks
the next condition, and so on. You can have multiple elif statements.
Example:
marks = 85
print("Grade: A")
print("Grade: B")
print("Grade: C")
else:
print("Grade: D")
In this example, the program checks the value of marks. It prints the corresponding grade based on
the conditions. Since marks is 85, it will output "Grade: B."
3. Nested if Statement
A nested if statement is an if statement inside another if statement. This allows for more complex
conditions to be evaluated.
Example:
num = 10
if num > 0:
if num % 2 == 0:
else:
else:
print("The number is negative or zero.")
In this example, the outer if checks if num is positive. If true, it then checks if num is even or odd using
a nested if. The output will be:
The number is positive.
Control statements in Python are used to control the flow of execution of the program based on certain
conditions. They allow you to make decisions, repeat actions, and manage the flow of your program. The main
types of control statements in Python include conditional statements, loops, and control flow statements
like break, continue, and pass. Here’s an explanation of each type with examples:
1. Conditional Statements
Conditional statements allow you to execute certain blocks of code based on specific conditions. The primary
conditional statements are if, if-elif, and else.
Example:
Number = 10
If number > 0:
Print("The number is positive.")
Elif number < 0:
Print("The number is negative.")
Else:
Print("The number is zero.")
In this example, the program checks if the number is positive, negative, or zero and prints the corresponding
message.
2. Loops
Loops are used to execute a block of code repeatedly. The two main types of loops in Python are for loops
and while loops.
A. For Loop
The for loop iterates over a sequence (like a list, tuple, or string).
Example:
Fruits = ["apple", "banana", "cherry"]
The range() function in Python is a built-in function that generates a sequence of numbers. It is commonly used
in loops, particularly for loops, to iterate over a sequence of numbers. The range() function can take one, two,
or three arguments, allowing for flexibility in the generated sequence.
Syntax
Start: (optional) The starting value of the sequence (inclusive). Defaults to 0 if not provided.
Stop: The end value of the sequence (exclusive). The sequence will stop before this value.
Step: (optional) The difference between each number in the sequence. Defaults to 1 if not provided.
Examples
When only one argument is provided, it generates numbers from 0 up to (but not including) that number.
Example:
For i in range(5):
Print(i)
Output:
0
1
When two arguments are provided, the first argument is the starting value, and the second is the stopping
value.
Example:
Print(i)
Output:
When three arguments are provided, the first is the starting value, the second is the stopping value, and the
third is the step value.
Example:
Print(i)
Output:
In this case, range(1, 10, 2) generates numbers starting from 1 up to (but not including) 10, incrementing by 2
each time.
You can also use range() to generate a sequence in reverse by providing a negative step.
Example:
For i in range(5, 0, -1):
Print(i)
Output: