🐍 Chapter 4: Programming in Python
SEE Computer Science 2083 - CDC New Curriculum. This chapter covers Python basics, user defined functions, libraries, graphics, file handling and data visualization.
📌 On This Page
4.1 Revision of Basics of Python
Introduction to Python
Python is a high-level, interpreted and general-purpose programming language. It is popular because of its simple syntax and easy readability.
Features of Python
- Simple and easy to learn.
- High level programming language.
- Interpreted language.
- Portable and platform independent.
- Supports object oriented programming.
- Provides large number of libraries.
Input and Output Statements
Input and Output statements are used to communicate with users. Input receives data and output displays results.
print() Statement
The print() function is used to display output on the screen.
print("Hello Python")
Output:
Hello Python
input() Function
The input() function is used to receive data from the user.
name = input("Enter your name: ")
print(name)
Output:
Enter your name: Ram Ram
Data Types in Python
A data type defines the type of value stored in a variable.
| Data Type | Description | Example |
|---|---|---|
| int | Whole numbers | 10 |
| float | Decimal numbers | 10.5 |
| str | Text/String | "Python" |
| bool | True or False | True |
Variables in Python
A variable is a named memory location used to store data.
Example:name = "Hari" age = 16 marks = 90
Rules for Naming Variables
- Must start with a letter or underscore.
- Cannot start with a number.
- No spaces are allowed.
- Python keywords cannot be used.
- Variable names are case sensitive.
Operators in Python
| Operator | Name |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus |
| ** | Power |
Expressions
An expression is a combination of variables, values and operators that produces a result.
Examples:10 + 5 a * b x > y
Conditional Statements
Conditional statements are used to make decisions according to conditions.
if Statement
age = 18
if age >= 18:
print("Eligible")
if-else Statement
age = 15
if age >= 18:
print("Adult")
else:
print("Child")
if-elif-else Statement
marks = 80
if marks >= 90:
print("A")
elif marks >= 60:
print("B")
else:
print("C")
Loops in Python
Loops are used to repeat a block of code multiple times.
for Loop
for i in range(5):
print(i)
while Loop
i = 1
while i <= 5:
print(i)
i = i + 1
- input() always returns string data.
- = is assignment operator.
- == is comparison operator.
- % gives remainder.
- Indentation is compulsory in Python.
4.2 User Defined Functions
What is a Function?
A function is a block of organized and reusable code that performs a specific task. Functions help divide large programs into smaller and manageable parts.
Advantages of Functions
- Code reusability.
- Reduces repetition of code.
- Makes programs easier to understand.
- Improves program organization.
- Makes debugging and maintenance easier.
Types of Python Functions
| Function Type | Description |
|---|---|
| Built-in Functions | Functions already available in Python. Examples: print(), input(), len(), sum() |
| User Defined Functions | Functions created by programmers according to their requirements. |
Creating a User Defined Function
User defined functions are created using the def keyword.
Syntax
def function_name(parameters):
statements
return value
Example: Function without Parameter
def welcome():
print("Welcome to Python")
welcome()
Output:
Welcome to Python
Function Call
A function call is the process of executing a function by writing its name followed by parentheses.
Example:
def greet():
print("Hello")
greet()
Parameters and Arguments
Parameters
Parameters are variables written inside the function definition. They receive values when the function is called.
Example:
def add(a,b):
print(a+b)
Here:
a and b are parameters
Arguments
Arguments are actual values passed to a function during function call.
Example:add(10,20)Here:
10 and 20 are arguments
Difference Between Parameter and Argument
| Parameter | Argument |
|---|---|
| Written in function definition | Written during function call |
| Receives values | Passes values |
| Example: a,b | Example: 10,20 |
Scope of Variables
Scope defines the area where a variable can be accessed in a program.
1. Local Scope
A variable created inside a function is called a local variable. It can only be used inside that function.
Example:
def show():
x = 10
print(x)
show()
2. Global Scope
A variable created outside a function is called a global variable. It can be accessed throughout the program.
Example:
x = 20
def display():
print(x)
display()
Return Statement
The return statement sends a value back from a function to the calling program.
Syntax:return valueExample:
def square(n):
return n*n
result = square(5)
print(result)
Output:
25
Types of Arguments
1. Positional Arguments
Arguments are passed in the same order as parameters.
Example:
def student(name,age):
print(name,age)
student("Ram",16)
2. Default Arguments
A default argument has a predefined value.
Example:
def greet(name="Student"):
print(name)
greet()
greet("Hari")
Output:
Student Hari
3. Keyword Arguments
In keyword arguments, values are passed using parameter names.
Example:
def info(name,age):
print(name,age)
info(age=16,name="Ram")
Functions Returning Values
A function that returns a result using return statement is called a non-void function.
Example:
def addition(a,b):
return a+b
print(addition(5,3))
Output:
8
Void Functions
A function that performs a task but does not return any value is called a void function.
Example:
def message():
print("Hello Python")
message()
Returning Multiple Values
Python allows a function to return multiple values separated by commas.
Example:
def calculate(a,b):
return a+b, a-b
x,y = calculate(10,5)
print(x)
print(y)
Output:
15 5
- Function is created using def keyword.
- Parameters are written in function definition.
- Arguments are passed during function call.
- return sends result back to caller.
- Local variables cannot be accessed outside function.
4.2 User Defined Functions
What is a Function?
A function is a block of organized and reusable code that performs a specific task. Functions help divide large programs into smaller and manageable parts.
Advantages of Functions
- Code reusability.
- Reduces repetition of code.
- Makes programs easier to understand.
- Improves program organization.
- Makes debugging and maintenance easier.
Types of Python Functions
| Function Type | Description |
|---|---|
| Built-in Functions | Functions already available in Python. Examples: print(), input(), len(), sum() |
| User Defined Functions | Functions created by programmers according to their requirements. |
Creating a User Defined Function
User defined functions are created using the def keyword.
Syntax
def function_name(parameters):
statements
return value
Example: Function without Parameter
def welcome():
print("Welcome to Python")
welcome()
Output:
Welcome to Python
Function Call
A function call is the process of executing a function by writing its name followed by parentheses.
Example:
def greet():
print("Hello")
greet()
Parameters and Arguments
Parameters
Parameters are variables written inside the function definition. They receive values when the function is called.
Example:
def add(a,b):
print(a+b)
Here:
a and b are parameters
Arguments
Arguments are actual values passed to a function during function call.
Example:add(10,20)Here:
10 and 20 are arguments
Difference Between Parameter and Argument
| Parameter | Argument |
|---|---|
| Written in function definition | Written during function call |
| Receives values | Passes values |
| Example: a,b | Example: 10,20 |
Scope of Variables
Scope defines the area where a variable can be accessed in a program.
1. Local Scope
A variable created inside a function is called a local variable. It can only be used inside that function.
Example:
def show():
x = 10
print(x)
show()
2. Global Scope
A variable created outside a function is called a global variable. It can be accessed throughout the program.
Example:
x = 20
def display():
print(x)
display()
Return Statement
The return statement sends a value back from a function to the calling program.
Syntax:return valueExample:
def square(n):
return n*n
result = square(5)
print(result)
Output:
25
Types of Arguments
1. Positional Arguments
Arguments are passed in the same order as parameters.
Example:
def student(name,age):
print(name,age)
student("Ram",16)
2. Default Arguments
A default argument has a predefined value.
Example:
def greet(name="Student"):
print(name)
greet()
greet("Hari")
Output:
Student Hari
3. Keyword Arguments
In keyword arguments, values are passed using parameter names.
Example:
def info(name,age):
print(name,age)
info(age=16,name="Ram")
Functions Returning Values
A function that returns a result using return statement is called a non-void function.
Example:
def addition(a,b):
return a+b
print(addition(5,3))
Output:
8
Void Functions
A function that performs a task but does not return any value is called a void function.
Example:
def message():
print("Hello Python")
message()
Returning Multiple Values
Python allows a function to return multiple values separated by commas.
Example:
def calculate(a,b):
return a+b, a-b
x,y = calculate(10,5)
print(x)
print(y)
Output:
15 5
- Function is created using def keyword.
- Parameters are written in function definition.
- Arguments are passed during function call.
- return sends result back to caller.
- Local variables cannot be accessed outside function.
4.4 Graphics Using Turtle
Introduction to Turtle Module
The Turtle module is a built-in Python module used to create graphics by drawing lines, shapes and designs using a cursor called a turtle.
It is mainly used for learning programming in a simple and visual way.
Uses of Turtle Module
- Helps learn programming through graphics.
- Makes programming interactive and interesting.
- Helps understand loops, functions and angles.
- Improves creativity and logical thinking.
- Makes errors easier to identify visually.
Basic Structure of Turtle Program
import turtle pen = turtle.Turtle() # Turtle commands turtle.done()
Explanation of Commands
| Command | Description |
|---|---|
| import turtle | Imports turtle module into the program. |
| turtle.Screen() | Creates drawing window. |
| turtle.Turtle() | Creates turtle object. |
| turtle.done() | Keeps drawing window open. |
Turtle Motion Commands
| Command | Purpose | Example |
|---|---|---|
| forward() | Moves turtle forward | pen.forward(100) |
| backward() | Moves turtle backward | pen.backward(50) |
| right() | Turns clockwise | pen.right(90) |
| left() | Turns anticlockwise | pen.left(90) |
| circle() | Draws circle | pen.circle(50) |
Color and Style Commands
| Command | Purpose |
|---|---|
| color() | Changes pen color |
| fillcolor() | Sets filling color |
| pensize() | Changes pen thickness |
| speed() | Controls drawing speed |
Pen Control Commands
penup()
Lifts the pen and stops drawing.
Example:pen.penup() pen.forward(100) pen.pendown()
pendown()
Places the pen down and starts drawing.
Position Commands
| Command | Purpose |
|---|---|
| goto(x,y) | Moves turtle to specific position. |
| home() | Returns turtle to starting position. |
| heading() | Shows current direction. |
Fill Commands
pen.begin_fill() # drawing commands pen.end_fill()
These commands fill closed shapes with colour.
Screen Commands
| Command | Purpose |
|---|---|
| clear() | Removes drawings. |
| reset() | Clears screen and resets turtle. |
| hideturtle() | Hides turtle cursor. |
| showturtle() | Shows turtle cursor. |
| bgcolor() | Changes background colour. |
Common Turtle Shapes
| Shape | Example |
|---|---|
| arrow | pen.shape("arrow") |
| turtle | pen.shape("turtle") |
| circle | pen.shape("circle") |
| square | pen.shape("square") |
| triangle | pen.shape("triangle") |
Solved Turtle Programs
1. Draw a Straight Line
import turtle pen = turtle.Turtle() pen.forward(200) turtle.done()
2. Draw a Square
import turtle
pen = turtle.Turtle()
for i in range(4):
pen.forward(100)
pen.right(90)
turtle.done()
3. Draw a Rectangle
import turtle
pen=turtle.Turtle()
for i in range(2):
pen.forward(150)
pen.right(90)
pen.forward(80)
pen.right(90)
turtle.done()
4. Draw a Triangle
import turtle
pen=turtle.Turtle()
for i in range(3):
pen.forward(120)
pen.left(120)
turtle.done()
5. Draw a Circle
import turtle pen=turtle.Turtle() pen.circle(80) turtle.done()
- Turtle starts from center position (0,0).
- Square turning angle = 90°.
- Triangle turning angle = 120°.
- Circle is drawn using circle() command.
- begin_fill() and end_fill() are used for colouring shapes.
4.5 Error Handling
Introduction
Error handling is the process of detecting and handling errors during program execution so that the program does not crash suddenly.
Importance of Error Handling
- Prevents program crashes.
- Makes programs reliable.
- Displays meaningful error messages.
- Improves debugging.
- Increases software quality.
Types of Errors in Python
| Error Type | Description |
|---|---|
| Syntax Error | Error caused by violation of Python syntax rules. Example: Missing colon. |
| Runtime Error | Error occurring during program execution. Example: Division by zero. |
| Logical Error | Program runs but gives incorrect output. |
Exception Handling
Exception handling is used to handle runtime errors using:
- try
- except
- else
- finally
try Block
The try block contains code that may produce an error.
except Block
The except block handles the error.
else Block
The else block executes when no error occurs.
finally Block
The finally block always executes whether error occurs or not.
Example of Exception Handling
try:
a = int(input("Enter number:"))
b = int(input("Enter number:"))
result = a/b
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Program completed")
Common Python Exceptions
| Exception | Meaning |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Wrong value entered |
| TypeError | Wrong data type |
| IndexError | Invalid index |
| FileNotFoundError | File does not exist |
4.6 File Handling Using Pandas Library
Introduction
File handling is the process of storing data permanently in files and accessing that data when required.
File Handling Modes
| Mode | Purpose |
|---|---|
| r | Read file |
| w | Write file |
| a | Append data |
Pandas Library
Pandas is a Python library used for data handling and analysis. It uses DataFrame structure to store data.
Reading CSV File
import pandas as pd
data = pd.read_csv("student.csv")
print(data)
Writing CSV File
import pandas as pd
data = {
"Name":["Ram","Hari"],
"Age":[15,16]
}
df = pd.DataFrame(data)
df.to_csv("student.csv")
Advantages of Pandas
- Easy data handling.
- Reads CSV and Excel files.
- Provides DataFrame structure.
- Useful for data analysis.
4.7 Introduction to Data Visualization
Data visualization is the process of representing data in graphical form so that information can be understood easily.
Matplotlib Library
Matplotlib is a Python library used to create charts and graphs.
Types of Charts
1. Line Chart
A line chart shows changes in data over time.
Example:import matplotlib.pyplot as plt x=[1,2,3] y=[4,5,6] plt.plot(x,y) plt.show()
2. Bar Graph
Bar graphs compare values between different categories.
Example:import matplotlib.pyplot as plt names=["A","B","C"] marks=[80,90,70] plt.bar(names,marks) plt.show()
3. Pie Chart
Pie charts show percentage distribution of data.
Example:import matplotlib.pyplot as plt data=[40,30,20,10] plt.pie(data) plt.show()
Practical Tasks
- Demonstrate structure of user defined functions.
- Install and use Python packages and libraries such as Pandas, Turtle and Matplotlib.
- Draw different shapes using Turtle graphics.
- Read and write CSV files using Pandas.
- Create bar, line and pie charts using Matplotlib.
Project Work
Develop a simple Python project using:
- User defined functions.
- Python libraries.
- Data visualization tools.
Project Report Should Include
- Introduction of project.
- Problem definition.
- Tools and libraries used.
- Development process.
- Program code.
- Output screenshots.
- Conclusion.
No comments:
Post a Comment