Showing posts with label Python Tips. Show all posts
Showing posts with label Python Tips. Show all posts

Saturday, 22 August 2026

๐Ÿš€ Day 103/150 – Phone Number Validation in Python

 

Image

Image


๐Ÿš€ Day 103/150 – Phone Number Validation in Python

Validating phone numbers is one of the most common tasks in Python applications. Whether you're building a registration form, login system, or contact management app, ensuring users enter a valid phone number helps improve data accuracy and prevents invalid entries.

In this post, we'll explore four different ways to validate phone numbers in Python, starting from simple checks to a more reliable solution using Regular Expressions.


Method 1 – Basic Phone Number Validation


The easiest way to validate a phone number is by checking whether it contains exactly 10 characters.


phone = input("Enter your phone number: ") if len(phone) == 10: print("Valid Phone Number") else: print("Invalid Phone Number")






Sample Input
9876543210

Output
Valid Phone Number

Explanation
input() accepts the phone number from the user.
len() calculates the total number of characters.
If the length is exactly 10, the number is considered valid.
Otherwise, it is marked as invalid.

Note: This method only checks the length and does not verify whether all characters are digits

Method 2 – Check Digits Only

A valid phone number should contain only numeric digits.

phone = input("Enter your phone number: ") if phone.isdigit(): print("Valid Phone Number") else: print("Invalid Phone Number")




Sample Input

9876543210

Output

Valid Phone Number

Explanation

isdigit() checks whether every character in the string is a digit.

If all characters are numeric, it returns True.

Otherwise, the phone number is considered invalid.

Note: This method doesn't verify the length of the phone number.


Method 3 – Check Length and Digits

This method combines the previous two validations to make the check more reliable.

phone = input("Enter your phone number: ") if len(phone) == 10 and phone.isdigit(): print("Valid Phone Number") else: print("Invalid Phone Number")




Sample Input

9876543210

Output

Valid Phone Number

Explanation

len(phone) == 10 ensures the phone number contains exactly 10 characters.

phone.isdigit() confirms every character is a digit.

Both conditions must be true for the phone number to be valid.

This approach is commonly used in beginner-level Python programs.


Method 4 – Using Regular Expressions

Regular Expressions (Regex) provide a more professional and flexible way to validate phone numbers.

import re phone = input("Enter your phone number: ") pattern = r"^[0-9]{10}$" if re.match(pattern, phone): print("Valid Phone Number") else: print("Invalid Phone Number")






Sample Input

9876543210

Output

Valid Phone Number

Explanation

import re imports Python's Regular Expression module.

^[0-9]{10}$ means:

^ → Start of the string

[0-9] → Any digit from 0 to 9

{10} → Exactly 10 digits

$ → End of the string

re.match() checks whether the entire input matches the pattern.

Regex is widely used in real-world applications because it provides accurate validation with minimal code.


Comparison of Methods

Method Best For

Check Length Basic validation

Check Digits Only Ensuring numeric input

Check Length + Digits Beginner-friendly phone validation

Regular Expressions Professional and production-level validation


๐Ÿ”ฅ Key Takeaways

Phone number validation helps prevent invalid user input.

len() checks whether the phone number has the required number of characters.

isdigit() ensures every character is numeric.

Combining length and digit validation provides a better solution.

Regular Expressions (re) offer the most reliable and scalable validation approach.

Phone number validation is commonly used in registration forms, authentication systems, contact applications, and web development projects.

Stay tuned for Day 104 of the #150DaysOfPython series! ๐Ÿš€


Learn :

Data Structures and Algorithm Design using Python











Thursday, 20 August 2026

๐Ÿš€ Day 102/150 – Email Validation Program in Python

 

Image

๐Ÿš€ Day 102/150 – Email Validation Program in Python

Email validation is a common task in many applications such as registration forms, login systems, and contact forms. A valid email address should follow a proper format, such as containing an @ symbol, a domain name, and a valid extension.

In this post, we'll explore four different ways to validate an email address in Python.


Method 1 – Basic Email Validation

Check whether the email contains both @ and ..

