
Python Programming – Course Overview
Evolution of Programming Languages:
In the past 50 years, programming languages have changed a lot. They started with FORTRAN and now Python is the most popular. Programming is like dancing and singing, it gets better with practice and dedication. People need to keep learning and gaining practical experience to improve their skills. Python is a widely used programming language nowadays, especially in the field of Artificial Intelligence. Our course focuses on teaching Python in a practical way. We emphasize on real-life application and provide comprehensive examples to explain important concepts and syntax. In contemporary times, Python stands at the forefront of programming languages, serving as a versatile tool across various domains, notably in the realm of Artificial Intelligence (AI).
Our course adopts a pragmatic approach to imparting proficiency in Python, emphasizing practicality, depth, and application across diverse fields.
Practical Learning Approach
Each facet of Python, from fundamental concepts to intricate syntax, is meticulously elucidated through comprehensive examples and practical applications. The course is structured to provide an in-depth understanding of Python's core elements:
Introduction and Basics of Python
Providing a foundational understanding of Python's syntax, data types, and fundamental principles to familiarize learners with the language's essentials.
Assignment and I/O Statements
Delving into assignment statements and input/output functions, enabling learners to comprehend data manipulation and interaction in Python.
Math and Datetime Libraries
Exploring the math library for mathematical functions and the datetime library for date and time manipulations, essential for data processing and computation.
Control and Loop Structures
Understanding control structures such as 'if' statements and loop structures including 'for' and 'while' loops for decision-making and iterative operations.
Data Structures and String Manipulation
Navigating through data structures like lists, tuples, sets, and delving into string manipulation for effective text processing.
User-Defined Functions and File Manipulation
Unveiling the creation of user-defined functions and exploring file manipulation for efficient data handling and storage.
Python Image Library (PIL)
Harnessing the capabilities of PIL for image processing, including loading images, performing operations like sharpening, blurring, and drawing shapes.
Introducing Essential Libraries
The course introduces pivotal Python libraries—Math, Pandas, Matplotlib, NumPy, and PIL—crucial for diverse applications:
Math Library
Covering essential functions spanning constants, numerical, trigonometric, logarithmic, distance, permutation, combination, and LCM/GCD operations for mathematical computations.
Pandas
Employing Pandas Dataframe to demonstrate database operations, elucidating data
manipulation techniques using a simplified database scenario.
Matplotlib
Showcasing Matplotlib's prowess in visual representation with line graphs, bar charts, scatter plots, horizontal bars, and pie charts, facilitating data visualization.
Practical Application and Tutorial Videos
Real-world examples accompany each concept, enabling seamless comprehension.
Furthermore, tutorial videos delve into university examination problem-solving, providing comprehensive insights into tackling global academic challenges.
In essence, this course champions a hands-on, practical approach to Python, empowering learners to grasp the language's intricacies and leverage its diverse libraries for practical applications across academic, professional, and AI domains.
In this lecture, we introduce the concept of Programming Language and describe the historical perspective. We introduce Python Language.
In Python, the comment statements play a major role to increase readability. In this lecture, we introduce the comment. statements.
In. programming, effective use of constants and variables is the key. In this lecture, we introduce the concept of constants and variables.
In this lecture we teach the fundamental data types in Python.
We introduce the assignment statements of Python.
University Question
Swap two variables
Swap without a third variable
Input Statements. We teach how we can read data using input statement.
Input statements in Python
Input statements in Python are essential for interacting with users and receiving input during
program execution. Let's delve into the concept, syntax, usage, and examples to illustrate
their functionality.
Exploring Python Input Statements
Definition of Input Statements
Input statements in Python prompt users to provide data or information during program
execution. They facilitate user interaction, allowing dynamic input that influences program
behavior.
Syntax of Input Statements
In Python, the input() function is used to obtain user input. It displays a prompt message
(if provided) and waits for the user to enter data through the keyboard.
variable_name = input("Prompt message ")
We introduce the output statement print.
Section 3.2 Python's output statements
Python's output statements are crucial for displaying information to users during program
execution. Let's explore their significance, syntax, usage, and provide examples to illustrate
how output statements work in Python.
Output statements in Python are used to display information or results from the program to
the user, typically on the console or terminal.
We introduce the constants e and pi in math library.
We explain the number functions in Math library.
1. Floor and CEiling
Mod function
absolute value
the square root of a number
Permutation and Combination
LCM
GCD
Modulo
University questions on some key mathematical functions
Lab Exercise: Read numbers x and n, compute x power n and print.
We introduce the library datetime. In this library we have the date class. We introduce the date class and its attributes, year, month and date.
In this lecture, we introduce the time class and its attributes, hour, month, second, and microseconds.
We introduce the datetime class.
We introduce the timedelta class.
We write program for a couple simple problems.
Employee Management System
Retirement Date and benefits
The date of birth and the date of joining in service are given. Find the date of retirement and Gratuity amount to be paid.
Rule 1: Retirement age 60 years
Rule 2: If the service is less than 5 years, no gratuity. If the service is more than 5, say n, Gratuity is 0.58*n times the the last month salary.
Rule 3: If an employee has more than 34 years of experience, the service is considered as 34 in calculating Gratuity. This means the service is capped at 34.
Tutorial
Solutions for Problems from University Examination Question Papers
DateTime Library
Program to calculate income tax as per given rules.
Loop Structures
In any work there is a repetition of some smaller sub-works. For example, consider the work of unloading 10 boxes from the lorry and placing them in 10 different rooms.
First box has to be placed in Room Number 1.
Second box has to be placed in Room number 2.
Third box has to be placed in Room number 3.
In general, the box number k must be placed in room number k. If there are 10 boxes to be unloaded from the lorry and placed in the 10 rooms, we can describe this work as follows:
Do the following, For k values from k =0 to 9
1. Unload Box number k
2. Move Box k to Room no k
3. place the box k in Room no k
Here the work is repeated 10 times as follows:
Iteration 1 (Initial Iteration)
Initially, the value of k = 1. So, the Box no 1 is unloaded, moved to room no 1 placed in room number 1.
Iteration 2
Now. the value of k becomes 2. Now Box no 2 is unloaded, moved to Room no 2 and kept at room number 2.
This is repeated for all the 10 boxes.
Iteration 10 (Last Iteration)
The value of k =10. So, Box number 10 is unloaded, moved to Room 10 and kept in the room number 10.
Example
Consider a teacher who is valuing the answer scripts of all his 40 students. This work can be written as follows:
Do the following For r = 1 to 40
1. Pick up answer script of Student No r
2. Value the answer script of Student number r
3. Find the total mark for the student no r
Example
Consider a college in which 100 staff are working (both teaching and non-teaching). Consider the work of distributing one green book each to all the teaching staff and one blue book each to all the non-teaching staff.
This work can be expressed as follows
Do the following for i = 0 to 99
1. Meet Staff number i
2. If staff number I is a teaching staff
give the staff a green book
else
give the staff a blue book
3. Record the fact that book issued to Staff no i.
From the above examples we find that in completing any job, we may have to repeat certain smaller works. Repeating some works is usually called looping in programming. There are two loop structures available in Python language
1. FOR loop
2. WHILE loop
Loop Structures in Python
Loop structures in Python are essential constructs used to execute a block of code repeatedly until a certain condition is met.
When a particular set of activities are to be continued repeatedly then we use loop structures.
Understanding the different types of loops, their syntax, working principles, variations, and real-life applications can significantly enhance a programmer's ability to control repetitive tasks and iterate through data efficiently.
Types of Loops in Python:
1. for Loop:
The for loop iterates over a sequence of elements, such as lists, tuples, strings, or the sequence generated by the range() function.
Syntax:
for element in sequence:
# Code block to execute for each element
2. while Loop:
The while loop repeats a block of code as long as a specified condition remains True.
Syntax:
while condition:
# Code block to execute while the condition is True
Working Principle:
for Loop: It iterates through a sequence of elements, executing the code block for each element until the sequence ends.
while Loop: It repeatedly executes the code block as long as the specified condition remains True. It's essential to ensure the condition eventually becomes False to prevent infinite looping.
for Loop Example:
for i in range(10)
print(i*i)
This loop iterates through i values 0 to 9. So, it prints,
0, 4, 9, ………81
while Loop Example:
count = 0
while count < 5:
print(5*5*5)
count += 1
Here, the loop prints the current value of count and increments it until count reaches 5.
Nested Loops:
Both for and while loops can be nested within each other to create more complex iterative structures.
Loop Control Statements:
break: Terminates the loop prematurely based on a certain condition.
continue: Skips the current iteration and proceeds to the next iteration.
pass: Acts as a placeholder, doing nothing when encountered.
Program Using continue
This program skips even numbers in a range using the continue statement.
# Skip even numbers in a range
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
The continue statement skips even numbers (i % 2 == 0) and continues with the next iteration.
Program : Using continue in Nested Loop
This program skips printing even numbers in a nested loop.
# Skipping even numbers in a nested loop
for i in range(3):
for j in range(1, 6):
if j % 2 == 0:
continue
print(i, j)
The continue statement skips even numbers (j % 2 == 0) in the inner loop and continues with the next iteration.
Program Using break
This program finds the first occurrence of a number divisible by 5 in a list.
# Finding the first number divisible by 5 in a list
for num in range(100,200):
if num % 7 == 0:
print(“First number divisible by 7”: num)
break
The break statement terminates the loop as soon as it encounters a number divisible by 5.
Program 3: Using pass
This program uses pass as a placeholder inside a loop.
# Looping through a range and doing nothing in specific cases
for i in range(1, 6):
if i == 3:
pass # Placeholder: Do nothing when i is 3
else:
print(i)
When i is equal to 3, the pass statement acts as a placeholder, doing nothing. In other cases, it prints the value of i.
These examples illustrate the functionality of continue, break, and pass statements within loops to control the flow of the program based on specific conditions or criteria.
Use Cases:
· Data Processing: Iterating through lists, tuples, or other data structures for analysis or modification.
· User Input Validation: Using loops to validate user inputs until specific criteria are met.
· Automation and Iterative Tasks: Automating repetitive tasks or processes.
Conclusion:
Loop structures are pivotal in Python programming for repetitive execution of code. Understanding their syntax, variations, and appropriate use cases empowers programmers to efficiently handle iterative tasks, process data, automate workflows, and manage control flow within applications. Mastering loop structures enables the creation of more efficient, scalable, and versatile programs in Python.
FOR loop
The simple format is as follows:
for rule :
statement 1
statement 2
…………..,..
…………….
statement n
Where the rule defines how to run each iteration of the loop
statement 1 to statement n are executed in every iteration.
For loop with range() function
The simple way of using a for-loop with the range() function. The general format of the range function is as follows:
range(start, end, increment)
This is a Python function call, which returns the running variable i, values ranging from integer start. The value is incremented by increment in every iteration and terminates when not less than end. The following are important points to remember:
1. In every iteration, the value is incremented with increment.
2. Note that the increment can be positive, or negative.
3. When the value is not less than end, the loop is terminated.
4. If increment is not specified, the default value of 1 is considered.
5. If the start value is not specified, the default start value of 0 is considered.
FOR Loop
The 'for' loop in Python is a fundamental control structure used for iterating over a sequence of elements or a range of values. It facilitates repetitive execution of a block of code for each item in the sequence.
Understanding its syntax, working principles, diverse applications, and variations can provide a comprehensive understanding of its functionality and versatility.
Syntax:
The syntax of the 'for' loop in Python is concise and intuitive:
for item in sequence:
# Code block to execute for each item
Here, 'item' represents the current element in the sequence being iterated, and the loop executes the code block for each 'item' in the 'sequence'.
Working Principle:
The 'for' loop iterates through each item in a sequence, executing the specified block of code for each iteration until it reaches the end of the sequence.
It's often used with lists, tuples, strings, dictionaries, sets, and ranges.
The loop automatically progresses through each item in the sequence, making it a powerful tool for iterating over collections of data.
Example : Using 'range()' Function
for i in range(5):
print(i)
Here:
The 'range()' function generates a sequence of numbers from 0 to 4.
The 'for' loop iterates through each value in the range and prints it.
Key Points:
Iteration Over Sequence: The 'for' loop iterates over each item in a sequence, performing operations or executing code for each item.
Iterating Numerically: 'range()' function is often used for numerical iteration, generating a sequence of numbers to loop over.
Element Extraction: In each iteration, the loop extracts an element from the sequence and executes the code block with that element.
Range Function
The range() function in Python is a versatile tool primarily utilized in conjunction with for loops to generate a sequence of numbers. It simplifies the process of iterating over a specific range or sequence of values. Understanding its syntax, functionalities, and variations can greatly enhance the efficiency and flexibility of for loops in Python programming.
Syntax:
The syntax of the range() function is straightforward:
range(start, stop, step)
start: The starting value of the sequence (optional; defaults to 0 if not specified).
stop: The end value of the sequence (exclusive).
step: The increment value between each number in the sequence (optional; defaults to 1 if not specified).
Basic Usage:
The range() function generates a sequence of numbers based on the provided parameters. It's often used in for loops to iterate over this sequence.
Example 1: Basic range() Usage
for i in range(5):
print(i)
This code:
Uses range(5) to generate a sequence from 0 to 4 (as 5 is exclusive).
The for loop iterates over this sequence, and for each iteration, it prints the current value of i.
Working Principle:
When the range() function is called with a single parameter (range(stop)), it generates a sequence starting from 0 up to, but not including, the specified stop value.
With two parameters (range(start, stop)), it generates a sequence starting from start and ending at stop (exclusive).
When all three parameters are used (range(start, stop, step)), it generates a sequence starting from start, incrementing by step, and stopping before reaching stop.
Additional Examples:
Using range() with Custom Start, Stop, and Step
for i in range(1, 10, 2):
print(i)
This code snippet uses range(1, 10, 2) to generate a sequence from 1 to 9 with a step of 2.
The for loop iterates over this sequence and prints each value. This prints: 1, 3, 5, 7, 9
Reverse Iteration with Negative Step
for i in range(10, 0, -1):
print(i)
Here, range(10, 0, -1) creates a sequence from 10 down to 1 (exclusive) with a step of -1.
The for loop iterates over this sequence in reverse order and prints each value.
10, 9, 8, 7, 6, 5, 4, 3, 2, 1
Use Cases:
· Numerical Iteration: Iterating over numerical ranges for calculations or operations.
· Customized Sequences: Generating custom sequences for specific needs, such as alternate or reverse sequences.
· Loop Control: Determining the range of iterations in loops based on specified conditions.
The range() function in Python serves as a powerful companion to the for loop, enabling the creation of custom sequences for iterative processes. Its flexibility in defining ranges of values allows for precise control over iterations, making it an indispensable tool for various programming tasks. Understanding the nuances of range() empowers programmers to efficiently handle iterative operations and control the flow of loops in Python.
The 'for' loop in Python is a versatile construct, allowing effortless iteration over a variety of data structures. Its simplicity and ability to handle sequences efficiently make it a cornerstone of programming in Python. Whether it's processing collections of data, performing numerical iterations, or traversing through dictionaries, the 'for' loop remains an indispensable tool for many programming tasks, offering a concise and powerful way to handle iterative operations. Mastering the 'for' loop empowers programmers to handle a wide range of scenarios efficiently and elegantly in Python.
Additional Examples:: Nested 'for' Loop
for i in range(5):
for j in range(3):
print("i = “, i, “j = “, j)
This example:
Utilizes nested 'for' loops to create a grid-like iteration.
The outer loop iterates over values from 0 to 4, while the inner loop iterates from 0 to 2 for each outer loop iteration.
Print will be as follows:
i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0
i = 1, j = 1
i = 1, j = 2
i = 2, j = 0
i = 2, j = 1
i = 2, j = 2
i = 3, j = 0
i = 3, j = 1
i = 3, j = 2
i = 4, j = 0
i = 4, j = 1
i = 4, j = 2
Prints the values of 'i' and 'j' for each iteration.
for i in range(10, 0, -2):
print(i)
Here:
'range(10, 0, -2)' generates a sequence from 10 down to 1 (exclusive) with a step of -2.
The 'for' loop iterates through this sequence in reverse and prints each value.
Conclusion:
The 'for' loop in Python, especially in conjunction with the 'range()' function, offers a concise and effective way to perform iterative operations over a range of values. Its versatility in handling numerical iterations and customization options with 'range()' makes it a cornerstone of programming in Python. Understanding and utilizing the 'for' loop and 'range()' function enables programmers to efficiently handle a diverse range of iterative tasks in Python.
Find the sum of the first n even numbers
University Question
Sum of Series 1
Sum of Series 2
Sum of Series 3
Sum of Series 4
Check if a given number is a Perfect number.
Check if a given number is an Armstrong number
Check if a given number is prime.
Fibonacci Series
Find Least Common Multiple LCM
Find Greatest Common Divisor GCD
Introduction to List, Tuple and Set
Length Function for List, Tuple and Set
Let us discuss more on Lists
Python Tuple.
Creating a Python list with For loop range() function Part 2
Creating a Python list with For loop range() funtion
Given a list, rotate the list right side k times
1. Find the sum of numbers in a list
2. Find the product of numbers in a list
3. Methods for remove items from list, change data items.
Sieve of Eratosthenes method to find the list of all prime numbers less than a given number n.
Create a list of random numbers and find the maximum number in the list
Tutorial
In this course, we teach Python Language using a practical approach. For every concept and syntax, elaborate details are given with a practical example. For every topic, we introduce the required. level of theory, explain the syntax, and illustrate using several example programs. The Tutorial Videos give coaching on Job Interview questions and solutions for problems from university examination papers. The following topics first with a sufficient number of practical examples:
1. Introduction and basics of to Python
2. Assignment Statements
3. Input Statement and Output Statements
4. Math Library functions
5. Datetime Library - date, time, datetime, timedelta
6. Control structures such as IF statement
7. Loop Structures such as For Loop and While Loop
8. List, Tuple, and Set
9. String Manipulation
10. User-Defined Functions
11. Data Files - File Manipulation
12. Drawing with Python Image Library (PIL)
13. Data Visualization using Matplotlib
14. Database Management using Python Pandas Data Frames
15. Playing Music with Python programs
We introduce some important Python Libraries such as Math, Pandas, Matplotlib, NumPy, and PIL.
Examples are chosen for each of the concepts so that the student understands the concept easily. In Math Library, we introduce all the important Functions such as Math constants, number functions, trigonometric functions, logarithmic functions, distance, permutation combination, and LCM / GCD. In introducing Pandas Dataframe, we have used a simple database and explained all the data frame methods and commands. By introducing PIL, we have illustrated the library capabilities such as load and display a picture, Image processing operations such as Sharp, Blur, and embodying. We have written programs for drawing rectangles and other shapes on a picture. We have used PIL.ImageFont library to write text on the image.
In Matplotlib, we have introduced Python programs for drawing line graphs, bar charts, scatter diagrams, horizontal bars, and pie chart.
We have added Tutorial videos for discussing the solutions for problems asked in university examinations globally.