0% found this document useful (0 votes)
13 views28 pages

Python Programs Bca 4th Sem

The document provides a comprehensive introduction to Python programming, covering basic concepts such as data types (numeric, string, list, tuple, boolean, set, dictionary), operators (arithmetic and logical), and control structures (conditional statements and loops). It includes examples of writing simple programs, performing arithmetic operations, and implementing functions, including Fibonacci sequence generation. Additionally, it explains user input handling and demonstrates how to check for odd/even numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views28 pages

Python Programs Bca 4th Sem

The document provides a comprehensive introduction to Python programming, covering basic concepts such as data types (numeric, string, list, tuple, boolean, set, dictionary), operators (arithmetic and logical), and control structures (conditional statements and loops). It includes examples of writing simple programs, performing arithmetic operations, and implementing functions, including Fibonacci sequence generation. Additionally, it explains user input handling and demonstrates how to check for odd/even numbers.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Writing and executing a simple Python program

print("Hello, World!")

2. Working with variables and basic data types

1. Numeric Data Types


Python numbers represent data that has a numeric value. A numeric value
can be an integer, a floating number or even a complex number. These
values are defined as int, float and complex classes.
 Integers: value is represented by int class. It contains positive or
negative whole numbers (without fractions or decimals). There is no
limit to how long an integer value can be.
 Float: value is represented by float class. It is a real number with a
floating-point representation. It is specified by a decimal point.
Optionally, character e or E followed by a positive or negative
integer may be appended to specify scientific notation.
 Complex Numbers: It is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example - 2+3j

a = 5
print(type(a))

b = 5.0
print(type(b))

c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

2. Sequence Data Types


A sequence is an ordered collection of items, which can be of similar or
different data types. Sequences allow storing of multiple values in an
organized and efficient fashion. There are several sequence data types of
Python:

String Data Type

Python Strings are arrays of bytes representing Unicode characters. In


Python, there is no character data type, a character is a string of length one.
It is represented by str class.
Strings in Python can be created using single quotes, double quotes or even
triple quotes. We can access individual characters of a String using index.

s = 'Welcome to the Geeks World'


print(s)

# check data type


print(type(s))

# access string with index


print(s[1])
print(s[2])
print(s[-1])

Output
Welcome to the Geeks World
<class 'str'>
e
l
d

List Data Type

Lists are similar to arrays found in other languages. They are an ordered and
mutable collection of items. It is very flexible as items in a list do not need to
be of the same type.
Creating a List in Python
Lists in Python can be created by just placing sequence inside the square
brackets[].

# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed values int and String


b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
In order to access the list items refer to index number. In Python, negative
sequence indexes represent positions from end of the array. Instead of
having to compute offset as in List[len(List)-3], it is enough to just write List[-
3]. Negative indexing means beginning from end, -1 refers to last item, -2
refers to second-last item, etc.

a = ["Geeks", "For", "Geeks"]


print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")


print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Tuple Data Type

Tuple is an ordered collection of Python objects. The only difference


between a tuple and a list is that tuples are immutable. Tuples cannot be
modified after it is created.
Creating a Tuple in Python
In Python, tuples are created by placing a sequence of values separated by
a ‘comma’ with or without the use of parentheses for grouping data
sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a
trailing ‘comma’ to make it a tuple.

# initiate empty tuple


tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)

Output
Tuple with the use of String: ('Geeks', 'For')
Note - The creation of a Python tuple without the use of parentheses is
known as Tuple Packing.
Access Tuple Items
In order to access tuple items refer to the index number. Use the index
operator [ ] to access an item in a tuple.
tup1 = (1, 2, 3, 4, 5)

# access tuple items


print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output
1
5
3

3. Boolean Data Type


Python Boolean Data type is one of the two built-in values, True or False.
Boolean objects that are equal to True are truthy (true) and those equal to
False are falsy (false). However non-Boolean objects can be evaluated in a
Boolean context as well and determined to be true or false. It is denoted by
class bool.

