0% found this document useful (0 votes)
2 views13 pages

Python

This document serves as a comprehensive Python tutorial covering fundamental programming concepts such as variables, data types, conditional statements, loops, and functions. It provides examples and explanations for each topic, including how to work with classes, error handling, and nested loops. Additionally, it discusses practical applications like number identification and file input/output operations.

Uploaded by

joysri1130
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Python

This document serves as a comprehensive Python tutorial covering fundamental programming concepts such as variables, data types, conditional statements, loops, and functions. It provides examples and explanations for each topic, including how to work with classes, error handling, and nested loops. Additionally, it discusses practical applications like number identification and file input/output operations.

Uploaded by

joysri1130
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python tutorial part 1

Understanding Variables

We'll start by talking about variables. In programming, a variable is a named location used to
store data in memory. It is called a variable because its value can vary throughout the execution
of a program. Variables must be given unique names, called identifiers. In Python, variable
names are case sensitive and cannot start with a number. They can contain letters, numbers,
and underscores.

For example, let's say we want to store the number of apples I have in a variable named apples.
We can do this with the following code:

apples = 5

Now, apples is a variable that stores the value 5. We can use this variable in calculations, such as
adding more apples:

apples = apples + 3

print(apples)

This will output 8, because we added 3 to the value stored in the apples variable.

Next, let's talk about data types. A data type is an attribute that tells what kind of data a
particular variable can hold. There are several basic data types in Python, including int, float, str,
and bool.

int is short for integer, which is a whole number, positive or negative, without decimals. For
example:

num_apples = 10

num_oranges = -5

float is short for floating point number, which is a number with decimals. For example:

price_per_apple = 0.5

price_per_orange = 0.35

str is short for string, which is a sequence of characters surrounded by quotes. Strings can be
enclosed in either single quotes or double quotes. For example:

name = "Alice"

greeting = 'Hello, world!'


bool is short for boolean, which is a logical value that can be either True or False. For example:

is_hungry = True

is_tired = False

We can also use data types to perform type conversions, such as converting a string to an
integer:

age_str = "25"

age_int = int(age_str)

print(type(age_int))

This will output <class 'int'>, because we converted the string "25" to an integer using the int()
function.

In conclusion, variables and data types are fundamental concepts in programming that allow us
to store and manipulate data. By understanding how to use variables and data types in Python,
we can create more complex and powerful programs.

That's it for this chapter on Variables and Data Types! I hope this summary has been helpful in
explaining these concepts and providing examples from the video. Thank you for reading.

Conditional Statements and Boolean


Values in Code
 Concept: Allows the program to make decisions based on certain conditions.
 ** Keywords:** if, elif, else
 Boolean Values: True or False

Variables and Data Types


 Variables: Used to store data and values.
 Data Types: Integers, Floats, Strings, Lists, Tuples, Dictionaries.

Working with Classes and Objects


 Classes: User-defined data types.
 Objects: Instance of a class.

Loops in Programming
 For Loops: Iterates over a sequence or collection.
 While Loops: Repeats as long as a condition is true.

List Operations
 Creating Lists: Using square brackets [].
 Indexing Lists: Accessing elements using their index.
 Modifying Lists: Changing the value of elements.

Functions and Modules


 Functions: Re-usable blocks of code that perform a specific task.
 Modules: Re-usable libraries of code.

Error Handling
 Exception Handling: Managing errors and exceptions in code.
 Keywords: try, except, finally.

Private Variables and Logical Errors


 Private Variables: Accessible only within the class they are defined.
 Logical Errors: Syntax is correct, but the output is not as expected.

Inheritance and Polymorphism


 Inheritance: One class inherits the properties and methods of another.
 Polymorphism: Multiple forms of a function or method.

Nested Loops
 Concept: A loop inside another loop.
 Implementation: Used to repeat a block of code for every element in a sequence.

Factorial Calculation
 Formula: $n! = n * (n-1) * (n-2) * ... * 1$
 Implementation: Using loops or recursion
