0% found this document useful (0 votes)
15 views

Python Unit 1 notes

Uploaded by

memowe8980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Unit 1 notes

Uploaded by

memowe8980
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python Unit 1

1. EXPLAIN FEATURES OF PYTHON PROGRAMMING

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.

2. EXPLAIN WHILE LOOP, FOR LOOP WITH EXAMPLE

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.

Example of a For Loop:

# Example: Printing numbers from 0 to 4

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.

Example of a While Loop:

# Example: Printing numbers from 0 to 4

count = 0

while count < 5:

print(count)

count += 1 # Increment count by 1

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.

3. Explain different types of operators with suitable example.

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

These operators are used to perform basic mathematical operations.

• Addition (+): adds two operands.

• A = 10

• B=5
• Print(a + b) # output: 15

• Subtraction (-): subtracts the second operand from the first.

• Print(a - b) # output: 5

• Multiplication (*): multiplies two operands.

• Print(a * b) # output: 50

• Division (/): divides the first operand by the second.

• Print(a / b) # output: 2.0

• Floor division (//): divides and returns the largest integer less than or equal to the result.

• Print(a // b) # output: 2

• Modulus (%): returns the remainder of the division.

• Print(a % b) # output: 0

• Exponentiation (**): raises the first operand to the power of the second.

• Print(a ** b) # output: 100000

2. Comparison operators

These operators compare two values and return a boolean result (true or false).

• Equal to (==): checks if two operands are equal.

• Print(a == b) # output: false

• Not equal to (!=): checks if two operands are not equal.

• Print(a != b) # output: true

• Greater than (>): checks if the left operand is greater than the right.

• Print(a > b) # output: true

• Less than (<): checks if the left operand is less than the right.

• Print(a < b) # output: false

• Greater than or equal to (>=): checks if the left operand is greater than or equal to the right.

• Print(a >= b) # output: true

• Less than or equal to (<=): checks if the left operand is less than or equal to the right.

• Print(a <= b) # output: false

3. Logical operators

These operators are used to combine conditional statements.

• Logical and (and): returns true if both operands are true.

• Print(a > 5 and b < 10) # output: true

• Logical or (or): returns true if at least one of the operands is true.


• Print(a > 15 or b < 10) # output: true

• Logical not (not): reverses the logical state of its operand.

• Print(not(a > 5)) # output: false

4. Assignment operators

These operators are used to assign values to variables.

• 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

These operators perform operations on binary representations of integers.

• Bitwise and (&): performs a bitwise and operation.

• Print(a & b) # output: 0

• Bitwise or (|): performs a bitwise or operation.

• Print(a | b) # output: 15

• Bitwise xor (^): performs a bitwise xor operation.

• Print(a ^ b) # output: 15

• Bitwise not (~): inverts the bits.

• Print(~a) # output: -11

• Left shift (<<): shifts bits to the left.

• Print(a << 1) # output: 20

• Right shift (>>): shifts bits to the right.

• Print(a >> 1) # output: 5

4. EXPLAIN DIFFERENT TYPES OF ERRORS IN PYTHON WITH EXAMPLE.

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:

# missing a closing parenthesis

Print("hello, world!" # syntaxerror: unexpected eof while parsing

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

Print(a / b) # zerodivisionerror: division by zero

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):

return 3.14 * radius * radius

Area = calculate_area(5)

Print("area of the circle:", area) # output: area of the circle: 78.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.

5. Explain conditional statements( if, if-elif,nested if) with example.

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

if age >= 18:

print("You are eligible to vote.")

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

if marks >= 90:

print("Grade: A")

elif marks >= 80:

print("Grade: B")

elif marks >= 70:

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:

print("The number is positive.")

if num % 2 == 0:

print("The number is even.")

else:

print("The number is odd.")

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.

The number is even.

6. Explain Control statements with examples.

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"]

For fruit in fruits:


Print(fruit)
This loop will print each fruit in the list.
B. While Loop
The while loop continues to execute as long as a specified condition is true.
Example:
Count = 0

While count < 5:


Print(count)
Count += 1
This loop will print numbers from 0 to 4.

3. Control Flow Statements


Control flow statements alter the flow of execution in loops.
A. Break
The break statement is used to exit a loop prematurely.
Example:
For num in range(10):
If num == 5:
Break
Print(num)
This loop will print numbers from 0 to 4 and then exit when num equals 5.
B. Continue
The continue statement skips the current iteration and moves to the next iteration of the loop.
Example:
For num in range(5):
If num == 2:
Continue
Print(num)
This loop will print numbers 0, 1, 3, and 4, skipping the number 2.
C. Pass
The pass statement is a null operation; it is used when a statement is syntactically required but you do not
want any command or code to execute.
Example:
For num in range(5):
If num == 2:
Pass # Do nothing
Print(num)
This loop will print all numbers from 0 to 4, and when num is 2, it will do nothing but continue to the next
iteration.

7. Explain the use of range function with example.

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

The syntax of the range() function is as follows:

Range(start, stop, step)

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

1. Using range() with One Argument

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

In this example, range(5) generates numbers from 0 to 4.

2. Using range() with Two Arguments

When two arguments are provided, the first argument is the starting value, and the second is the stopping
value.

Example:

For i in range(2, 6):

Print(i)

Output:

Here, range(2, 6) generates numbers starting from 2 up to (but not including) 6.

3. Using range() with Three Arguments

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:

For i in range(1, 10, 2):

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.

4. Using range() in Reverse

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:

Here, range(5, 0, -1) generates numbers starting from 5 down to 1.

You might also like