print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/[Link]", line 8, in
print(type(true))
NameError: name 'true' is not defined

Truthy and Falsy Values


In Python, truthy and falsy values are values that evaluate to True or False in
a Boolean context. Truthy values behave like True, while falsy values
behave like False when used in conditions.

if 1:
print("1 is truthy")

if not 0:
print("0 is falsy")

Output
1 is truthy
0 is falsy

4. Set Data Type


In Python Data Types, Set is an unordered collection of data types that is
iterable, mutable, and has no duplicate elements. The order of elements in a
set is undefined though it may consist of various elements.

Create a Set in Python

Sets can be created by using the built-in set() function with an iterable object
or a sequence by placing the sequence inside curly braces, separated by a
‘comma’. The type of elements in a set need not be the same, various
mixed-up data type values can also be passed to the set.

# initializing empty set


s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)
Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}

Access Set Items


Set items cannot be accessed by referring to an index, since sets are
unordered the items have no index. But we can loop through the set items
using a for loop, or ask if a specified value is present in a set, by using the
keyword in.

set1 = set(["Geeks", "For", "Geeks"]) #Duplicates are removed


automatically
print(set1)

# loop through set


for i in set1:
print(i, end=" ") #prints elements one by one

# check if item exist in set


print("Geeks" in set1)

Output
{'For', 'Geeks'}
For Geeks True

5. Dictionary Data Type


A dictionary in Python is a collection of data values, used to store data
values like a map, unlike other Python Data Types, a Dictionary holds a key:
value pair. Key-value is provided in dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon : , whereas each
key is separated by a ‘comma’.

Create a Dictionary in Python

Values in a dictionary can be of any datatype and can be duplicated, whereas


keys can’t be repeated and must be immutable. The dictionary can also be
created by the built-in function dict().
Note - Dictionary keys are case sensitive, the same name but different cases
of Key will be treated distinctly.

# initialize empty dictionary


d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Accessing Key-value in Dictionary


In order to access items of a dictionary refer to its key name. Key can be
used inside square brackets. Using get() method we can access dictionary
elements.

d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key


print(d['name'])

# Accessing a element using get


print([Link](3))

Output
For
Geeks

3. Performing arithmetic and logical operations


Python operators are fundamental for performing mathematical calculations.
Arithmetic operators are symbols used to perform mathematical operations
on numerical values. Arithmetic operators include addition (+), subtraction (-
), multiplication (*), division (/), and modulus (%).
Operator Description Syntax

Addition: adds two


x+y
+ operands

Subtraction: subtracts two


x–y
– operands

Multiplication: multiplies
x*y
* two operands

Division (float): divides


the first operand by the x/y
/ second

Division (floor): divides


the first operand by the x // y
// second

Modulus: returns the


remainder when the first
x%y
operand is divided by the
% second

Power: Returns first raised


x ** y
** to power second

Addition Operator
In Python, + is the addition operator. It is used to add 2 values.

val1 = 2
val2 = 3
# using the addition operator
res = val1 + val2
print(res)
Output:
5

Subtraction Operator
In Python, - is the subtraction operator. It is used to subtract the second
value from the first value.

val1 = 2
val2 = 3

# using the subtraction operator


res = val1 - val2
print(res)
Output:
-1

Multiplication Operator
Python * operator is the multiplication operator. It is used to find the product
of 2 values.

val1 = 2
val2 = 3

# using the multiplication operator


res = val1 * val2
print(res)
Output :
6

Division Operator
In Python programming language Division Operators allow us to divide two
numbers and return a quotient, i.e., the first number or number at the left is
divided by the second number or number at the right and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if
two numbers are integers. For example:
Example:

print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)

Output
1.0
5.0
-5.0
10.0

Integer division( Floor division)