password = input("Enter your password: ") special = "!@#$%^&*()_+-=[]{}|;:',.<>?/" if (len(password) >= 8 and any(char.isupper() for char in password) and any(char.islower() for char in password) and any(char.isdigit() for char in password) and any(char in special for char in password)): print("Strong Password") else: print("Weak Password")







Sample Input

user@example.com

Output
Valid Email

Explanation

  • input() reads the email address.

  • The program checks if the email contains both @ and ..

  • If both are present, it considers the email valid.

  • Otherwise, it prints "Invalid Email".


Method 2 – Check Email Format

Ensure the email contains exactly one @ and ends with a common domain extension.


email = input("Enter your email: ") if email.count("@") == 1 and email.endswith((".com", ".org", ".net")): print("Valid Email") else: print("Invalid Email")







Sample Input
python@gmail.com

Output

Valid Email

Explanation

    count("@") ensures there is only one @.
    endswith() checks if the email ends with .com, .org, or .net.
    Both conditions must be true for the email to be valid.

Method 3 – Using Regular Expressions

Use Python's re module for more accurate email validation.

import re email = input("Enter your email: ") pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" if re.match(pattern, email): print("Valid Email") else: print("Invalid Email")










Sample Input
hello123@gmail.com

Output

Valid Email

Explanation

  • The re module provides support for regular expressions.

  • re.match() checks whether the email matches the specified pattern.

  • This method is more reliable than checking only for @ and ..


Method 4 – Validate Multiple Email Addresses

Check several email addresses stored in a list.


emails = [ "alice@gmail.com", "bob@yahoo", "charlie@example.com" ] for email in emails: if "@" in email and "." in email: print(email, "- Valid") else: print(email, "- Invalid")











Output
alice@gmail.com - Valid 
bob@yahoo - Invalid 
charlie@example.com - Valid

Explanation

  • A list of email addresses is created.

  • The for loop checks each email one by one.

  • Emails containing both @ and . are marked as valid.

  • Others are marked as invalid.


Comparison of Methods

MethodBest For
Basic ValidationBeginners learning string operations
Format CheckSimple real-world validation
Regular ExpressionsAccurate email validation
Multiple EmailsValidating lists of email addresses

๐Ÿ”ฅ Key Takeaways

  • Email validation helps ensure users enter properly formatted email addresses.

  • Basic validation checks for the presence of @ and ..

  • count() and endswith() provide additional format checks.

  • The re module offers a more robust way to validate email addresses using regular expressions.

  • Email validation is commonly used in registration forms, login systems, and web applications.

Stay tuned for Day 103 of the #150DaysOfPython series! ๐Ÿš€

Thursday, 6 August 2026

๐Ÿš€ Day 96/150 – map() Function in Python

 

Image


๐Ÿš€ Day 96/150 – map() Function in Python

The map() function is a built-in Python function used to apply a function to every item in an iterable, such as a list or tuple. It helps you write cleaner and more concise code by avoiding explicit loops.

Syntax:

map(function, iterable)

In this post, we'll explore four common examples of using the map() function in Python.


Method 1 – Using map() with a Normal Function

Apply a normal function to every element in a list.

def square(num): return num ** 2 numbers = [1, 2, 3, 4, 5] result = list(map(square, numbers)) print(result)








Output

[1, 4, 9, 16, 25]

Explanation

  • square() returns the square of a number.
  • map() applies the square() function to every element in numbers.
  • list() converts the map object into a list.

Method 2 – Using map() with a Lambda Function

Use a lambda function for shorter code.

numbers = [2, 4, 6, 8] result = list(map(lambda x: x * 2, numbers)) print(result)





Output

[4, 8, 12, 16]

Explanation

  • lambda x: x * 2 doubles each element.
  • map() applies the lambda function to every item in the list.
  • The result is converted into a list.

Method 3 – Using map() with Multiple Iterables

map() can process multiple iterables at the same time.

list1 = [1, 2, 3] list2 = [4, 5, 6] result = list(map(lambda x, y: x + y, list1, list2)) print(result)






Output

[5, 7, 9]

Explanation

  • map() takes one element from each list at the same position.
  • The lambda function adds the corresponding elements.
  • The result is returned as a new list.

Method 4 – Taking User Input