Fundamentals of Loops in Python
For Loops
 Initialization of counter variable
 Condition check for continuation of loop
 Increment/decrement of counter variable

While Loops
 Initialization of condition variable
 Evaluation of condition in while statement
 Updation of condition variable

List Operations
 Creating lists using square brackets
 Accessing list elements using indexing
 Modifying list elements

Nested Loops
 Loop inside a loop
 Outer loop controls the number of times inner loop is executed

Factorial Calculation
 Implementing the formula using loops

Conditional Statements
 Checking for a given condition
 Executing a block of code based on the condition

Error Handling
 Detecting various errors in the program
 Handling the errors using try and except blocks

Understanding Variables
 Storing values in variables
 Understanding data types of variables
 Rules for naming variables in Python

Functions and Modules


 Defining a function
 Calling a function
 Importing modules in Python programs

Working with Numbers: Even, Odd, and


Prime Number Identification (Python
Classes and Objects)
Understanding Variables and Data Types in
Programming
Before diving into number identification, it's important to understand variables and data types in
programming, including:

 Scalar data types (int, float, bool, str)


 Compound data types (list, tuple, dictionary, set)
 Assigning values to variables

Even, Odd, and Prime Number Identification


Even Numbers

 Even numbers can be identified by checking if the remainder of the number divided by 2 is 0.

if num % 2 == 0:
print(f"{num} is an even number.")

Odd Numbers

 Odd numbers can be identified by checking if the remainder of the number divided by 2 is
not 0.

if num % 2 != 0:
print(f"{num} is an odd number.")

Prime Numbers

 Prime numbers are numbers greater than 1 that have only 2 factors: 1 and itself.
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True

if is_prime(num):
print(f"{num} is a prime number.")

File Input and Output Operations

 Useful for reading and writing data to external files.

# Reading from a file


with open("[Link]", "r") as file:
numbers = [Link]()
for num in numbers:
num = int(num)
# Even, odd, or prime number check here

# Writing to a file
with open("[Link]", "w") as file:
for num in numbers:
# Even, odd, or prime number result here
[Link](f"{result}\n")

Loops: For and While Loops

 For loops iterate through a sequence of items.

for num in range(1, 101):


# Even, odd, or prime number check here

 While loops repeat a block of code while a condition is true.

num = 1
while num <= 100:
if num % 2 == 0:
print(f"{num} is an even number.")
num += 1

List Operations

 Lists are ordered collections that can hold multiple items.

# Creating a list
numbers = [1, 2, 3, 4, 5]
# Indexing a list
even_numbers = [num for num in numbers if num % 2 == 0]

# Modifying a list
for i in range(len(numbers)):
if numbers[i] % 2 != 0:
numbers[i] = 0

Conditional Statements and Boolean Values

 Control the flow of a program based on conditions.

if num % 2 == 0:
print(f"{num} is an even number.")
elif num % 2 != 0 and is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is an odd number.")

Nested Loops

 Loops can be nested within other loops.

for i in range(1, 10):


for j in range(1, 10):
if i * j == num:
print(f"{num} can be made by multiplying {i} and {j}.")

Factorial Calculation

 Calculate the factorial of a number using a for loop or recursive function.

def factorial(num):
result = 1
for i in range(1, num + 1):
result *= i
return result

print(factorial(5)) # 120

List Operations in Python


Creating Lists
 Use square brackets [] to create a new list
 Elements are separated by commas ,
 Lists can contain items of different data types

Example:

my_list = ["apple", 1, [2, 3, 4]]

Indexing Lists
 Access elements in a list using their index
 Indexing starts from 0
 Negative indexing starts from -1 (last element)

Example:

my_list = ["apple", "banana", "orange"]


print(my_list[1]) # prints: banana
print(my_list[-1]) # prints: orange

Modifying Lists
 Change the value of an element by accessing it using its index
 Add elements to a list using the append() method
 Insert elements to a list using the insert() method
 Remove elements from a list using the remove()method
 Sort a list using the sort() method

Example:

my_list = ["apple", "banana", "orange"]


my_list[1] = "grape"
my_list.append("mango")
my_list.insert(2, "pineapple")
my_list.remove("banana")
my_list.sort()

Nested Loops in Python


Definition
A nested loop is a loop inside another loop. The outer loop iterates once for each iteration of the
inner loop.

Concept and Implementation


Here is an example of a nested loop in Python:
for i in range(3):
for j in range(4):
print(i, j)

This will output:

0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3

The outer loop iterates three times, and for each iteration of the outer loop, the inner loop iterates
four times.

It is important to be careful with indentation in nested loops, as it can affect the behavior of the code.

Use Cases
Nested loops can be useful in a variety of situations, such as:

 Iterating over a two-dimensional list


 Performing calculations on a grid of values
 Simulating multiple passes through a dataset

Example: Iterating over a two-dimensional list


Given a two-dimensional list, you can use nested loops to iterate over each element:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


for row in matrix:
for item in row:
print(item)

This will output:

1
2
3
4
5
6
7
8
9

Note:

 Nested loops are not limited to two levels deep, they can be nested as many levels as
needed
 Be aware of the complexity of nested loops, it can increase the time and space requirement
rapidly. *

FAQs
1. What is a nested loop?
o A nested loop is a loop inside another loop. The outer loop iterates once for each
iteration of the inner loop.
2. How do you implement a nested loop in Python?
o You can implement a nested loop in Python by placing one loop inside another and
indenting the inner loop.
3. What are some use cases for nested loops?
o Some use cases for nested loops include iterating over a two-dimensional list,
performing calculations on a grid of values, and simulating multiple passes through a
dataset.

Further reading
 Python documentation on loops
 W3Schools tutorial on loops
 [Real Python's tutorial on loops]([Link] loops-in-python/)
 [Link]'s tutorial on loops

Understanding Nested Loops in Python


Definition
Nested loops are loops within loops. An outer loop controls the execution of an inner loop, which
repeats a set of instructions.

Concept and Implementation


Here is an example of a nested loop:

for i in range(3):
for j in range(4):
print(i, j)

This will output:

0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3

The outer loop iterates three times, and for each iteration of the outer loop, the inner loop iterates
four times. The inner loop is executed completely during each iteration of the outer loop.

It is important to be careful with indentation in nested loops, as it can affect the behavior of the code.
The block of code inside the inner loop should be indented to show that it is nested within the outer
loop.

Use Cases
Nested loops can be useful in a variety of situations, such as:

 Iterating over a two-dimensional list


 Performing calculations on a grid of values
 Simulating multiple passes through a dataset

Example: Iterating over a two-dimensional list


Given a two-dimensional list, you can use nested loops to iterate over each element:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


for row in matrix:
for item in row:
print(item)

This will output:

1
2
3
4
5
6
7
8
9

Complexity
It is important to be aware of the complexity of nested loops, as it can increase the time and space
requirement rapidly. For example, if the inner loop executes N times for each iteration of the outer
loop, the nested loops will execute a total of N^2 times.

Common Mistakes
 Not indenting the inner loop correctly
 Forgetting to reset the counter variable of the inner loop at the beginning of the outer loop

Note:

 Nested loops are not limited to two levels deep, they can be nested as many levels as
needed
 Be aware of the complexity of nested loops, it can increase the time and space requirement
rapidly.

FAQs
1. What is a nested loop?
o A nested loop is a loop within another loop. An outer loop controls the execution of
an inner loop, which repeats a set of instructions.
2. How do you implement a nested loop in Python?
o You can implement a nested loop in Python by placing one loop inside another and
indenting the inner loop.
3. What are some use cases for nested loops?
o Some use cases for nested loops include iterating over a two-dimensional list,
performing calculations on a grid of values, and simulating multiple passes through a
dataset.

Further reading
 Python documentation on loops
 W3Schools tutorial on loops
 [Real Python's tutorial on loops]([Link] loops-in-python/)
 [Link]'s tutorial on loops

You might also like