The quotient returned by this operator is dependent on the argument being
passed. If any of the numbers is float, it returns output in float. It is also known
as Floor division because, if any number is negative, then the output will be
floored. For example:
Example:

print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)

Output
3
-3
2.0
-3.0

Modulus Operator
The % in Python is the modulus operator. It is used to find the remainder
when the first operand is divided by the second.

val1 = 3
val2 = 2

# using the modulus operator


res = val1 % val2
print(res)
Output:
1

Exponentiation Operator
In Python, ** is the exponentiation operator. It is used to raise the first
operand to the power of the second.

val1 = 2
val2 = 3

# using the exponentiation operator


res = val1 ** val2
print(res)
Output:
8

Precedence of Arithmetic Operators in Python

Let us see the precedence and associativity of Python Arithmetic operators.


Operator Description Associativity

** Exponentiation Operator right-to-left

Modulos, Multiplication, Division, and Floor left-to-right


%, *, /, //
Division

+, - Addition and Subtraction operators left-to-right

Python logical operators are used to combine or modify conditions and return
a Boolean result (True or False). They are commonly used in conditional
statements to control the flow of a program based on multiple logical
conditions.
Let's see an example which demonstrates how Python logical operators and,
or, and not work using Boolean variables.

a, b, c = True, False, True

# AND: Both conditions must be True


if a and c:
print("Both a and c are True (AND condition).")

# OR: At least one condition must be True


if b or c:
print("Either b or c is True (OR condition).")

# NOT: Reverses the condition


if not b:
print("b is False (NOT condition).")

Output
Both a and c are True (AND condition).
Either b or c is True (OR condition).
b is False (NOT condition).
Example 1: Below example shows how the logical AND (and) operator
works by checking if all conditions are true before executing a statement.

a = 10
b = 10
c = -10
if a > 0 and b > 0:
print("The numbers are greater than 0")
if a > 0 and b > 0 and c > 0:
print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")

4. Taking user input and displaying output


# Taking integer input and converting it immediately
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Performing a calculation
sum_result = num1 + num2

# Displaying the output, including variables and text


print(f"The sum of {num1} and {num2} is {sum_result}.")

[Link] conditional statements (e.g., checking odd/even numbers)

# Python program to check if the input number is odd or even.


# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))

6. Writing loops for pattern printing, Fibonacci series, prime numbers


def fibonacci_iterative(nterms):
# First two terms
n1, n2 = 0, 1
count = 0

# Check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence up to", nterms, ":")
print(n1)
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1, end=" ")
nth = n1 + n2
# Update values
n1 = n2
n2 = nth
count += 1

# Driver code to run the function


num_terms = 10
fibonacci_iterative(num_terms)

USING RECURSION

def fibonacci_recursive(n):
if n <= 1:
return n
else:
return(fibonacci_recursive(n-1) + fibonacci_recursive(n-2))

# Driver code to run the function


num_terms = 10

if num_terms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(num_terms):
print(fibonacci_recursive(i), end=" ")

7. Creating functions with different argument types


def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

def my_function(name): # name is a parameter


print("Hello", name)
my_function("Emil") # "Emil" is an argument

This function expects 2 arguments, and gets 2 arguments::

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil", "Refsnes")

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname):


print(fname + " " + lname)

my_function("Emil")

def my_function(name = "friend"):


print("Hello", name)

my_function("Emil")
my_function("Tobias")
my_function()
my_function("Linus")

Default value for country parameter:

def my_function(country = "Norway"):