Use map() to convert multiple user inputs into integers.

numbers = list(map(int, input("Enter numbers separated by spaces: ").split())) print(numbers)




Sample Input

10 20 30 40

Output

[10, 20, 30, 40]

Explanation

  • input() reads the values as a string.
  • split() separates the string into a list of strings.
  • map(int, ...) converts each string into an integer.
  • list() stores the converted values in a list.

Comparison of Methods

MethodBest For
Normal FunctionReusing existing functions
Lambda FunctionShort and simple operations
Multiple IterablesProcessing two or more lists together
User InputConverting input values to the desired data type

๐Ÿ”ฅ Key Takeaways

  • map() applies a function to every element in an iterable.
  • It returns a map object, which is often converted to a list using list().
  • map() works with both normal functions and lambda functions.
  • It can process multiple iterables simultaneously.
  • map() makes code cleaner and often replaces explicit for loops for simple transformations.

Tuesday, 4 August 2026

๐Ÿš€ Day 95/150 – Lambda Function Examples in Python

Image

๐Ÿš€ Day 95/150 – Lambda Function Examples in Python

A lambda function is a small, anonymous function in Python. It is useful when you need a simple function for a short period without defining it using the def keyword.

The syntax of a lambda function is:

lambda arguments: expression

In this post, we'll explore four common examples of lambda functions in Python.


Method 1 – Simple Lambda Function

Create a lambda function to add two numbers.

add = lambda a, b: a + b print(add(5, 3))



Output

8
Explanation
  • lambda a, b: defines an anonymous function with two parameters.

  • a + b is the expression whose result is returned automatically.

  • add(5, 3) returns 8.

Method 2 – Lambda with map()

Use a lambda function with map() to square each element in a list.

numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x ** 2, numbers)) print(squares)






Output
[1, 4, 9, 16, 25]

Explanation

  • map() applies the lambda function to every element in the list.

  • lambda x: x ** 2 returns the square of each number.

  • list() converts the result into a list.


Method 3 – Lambda with filter()

Use a lambda function to filter even numbers from a list.


numbers = [1, 2, 3, 4, 5, 6] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers)







Output
[2, 4, 6]

Explanation

  • filter() keeps only the elements for which the lambda function returns True.

  • lambda x: x % 2 == 0 checks whether a number is even.

  • The result is converted into a list.


Method 4 – Lambda with sorted()

Sort a list of tuples based on the second element.

students = [ ("Alice", 85), ("Bob", 92), ("Charlie", 78) ] sorted_students = sorted(students, key=lambda student: student[1]) print(sorted_students)









Output
[('Charlie', 78), ('Alice', 85), ('Bob', 92)]

Explanation

  • sorted() sorts the list.

  • The key parameter specifies the sorting rule.

  • lambda student: student[1] tells Python to sort using the second element (marks).


Comparison of Methods

MethodBest For
Simple LambdaShort mathematical operations
map()Transforming every element
filter()Selecting elements based on a condition
sorted()Custom sorting

๐Ÿ”ฅ Key Takeaways

  • A lambda function is a small anonymous function written in a single line.

  • It is best suited for short and simple operations.

  • map() uses lambda functions to transform data.

  • filter() uses lambda functions to select matching elements.

  • sorted() uses lambda functions to define custom sorting rules.

  • For complex logic, use a regular function (def) instead of a lambda function.

Stay tuned for Day 96 of the #150DaysOfPython series! ๐Ÿš€



Popular Posts

Categories

100 Python Programs for Beginner (119) AI (337) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (339) Bootcamp (14) C (78) C# (12) C++ (83) cloud (1) Course (89) Coursera (302) Cybersecurity (35) data (10) Data Analysis (46) Data Analytics (31) data management (16) Data Science (421) Data Strucures (18) Deep Learning (215) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (13) flask (4) flutter (1) FPL (17) Generative AI (77) Git (13) Google (54) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (387) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (16) PHP (20) Projects (34) Python (1362) Python Coding Challenge (1223) Python Library (1) Python Mathematics (12) Python Mistakes (51) Python Quiz (608) Python Tips (101) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (55) Udemy (20) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)