Category: Python

  • Python – For Loop Examples

    Example 1
    mycity=["Kalugumalai","Chennai","Madurai"]
    
    for citynames in mycity:
            print (citynames)
            print ("hi")
    Output:
    ======
    Kalugumalai
    hi
    Chennai
    hi
    Madurai
    hi
    Example 2
    mynumbers=[1,2,3,4,5]
    
    for n in mynumbers:
            print (n)
    Output:
    ======
    1
    2
    3
    4
    5
    Example.3
    mynumbers=[2,4,6,8,10]
    
    for n in mynumbers:
            print (n-1)
    output:
    1
    3
    5
    7
    9
    Example 4: To Prints the numbers from 1 to 5
    for i in range(1, 6):
        print(i)

    Output :

    1
    2
    3
    4
    5
    Example 4 : To Prints charactors
    # Define a string
    word = "Hello"
    
    # Start the for loop
    for char in word:
        print(char)

    Output :

    H
    e
    l
    l
    o
    Example 5 : Printing the Elements of a List
    colors = ["red", "green", "blue"]
    
    for color in colors:
        print(color)

    Output :

    red
    green
    blue
    Example 6 : To Sum the Numbers in a List
    numbers = [1, 2, 3, 4, 5]
    
    total = 0
    
    for number in numbers:
        total = total + number 
    
    print("Total sum:", total)
    

    Output :

    Total sum: 15
    Example 7:to Print Multiplication Table
    # Define the number for which to print the multiplication table
    number = 7
    
    # Start the for loop
    for i in range(1, 11):
        print(f"{number} x {i} = {number * i}")
    

    Output :

    7 x 1 = 7
    7 x 2 = 14
    7 x 3 = 21
    ...
    7 x 10 = 70
    Example 8: To Print Odd Numbers Only
    mynumbers=[1,2,3,4,5,6,7,8,9,10]
    
    for n in mynumbers:
        if(n%2=1)
            print (n)
    Output : 
    1
    3
    5
    7
    9
    Example 9 : To Print Even Numbers from 1 to 100
    for n in range(1,101):
        if(n%2=0)
            print (n)
    Output :
    2
    4
    6
    .
    .
    .100
    Example 10 :
    mytable=2
    for i in range(1,10):
         print(f"{i}  x  {mytable}  = {mytable* i}")
    Output : 
    1  x  2  = 2
    2  x  2  = 4
    3  x  2  = 6
    4  x  2  = 8
    5  x  2  = 10
    6  x  2  = 12
    7  x  2  = 14
    8  x  2  = 16
    9  x  2  = 18
  • Python – While Loop Examples

    Example 1 : Counting from 1 to 5

    count = 1
    
    while count <= 5:
        print(count)
        count = count+1

    Output :

    1
    2
    3
    4
    5

    Example 2 : Sum of Numbers from 1 to 10

    
    
    count = 1
    total_sum = 0

    while count <= 10:
    total_sum = total_sum + count
    count =count + 1

    print("The sum of numbers from 1 to 10 is:", total_sum)

    Output :

    The sum of numbers from 1 to 10 is: 55

    Example 3: Asking for a Password

    correct_password = "root1234"
    
    while True:
        password = input("Enter the password: ")
        if password == correct_password:
            print("Access granted!")
            break                                          
        else:
            print("Incorrect password, try again.")

    Output :

    Enter the password: abc
    Incorrect password, try again.
    
    Enter the password: root1234
    Access granted!

    Example 4: To Print Even Numbers Between 1 and 10

    number = 2
    
    while number <= 10:
        print(number)
        number = number + 2

    Output :

    2
    4
    6
    8
    10

    Example 5: ATM Withdrawal

    balance = 1000
    
    
    while True:
        withdrawal = int(input("Enter amount to withdraw: "))
        
        if withdrawal > balance:
            print("Insufficient funds. Your balance is:", balance)
        else:
            balance -= withdrawal
            print("Withdrawal successful. New balance is:", balance)
            break 

    Output :

    Enter amount to withdraw: 1500
    Insufficient funds. Your balance is: 1000
    Enter amount to withdraw: 500
    Withdrawal successful. New balance is: 500

    Example 6: Password Retry Limits

    correct_password = "securePass"
    attempts_left = 3
    
    
    while attempts_left > 0:
        password = input("Enter the password: ")
        
        if password == correct_password:
            print("Access granted!")
            break 
        else:
            attempts_left -= 1
            print("Incorrect password. Attempts left:", attempts_left)
    
    if attempts_left == 0:
        print("Too many failed attempts. Access denied.")

    Output :

    Enter the password: wrong1
    Incorrect password. Attempts left: 2
    Enter the password: wrong2
    Incorrect password. Attempts left: 1
    Enter the password: securePass
    Access granted!
  • Overview of Python: Python’s history, its uses, and why it’s popular.

    History:

    • Birth: Python is a type of computer language. A guy named Guido van Rossum made it and introduced it to the world in 1991.
    • Guiding Principles: The people who made Python wanted it to be easy to read and write. They said, “Let’s make it so that you can understand what’s happening just by looking at the code.”
    • Evolution: Like how animals evolve, Python also got better over time. There are different versions, but the newest one is called Python 3.

    Uses:

    • Web Development: People use Python to build websites. It’s like making a house, but on the internet.
    • Data Science: Scientists use Python to understand big amounts of data. It’s like finding patterns in a lot of information.
    • Automation: Python helps with boring tasks on the computer, like copying files or sending emails automatically.
    • Game Development: Some people create video games with Python. It’s like writing a story and making it interactive on the computer.
    • Desktop Applications: People make regular computer programs with Python. These could be anything from a simple calculator to a music player.

    Popularity:

    • Easy to Learn: Python is like learning a new language, but an easy one. People can start using it without getting too confused.
    • Large Community: Many people around the world use Python. If you have a question or need help, you can find lots of friendly people to assist you.
    • Versatile: Python can do many different things. It’s like a Swiss Army knife for programming!
    • Lots of Helpful Tools: There are many extra things you can add to Python to make it do even more. It’s like having a big box of toys to play with.
    • Used Everywhere: Companies and smart people all over the world use Python for their projects. It’s like the cool kid in school that everyone wants to be friends with.

    In simple words, Python is a friendly language that helps you do lots of cool stuff on the computer, and many people love it!

  • Outline of Python

    Learning Python effectively requires a structured approach that builds from basic to advanced concepts. Here’s a comprehensive outline to guide your learning journey:

    1. Introduction to Python

    • Overview of Python: Learn about Python’s history, its uses, and why it’s popular.
    • Setting Up Python: Install Python and set up your development environment (IDEs like VSCode, PyCharm, or Jupyter Notebook).

    2. Basic Syntax and Operations

    • Hello, World!: Write your first Python program.
    • Basic Syntax: Understand Python’s syntax, indentation, and comments.
    • Data Types: Learn about integers, floats, strings, booleans, and NoneType.
    • Variables: How to declare and use variables.

    3. Control Structures

    • Conditional Statements: if, elif, else
    • Loops: for and while loops
    • Control Flow Tools: break, continue, and pass

    4. Functions and Modules

    • Defining Functions: Learn to define and call functions, pass arguments, and return values.
    • Lambda Functions: Understand the use of anonymous functions.
    • Modules and Packages: Importing modules, exploring the standard library, and creating packages.

    5. Data Structures

    • Lists: Creation, manipulation, list comprehensions.
    • Tuples: Understanding immutable sequences.
    • Sets: Operations and uses of sets.
    • Dictionaries: Key-value pairs and dictionary comprehensions.

    6. String Manipulation

    • String Operations: Concatenation, slicing, and formatting.
    • String Methods: Common string methods like split(), join(), replace(), and others.
    • Regular Expressions: Using the re module for pattern matching.

    7. File Handling

    • Reading and Writing Files: Open, read, write, and close files.
    • File Methods: Using methods like read(), readline(), and readlines().

    8. Error Handling

    • Exceptions: Understanding try, except, finally, and else blocks.
    • Custom Exceptions: Creating and raising custom exceptions.

    9. Object-Oriented Programming (OOP)

    • Classes and Objects: Defining classes, creating objects.
    • Attributes and Methods: Instance attributes, class attributes, and methods.
    • Inheritance: Subclasses, overriding methods, and multiple inheritance.
    • Encapsulation and Polymorphism: Private attributes/methods and polymorphic behavior.

    10. Libraries and Frameworks

    • Standard Libraries: Explore commonly used libraries like os, sys, math, datetime, and collections.
    • Third-Party Libraries: Learn to use pip to install packages. Explore popular libraries like NumPy, pandas, requests, and Flask/Django for web development.

    11. Advanced Topics

    • Generators and Iterators: Understanding yield, creating iterators.
    • Decorators: Writing and applying decorators.
    • Context Managers: Using with statements and creating custom context managers.
    • Concurrency: Introduction to threading, multiprocessing, and async programming.

    12. Working with Data

    • Data Analysis: Introduction to pandas and NumPy for data manipulation.
    • Visualization: Using libraries like Matplotlib and Seaborn for data visualization.
    • APIs: Interacting with web APIs using requests.

    13. Testing and Debugging

    • Debugging Tools: Using pdb and IDE-specific debugging tools.
    • Unit Testing: Writing tests using the unittest framework or pytest.

    14. Web Development

    • Introduction to Web Frameworks: Overview of Flask and Django.
    • Building a Web Application: Create a simple web application using Flask/Django.
    • Working with Databases: Using SQLAlchemy or Django ORM for database interactions.

    15. Project-Based Learning

    • Build Projects: Start with small projects like a to-do list app, a calculator, or a web scraper.
    • Incremental Complexity: Move on to more complex projects like a personal blog, a chatbot, or a data visualization dashboard.

    16. Best Practices

    • Code Readability: Follow PEP 8 guidelines for writing clean and readable code.
    • Version Control: Use Git for version control and GitHub for collaboration.
    • Documentation: Learn to write effective documentation and docstrings.

    17. Continuous Learning

    • Community Engagement: Join Python communities on Stack Overflow, Reddit, or Discord.
    • Stay Updated: Follow Python-related blogs, podcasts, and news.
    • Advanced Resources: Dive into advanced books like “Fluent Python” and “Effective Python.”

    By following this outline, you’ll build a strong foundation in Python and progressively advance your skills through practical application and continuous learning.