print("I am from", country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

8. Implementing exception handling for division by zero


def safe_division(numerator, denominator):
"""
Performs division of two numbers with exception handling for division by
zero.
Args:
numerator: The number to be divided.
denominator: The number to divide by.

Returns:
The result of the division, or a string message if an error occurred.
"""
try:
# Attempt the division
result = numerator / denominator
return result
except ZeroDivisionError:
# Handle the specific error of division by zero
return "Error: Cannot divide by zero."
except TypeError:
# Handle cases where inputs are not numbers
return "Error: Both inputs must be valid numbers."
except Exception as e:
# Catch any other potential exceptions
return f"An unexpected error occurred: {e}"

# --- Examples of usage ---

# Successful division
result1 = safe_division(10, 2)
print(f"10 / 2 = {result1}")

# Division by zero
result2 = safe_division(10, 0)
print(f"10 / 0 = {result2}")

# Type error (non-numeric input)


result3 = safe_division("ten", 2)
print(f"'ten' / 2 = {result3}")

[Link] CRUD operations on lists and dictionaries


# --- LIST CRUD OPERATIONS ---
my_list = []

# 1. CREATE (Add elements)


my_list.append("apple") # Add to the end
my_list.append("banana")
my_list.insert(0, "orange") # Insert at a specific index
print(f"After creation: {my_list}")

# 2. READ (Access elements)


first_item = my_list[0]
print(f"Reading first item: {first_item}")
# Iterate through the list
print("Reading all items:")
for item in my_list:
print(item)

# 3. UPDATE (Modify elements)


my_list[1] = "grape" # Update element at index 1 (banana becomes grape)
print(f"After update: {my_list}")

# 4. DELETE (Remove elements)


my_list.remove("orange") # Remove by value
deleted_item = my_list.pop(0) # Remove by index and return the item (grape)
del my_list[0] # Remove by index (apple)
print(f"After deletion: {my_list}")

# --- DICTIONARY CRUD OPERATIONS ---


my_dict = {}

# 1. CREATE (Add key-value pairs)


my_dict["name"] = "Alice"
my_dict["age"] = 30
my_dict["city"] = "New York"
print(f"After creation: {my_dict}")

# 2. READ (Access values using keys)


users_name = my_dict["name"] # Access value by key
print(f"Reading name: {users_name}")
# Safely read a key that might not exist
country = my_dict.get("country", "Unknown")
print(f"Reading country (safe): {country}")
# Iterate through keys and values
print("Reading all items:")
for key, value in my_dict.items():
print(f"{key}: {value}")

# 3. UPDATE (Modify existing values)


my_dict["age"] = 31 # Update the value for the "age" key
print(f"After update: {my_dict}")

# 4. DELETE (Remove key-value pairs)


del my_dict["city"] # Remove by key
deleted_age = my_dict.pop("age") # Remove by key and return the value (31)
print(f"After deletion: {my_dict}")

10. Writing programs to manipulate and process strings

 Concatenation: Strings can be joined using the + operator or f-strings


(formatted string literals), which is generally the preferred method [1].

python
s1 = "Hello"
s2 = "world"
combined = s1 + " " + s2 # Hello world
# Using f-strings
greeting = f"{s1} {s2}" # Hello world
 Slicing: You can access substrings using slicing notation [start:stop:step] .

python
text = "Python Programming"
sub = text[0:6] # Python
sub = text[7:] # Programming (from index 7 to the end)
sub = text[-1] # g (last character)
String Methods
Python strings have numerous built-in methods for manipulation [1, 2]:
 len() : Returns the length of a string [1].

python
length = len(text) # 18
 split() and join() : split() divides a string into a list based on a delimiter,
while join() combines a list of strings into a single string [1, 2].

python
words = [Link](" ") # ['Python', 'Programming']
new_text = "-".join(words) # Python-Programming
 Case Modification: Methods like lower() , upper() , capitalize() ,
and title() change the case of the characters [2].

python
print([Link]()) # python programming
print([Link]()) # PYTHON PROGRAMMING

import re

phone_number = "Call us at 123-456-7890 or 098-765-4321."


# Find all occurrences of phone numbers (simple pattern)
pattern = r"\d{3}-\d{3}-\d{4}"
found_numbers = [Link](pattern, phone_number) # ['123-456-7890', '098-
765-4321']

# Substitute matching patterns


cleaned_text = [Link](pattern, "PHONE_NUMBER", phone_number)
# Call us at PHONE_NUMBER or PHONE_NUMBER.
11. Reading from and writing to files
with open("[Link]", "a") as f:
[Link]("Now the file has more content!")

#open and read the file after the appending:


with open("[Link]") as f:
print([Link]())

with open("[Link]", "w") as f:


[Link]("Woops! I have deleted the content!")

#open and read the file after the overwriting:


with open("[Link]") as f:
print([Link]())

Create a new file called "[Link]":

f = open("[Link]", "x")

[Link] and using classes and objects


class Dog:
# A class attribute, shared by all instances
species = "Canis familiaris"

# The __init__ method (constructor) initializes the object's attributes


def __init__(self, name, age):
[Link] = name # Instance attribute, unique to each object
[Link] = age # Instance attribute

# An instance method to define the behavior of the object


def bark(self):
print(f"{[Link]} says Woof!")

# Another method
def describe(self):
return f"{[Link]} is a {[Link]} year old {[Link]}."

# Creating objects (instances) of the Dog class


dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

# Accessing attributes and calling methods using the objects


print([Link]())
[Link]()

print([Link]())
[Link]()

13. Implementing inheritance and method overriding


# Parent Class (Superclass/Base Class)
class Animal:
def __init__(self, name):
[Link] = name
print(f"Animal {[Link]} created.")

def make_sound(self):
"""Generic method for an animal sound."""
print("Some generic animal sound")

def info(self):
"""A method that will not be overridden."""
print(f"My name is {[Link]}.")

# Child Class (Subclass/Derived Class) - Dog


class Dog(Animal):
def __init__(self, name):
# Call the parent class constructor using super()
super().__init__(name)
print(f"Dog {[Link]} created.")

# Override the make_sound method


def make_sound(self):
"""Specific method for a dog sound."""
print("Woof! Woof!")

# Child Class (Subclass/Derived Class) - Cat


class Cat(Animal):
def __init__(self, name):
super().__init__(name)
print(f"Cat {[Link]} created.")

# Override the make_sound method


def make_sound(self):
"""Specific method for a cat sound."""
# Optionally call the parent's method from within the overridden
method
super().make_sound()
print("Meow!")

# Create instances and test the methods


dog_instance = Dog("Buddy")
cat_instance = Cat("Whiskers")
generic_animal = Animal("Leo")

print("-" * 20)
dog_instance.info() # Uses the inherited info() method
dog_instance.make_sound() # Calls the overridden method in the Dog class

print("-" * 20)
cat_instance.info() # Uses the inherited info() method
cat_instance.make_sound() # Calls the overridden method in the Cat class
(with super() call)

print("-" * 20)
generic_animal.info() # Uses the parent class info() method
generic_animal.make_sound() # Uses the parent class make_sound() method

14. Using built-in and user-defined modules


# Import the entire math module
import math

# Use the sqrt function from the math module


square_root = [Link](25)
print(f"The square root of 25 is: {square_root}")

# Use the pi constant


print(f"The value of pi is: {[Link]}")

14. Writing Python programs using NumPy and Pandas


import numpy as np

# Create a NumPy array


arr = [Link]([10, 20, 30, 40, 50])

# Perform a basic operation (e.g., add 5 to each element)


arr_plus_five = arr + 5

# Calculate the mean of the array


mean_value = [Link](arr)

print(f"Original array: {arr}")


print(f"Array after adding 5: {arr_plus_five}")
print(f"Mean value: {mean_value}")

import pandas as pd

# Create a DataFrame from a dictionary


data = {
'City': ['Mumbai', 'Delhi', 'Bangalore', 'Chennai'],
'Population_Millions': [20.4, 29.3, 13.1, 11.0],
'Area_SqKm': [603, 1484, 709, 426]
}
df = [Link](data)

# Display the DataFrame


print("Original DataFrame:")
print(df)
print("-" * 30)

# Filter cities with population over 15 million


high_pop_cities = df[df['Population_Millions'] > 15]
print("Cities with population > 15 million:")
print(high_pop_cities)

16. Connecting and querying databases from Python

import sqlite3

def connect_and_query_sqlite(db_file):
conn = None
try:
# Establish a connection (creates the file if it doesn't exist)
conn = [Link](db_file)
print(f"Connection established to {db_file} successfully.")

# Create a cursor object


cursor = [Link]()

# Execute a SQL query (create table)


[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
''')
[Link]()
print("Table ensured to exist.")

# Execute an INSERT query (safely parameterized)


user_name = 'John Doe'
user_email = 'john@[Link]'
[Link]("INSERT INTO users (name, email) VALUES (?, ?)",
(user_name, user_email))
[Link]()
print(f"Inserted record for {user_name}.")

# Execute a SELECT query


[Link]("SELECT name, email FROM users;")
records = [Link]()
print("\nFetched records:")
for row in records:
print(f"- Name: {row[0]}, Email: {row[1]}")

except [Link] as e:
print(f"A database error occurred: {e}")
if conn:
[Link]() # Roll back changes in case of an error
finally:
if conn:
# Close the connection
[Link]()
print("\nConnection closed.")

if __name__ == "__main__":
connect_and_query_sqlite("my_database.db")

17. Creating a basic web application using Flask

Flask - Creating First Simple Application


Prerequisites

To follow this article, you need:


 Python 3.x installed on your system
 pip (Python package manager)
 Flask (will be installed during the steps)
Step-by-Step Process
Step 1: Install Flask
To install Flask, open your terminal or command prompt and enter below
command:
pip install Flask
This command installs Flask along with the required supporting libraries.
Step 2: Create Your First Flask Application
Create a new Python file named [Link]. This file will contain the code for
your first Flask web application.
from flask import Flask

app = Flask(__name__)

@[Link]('/')
def hello_world():
return 'Hello World'

if __name__ == '__main__':
[Link]()
Explanation:
 Flask(__name__) creates the Flask application
 @[Link]('/') connects the home URL (/) to a function
 The function returns text shown in the browser
 [Link]() starts the local server
Step 3: Run the Flask Application
Run the command and you will see following in your terminal:
Run the Flask Application
Open the given URL in your web browser to view your first Flask web page
showing Hello World.

Output of the above


FlaskAPI app
Step 4: Handling a POST Request Using an HTML Form
To understand how POST requests work in Flask, we will create a form that
sends a user’s name to the server and displays it after submission.
Folder Structure
Before writing any code, organize your project folder as shown below:

App Folder Structure


Explanation:
 [Link]: Main Flask application file
 templates/: Flask automatically looks here for HTML files
 [Link]: HTML form used to send POST data
Create the HTML Form
Inside the templates folder, create a file named [Link] and add the
following code:
<!DOCTYPE html>
<html>
<body>
<h3>Enter Your Name</h3>
<form method="post">
<input type="text" name="username" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Explanation:
 The form uses method="post" to send data securely
 The input field sends the value using the name username
 Clicking Submit sends the data to the Flask server
Now, Update [Link] as shown below:
from flask import Flask, request, render_template

app = Flask(__name__)

@[Link]('/login', methods=['GET', 'POST'])


def login():
if [Link] == 'POST':
name = [Link]['username']
return f"Hello {name}, POST request received"
return render_template('[Link]')

if __name__ == '__main__':
[Link](debug=True)
Output
Open the browser and visit [Link]
Flask
development server running successfully.
Now, Enter a name and click Submit

Entering a name in
the form before submission.
The browser displays:

Output
displayed after submitting the form using POST request.
Explanation:
 render_template() displays the HTML form
 methods=['GET', 'POST'] allows both request types
 GET request shows the form in the browser
 POST request reads submitted form data using [Link]
 debug=True helps during development

You might also like