Tuesday, 16 December 2025

Python Learning Session-11 Functions, Modules & Packages in Python

 

Functions, Modules & Packages in Python

Reusable, Organized & Scalable Code — A Practical Guide

If you’ve mastered lists, tuples, sets, and dictionaries, the next step is structuring your code. In this guide, we’ll learn how to make your code reusable with functions and organized with modules and packages — the foundation of any production-grade Python project.


Table of Contents

  1. Why Functions?
  2. Defining & Calling Functions
  3. Parameters, Arguments & Return Values
  4. Default, Keyword, *args, **kwargs
  5. Scope, Closures & Lambda
  6. Docstrings & Type Hints
  7. Modules: Importing & Organizing
  8. Packages: Structure & __init__.py
  9. Best Practices & Pitfalls
  10. Mini Project: A Reusable Utility Package
  11. FAQs
  12. Summary & Next Steps

Why Functions?

Functions let you name logic, reuse it, test it independently, and keep code readable.

Benefits

  • Avoid repetition (DRY principle).
  • Encapsulate logic.
  • Easier testing and debugging.
  • Clear inputs/outputs.

Defining & Calling Functions

Python

def greet(name):

"""Return a friendly greeting."""

return f"Hello, {name}!"

 

print(greet("Hitesh")) # Hello, Hitesh!

``

Show more lines

Multiple returns

Python

def divide(a, b):

if b == 0:

return None, "Cannot divide by zero."

return a / b, None

 

result, error = divide(10, 2)

Show more lines


Parameters, Arguments & Return Values

Python

def area_of_rectangle(width: float, height: float) -> float:

return width * height

 

w = 5.0

h = 2.5

print(area_of_rectangle(w, h)) # 12.5

Show more lines

Return dictionaries for structured data

Python

def analyze(numbers):

return {

"count": len(numbers),

"sum": sum(numbers),

"mean": sum(numbers) / len(numbers) if numbers else 0

}

Show more lines


Default, Keyword, *args, **kwargs

Python

def power(base, exponent=2):

return base ** exponent

 

print(power(3)) # 9 (default exponent)

print(power(3, 3)) # 27

print(power(exponent=4, base=2)) # 16

Show more lines

Python

def total(*args):

return sum(args)

 

print

Show more lines

Python

def greet_user(**kwargs):

return f"Hello, {kwargs.get('name', 'Guest')} from {kwargs.get('city', 'Unknown')}!"

 

print(greet_user(name="Hitesh", city="Jafrabad"))

``

Show more lines

Tip: Use *args for flexible positional inputs, **kwargs for flexible named inputs.


Scope, Closures & Lambda

Scope

  • Local: Inside a function.
  • Global: Module-level.
  • Enclosing: Outer function for nested functions.
  • Built-in: Python’s built-ins like len, sum.

Python

x = 10

def foo():

x = 5 # local shadows global

return x

Show more lines

global & nonlocal

Python

count = 0

def increment():

global count

count += 1

``

Show more lines

Python

def outer():

total = 0

def inner():

nonlocal total

total += 1

return total

return inner

``

Show more lines

Lambda (small anonymous functions)

Python

square = lambda x: x**2

print(square(6)) # 36

Show more lines

Use lambdas sparingly; prefer def for readability.


Docstrings & Type Hints

Python

def add(a: int, b: int) -> int:

"""

Add two integers.

 

Args:

a (int): First number.

b (int): Second number.

 

Returns:

int: Sum.

"""

return a + b

Show more lines

Type hints improve clarity and tooling (linters, IDEs). They are optional at runtime.


Modules: Importing & Organizing

A module is any .py file that can be imported.

Import styles

Python

# Basic imports

import math

from math import sqrt, pi

from math import sqrt as square_root

 

# Your own module (file: utils.py)

# utils.py

def slugify(text):

return text.lower().replace(" ", "-")

 

# main.py

from utils import slugify

print(slugify("Hello World")) # hello-world

``

Show less

Code block expanded

Executable modules

Use the common entry point:

Python

# main.py

def run():

print("App started")

 

if __name__ == "__main__":

run()

``

Show more lines


Packages: Structure & __init__.py

A package is a directory with Python modules and (optionally) __init__.py.

myapp/

myapp/

  __init__.py

  utils.py

  mathops/

    __init__.py

    └─ stats.py

main.py

requirements.txt

__init__.py controls what’s exposed

Python

# myapp/mathops/__init__.py

from .stats import mean, median

__all__ = ["mean", "median"]

Show more lines

Relative imports inside packages

Python

# myapp/utils.py

def safe_div(a, b):

return a / b if b else None

 

# myapp/mathops/stats.py

from ..utils import safe_div

 

def mean(values):

return safe_div(sum(values), len(values))

``

Show more lines

Tip: Keep imports explicit and avoid deep relative imports in large projects.


Best Practices & Pitfalls

Do:

  • Keep functions small and single-purpose.
  • Name functions with verbs: calculate_tax, fetch_data.
  • Write docstrings and type hints.
  • Group related functions into modules.
  • Use packages to organize features/domains.

Avoid:

  • Global mutable state (hard to debug).
  • Circular imports (module_a imports module_b and vice versa).
  • Overusing from x import * (namespace pollution).
  • Long parameter lists—prefer objects or dataclasses.

Mini Project: A Reusable Utility Package

Let’s build a simple blogtools package that:

  • Slugifies titles.
  • Estimates reading time.
  • Generates meta tags.
  • Provides text analytics (word stats).

Project Structure

blogtools/

blogtools/

  __init__.py

  meta.py

  text.py

  └─ utils.py

└─ demo.py

blogtools/utils.py

Python

import re

 

def slugify(title: str) -> str:

"""

Convert a title to a URL-friendly slug.

"""

slug = re.sub(r"[^\w\s-]", "", title).strip().lower()

slug = re.sub(r"[\s_-]+", "-", slug)

return slug

``

Show more lines

blogtools/text.py

Python

import math

 

AVERAGE_WPM = 200 # average reading speed

 

def word_count(text: str) -> int:

return len(text.split())

 

def reading_time(text: str) -> str:

minutes = max(1, math.ceil(word_count(text) / AVERAGE_WPM))

return f"{minutes} min read"

 

def summary(text: str, limit: int = 160) -> str:

s = " ".join(text.split())

 

Show more lines

blogtools/meta.py

Python

from .utils import slugify

from .text import reading_time, summary

 

def build_meta(title: str, body: str, tags=None) -> dict:

tags = tags or []

return {

"title": title,

"slug": slugify(title),

"description": summary(body),

"reading_time": reading_time(body),

"tags": tags,

}

``

Show more lines

blogtools/__init__.py

Python

from .meta import build_meta

from .text import word_count, reading_time, summary

from .utils import slugify

 

__all__ = [

"build_meta",

"word_count",

"reading_time",

"summary",

"slugify",

]

``

Show more lines

demo.py

Python

from blogtools import build_meta, slugify, reading_time

 

post_title = "Functions, Modules & Packages in Python — A Practical Guide"

post_body = """

Functions help you reuse code, while modules and packages help you organize it.

This guide walks through the essentials with examples and a mini project.

"""

 

meta = build_meta(post_title, post_body, tags=["Python", "Tutorial", "Beginner"])

print("Slug:", meta["slug"])

print("Reading Time:", meta["reading_time"])

print("Description:", meta["description"])

Show more lines

How to run: Place files as shown, then run python demo.py.


FAQs

Q1. Do I need __init__.py in every package?
A: In modern Python, namespace packages can work without it, but including __init__.py keeps behavior explicit and compatible across tools.

Q2. When should I use a module vs a package?
A: Use a module for a small set of related functions. Use a package when you need multiple modules grouped by feature/domain.

Q3. How do I avoid circular imports?
A: Move shared functions into a common module, import inside functions when needed, or refactor dependencies.


Summary & Next Steps

  • Functions: Make your logic reusable, testable, and clear.
  • Modules: Group related functions and keep files focused.
  • Packages: Organize features into a scalable structure.

Next: Add unit tests (pytest), use virtual environments (venv), and publish your package to PyPI.


Bonus: Copy-Paste Blog Intro (Social Caption)

Learn how to write clean, reusable Python with functions, and organize it like a pro using modules & packages. Includes examples, best practices, and a mini project you can run today. #Python #Coding #DevTips

 

Monday, 15 December 2025

Python Learning Session-10 : Dictionaries in Python –from lists, tuples and Key-Value Power!.

 

Session-10 : Dictionaries in Python –from lists, tuples and Key-Value Power!.

Learning Objectives

  • Understand what sets are in Python.
  • Learn how sets differ from lists and tuples.
  • Explore set operations (union, intersection, difference, symmetric difference).
  • Work with set methods like add(), remove(), discard(), update().
  • Understand immutability with frozenset.

📌 Key Concepts

  1. Definition:
    A set is an unordered collection of unique elements in Python.
    Example:

Python

my_set = {1, 2, 3, 3} # Output: {1, 2, 3}

Show more lines

  1. Why Sets?
    • Automatically removes duplicates.
    • Faster membership testing (in operator).
    • Useful for mathematical operations.
  2. Creating Sets:

Python

s1 = {1, 2, 3}

s2 = set([4, 5, 6])

empty_set = set() # {} creates a dictionary, not a set

 

Show more lines

  1. Common Operations:

Python

a = {1, 2, 3}

b = {3, 4, 5}

 

print(a | b) # Union: {1, 2, 3, 4, 5}

print(a & b) # Intersection: {3}

print(a - b) # Difference: {1, 2}

print(a ^ b) # Symmetric Difference: {1, 2, 4, 5}

Show more lines

  1. Methods:
    • add(), remove(), discard(), pop(), clear()
    • update() for merging sets.
  2. frozenset:
    • Immutable version of a set.

Python

fs = frozenset([1, 2, 3])

Show more lines


🛠 Practice Ideas

  • Remove duplicates from a list using a set.
  • Find common elements between two lists.
  • Write a program to check if two sets are disjoint.
  • Implement a simple set-based membership system.

Key-Value Power


Learning Objectives

  • Understand what dictionaries are and why they are useful.
  • Learn how to create, access, and modify dictionary elements.
  • Explore dictionary methods like get(), keys(), values(), items(), update().
  • Understand nested dictionaries and dictionary comprehensions.

📌 Key Concepts

  1. Definition:
    A dictionary is an unordered collection of key-value pairs.
    Example:

Python

my_dict = {"name": "Hitesh", "role": "Engineer"}

Show more lines

  1. Creating Dictionaries:

Python

d1 = {"a": 1, "b": 2}

d2 = dict(x=10, y=20)

empty_dict = {}

Show more lines

  1. Accessing & Modifying:

Python

print(d1["a"]) # 1

print(d1.get("c")) # None

d1["b"] = 5 # Modify value

d1["c"] = 3 # Add new key-value

Show more lines

  1. Common Methods:
    • keys(), values(), items()
    • update(), pop(), clear()
  2. Dictionary Comprehension:

Python

squares = {x: x**2 for x in range(5)}

Show more lines

  1. Nested Dictionaries:

Python

student = {

"name": "Hitesh",

"marks": {"math": 90, "science": 85}

 

Show more lines


🛠 Practice Ideas

  • Count word frequency in a sentence using a dictionary.
  • Merge two dictionaries.
  • Create a dictionary from two lists (keys and values).
  • Implement a simple phonebook using a dictionary.

 

Saturday, 13 December 2025

Python Learning Session-09: Tuples in Python – Immutable Collections!

 

Python Learning Session-09: Tuples in Python – Immutable Collections!


👋 Welcome Back!

We’ve learned about lists, which are flexible and allow changes. But what if you need a collection that should never change? That’s where Tuples come in. Tuples are like lists, but with one big difference: they are immutable.


What is a Tuple?

A tuple is an ordered collection of items, just like a list, but you cannot modify it after creation.

Why use tuples?

  • Protect data from accidental changes.
  • Faster than lists (because they’re immutable).
  • Commonly used for fixed data like coordinates, dates, or configuration settings.

Creating Tuples

Tuples use parentheses ():

Python

# Example of a tuple

colors = ("red", "green", "blue")

print(colors)

Show more lines

You can also create a tuple without parentheses:

Python

numbers = 1, 2, 3

Show more lines


Accessing Tuple Elements

Just like lists, tuples use indexing:

Python

print(colors[0]) # red

print(colors[-1]) # blue

Show more lines


Immutability in Action

Try changing a tuple:

Python

colors[0] = "yellow" # Error: 'tuple' object does not support item assignment

Show more lines

Why important? Tuples are perfect for data that should remain constant.


Tuple Operations

  • Concatenation

Python

tuple1 = (1, 2)

tuple2 = (3, 4)

print(tuple1 + tuple2) # (1, 2, 3, 4)

Show more lines

  • Repetition

Python

print(tuple1 * 3) # (1, 2, 1, 2, 1, 2)

Show more lines


Looping Through Tuples

Python

for color in colors:

print(color)

Show more lines


Tuple Methods

  • count(value) → Count occurrences
  • index(value) → Find position of value

Python

numbers = (1, 2, 2, 3)

print(numbers.count(2)) # 2

print(numbers.index(3)) # 3

Show more lines


Nested Tuples

Tuples can contain other tuples:

Python

nested = ((1, 2), (3, 4))

print(nested[0][1]) # 2

Show more lines


Summary

Tuples are simple, fast, and secure. Use them when you need fixed data that should never change.


🔥 Challenge for You

Create a tuple of 5 cities. Print them one by one. Then, try adding a new city and see what happens!


👉 Next Session: Session-10: Sets in Python – Unique Collections!

 

Friday, 12 December 2025

Python Learning Session-08: Dictionaries in Python – Key-Value Magic!

 

Python Learning Session-08: Dictionaries in Python – Key-Value Magic!


👋 Welcome Back!

We’ve explored lists, which are great for storing ordered collections. But what if you need to store data with labels? For example, a student’s name and their marks. Lists can do it, but it’s messy. Enter Dictionaries—Python’s way of storing data as key-value pairs.


 What is a Dictionary?

A dictionary is like a real-life dictionary: you look up a word (key) and get its meaning (value). In Python:

  • Keys are unique
  • Values can be anything (numbers, strings, lists, even another dictionary)
  • Defined using curly braces {}

Example:

Python

student = {

"name": "Alice",

"age": 21,

"marks": 85

}

print(student)

Show more lines

Output:

{'name': 'Alice', 'age': 21, 'marks': 85}

 Why useful? Perfect for structured data like user profiles, product details, etc.


 Creating Dictionaries

Python

# Empty dictionary

my_dict = {}

 

# Dictionary with data

 

Show more lines


 Accessing Values

Use the key:

Python

print(student["name"]) # Alice

Show more lines

 Pro Tip: If you use a key that doesn’t exist, Python throws an error. Use get() to avoid that:

Python

print(student.get("grade", "Not Available"))

Show more lines


 Adding & Updating Data

Python

student["grade"] = "A" # Add new key-value

student["marks"] = 90 # Update existing value

Show more lines


 Removing Data

  • pop() → Remove by key

Python

student.pop("age")

Show more lines

  • clear() → Remove all items

Python

student.clear()

Show more lines


 Looping Through Dictionaries

Python

for key, value in student.items():

print(key, ":", value)

Show more lines

 Real-world example: Displaying user details in a profile page.


 Dictionary Methods You’ll Love

  • keys() → All keys
  • values() → All values
  • items() → All key-value pairs

Example:

Python

print(student.keys())

print(student.values())

Show more lines


 Nested Dictionaries

Dictionaries inside dictionaries:

Python

students = {

"101": {"name": "Alice", "marks": 85},

"102": {"name": "Bob", "marks": 78}

}

print(students["101"]["name"]) # Alice

Show more lines

 Why powerful? Great for storing complex data like JSON.


 Summary

Dictionaries are the backbone of Python data handling. They’re fast, flexible, and perfect for real-world applications like APIs, databases, and configurations.


🔥 Challenge for You

Create a dictionary of 5 countries and their capitals. Then:

  • Print all keys and values
  • Add a new country
  • Remove one country

👉 Next Session: Session-09: Tuples in Python – Immutable Collections!

 


Monday, 8 December 2025

Python Learning Session-07: Working with Lists

Python Learning Session-07: Working with Lists


👋 Welcome Back!

If you’ve been following our Python journey, you already know how to work with strings. Today, we’re stepping into one of the most powerful tools in Python: Lists.

Think of a list like a shopping basket. You can throw in apples, bananas, and even a bottle of juice—all in one basket. Similarly, Python lists can hold multiple items, even of different types.


What is a List?

A list is a collection of items stored in a single variable. It’s like a container that keeps things organized.

Example:

Python

fruits = ["apple", "banana", "cherry"]

print(fruits)

Show more lines

Output:

['apple', 'banana', 'cherry']


Why Do We Need Lists?

Imagine you’re building a student management system. Instead of creating 100 variables for 100 students, you can store all names in one list. Simple, right?


Creating Lists

Python

numbers = [1, 2, 3, 4, 5]

mixed = [1, "hello", 3.14, True]

empty_list = []

Show more lines

Pro Tip: Lists can hold anything—numbers, strings, even other lists!


Accessing Items

Lists use indexing:

Python

fruits = ["apple", "banana", "cherry"]

print(fruits[0]) # apple

print(fruits[-1]) # cherry

Show more lines

Why important? Indexing helps you grab exactly what you need.


Updating Lists

Lists are mutable, meaning you can change them:

Python

fruits[1] = "orange"

print(fruits) # ['apple', 'orange', 'cherry']

Show more lines

Real-life example: Updating a product name in your online store.


Adding Items

  • append() → Add at the end

Python

fruits.append("grape")

Show more lines

  • insert() → Add at a specific position

Python

fruits.insert(1, "mango")

Show more lines

Why useful? Dynamic data handling without creating new lists.


Removing Items

  • remove() → Remove by value

Python

fruits.remove("apple")

Show more lines

  • pop() → Remove by index

Python

fruits.pop(0)

 

Show more lines

Use case: Removing sold-out items from inventory.


Looping Through Lists

Python

for fruit in fruits:

print(fruit)

Show more lines

Practical example: Displaying all items in a shopping cart.


List Comprehension

A smart way to create lists:

Python

squares = [x**2 for x in range(5)]

print(squares) # [0, 1, 4, 9, 16]

Show more lines

Why powerful? Less code, more clarity.


Summary

Lists are your best friend when you need to store and manage multiple values. They’re flexible, easy to use, and form the backbone of Python programming.


🔥 Challenge for You

Create a list of your favorite movies and print them one by one using a loop. Then, add a new movie to the list and remove one you don’t like anymore.

 


Tuesday, 5 March 2024

Python Learning Session –06 - Sting Data Type

string data type in Python:

  introduction about the string data type in python 

String is nothing but is only set of character i.e “Techshoot03” it set of alphabet characters “ T,e,c,h,s,h,o,o,0,3 ” . All the set of character are get to gather and make one word and set of words are call String.

 There are so many Data type are available in the programing all languages are same data type are used

 Lest we seen how many data type are available in programing.

·         Intrigue

·         Boolean

·         String

·         Double

·         Float

·         Complex

·         List

·         Tuple

·         Dict

·         Set

“Mastering Python Strings: A Comprehensive Guide”

Dive deep into string manipulation, slicing, and formatting techniques.

Cover common use cases and best practices for handling strings.

 

“Python String Methods Every Developer Should Know”

Explore essential string methods like split()join()replace(), and more.

Provide practical examples and tips for efficient string processing.

 

“Formatting Strings in Python: A Detailed Overview”

Discuss f-strings, .format(), and % formatting.

Explain when to use each method and their pros/cons.

 

“Exploring Python’s Built-in String Functions”

Highlight lesser-known string functions like isalpha()startswith(), and count().

Showcase their applications and performance considerations.

 

“String Manipulation in Python: Tips and Tricks for Efficiency”

Share tricks for optimizing string concatenation, searching, and case conversion.

Address memory usage and performance bottlenecks.

 

Example : -

Code : - a = “hello techshoot03”

Print (a)                   --  then press the enter and check the result as we seen in the snap

 Looking Inside Strings :

We can get at any single character in a string using an index specified in square brackets

The index value must be an integer and starts at zero

The index value can be an expression that is computed

Lest we more undartanding we go throw the code :

Code : -

>>> a = "hello Techshoot03"

>>> print ( a )

hello Techshoot03

>>> 

>>> a = 3

>>> b = a [a-1]

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'int' object is not subscriptable

>>> demo = "hello techshoot03"

>>> test = demo[1]

>>> print (test)

e

>>> a = 3

>>> b = demo[a-1]

>>> print(b)

l

>>> 

The built-in function len gives us the length of a string

Code : -

 >>> demo = "hello techshoot03"

>>> print(len(demo))

17

>>> 


LEN A function is some stored code that we use. A function takes some input and produces an output.

Looping and Counting of Strings : -

This is a simple loop that loops through each letter in a string and counts the number of times the loop encounters the 'a' character

Slicing Strings: -

We can also look at any continuous section of a string using a colon operator

The second number is one beyond the end of the slice – “up to but not including”

If the second number is beyond the end of the string, it stops at the end

If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively

 When the  +  operator is applied to strings, it means “concatenation”



The in keyword can also be used to check to see if one string is “in” another string

The in expression is a logical expression that returns True or False and can be used in an if statement



String Comparison :




String Library: -

·         str.capitalize()

·         str.center(width[, fillchar])

·         str.endswith(suffix[, start[, end]])

·         str.find(sub[, start[, end]])

·         str.lstrip([chars])

·         str.replace(old, new[, count])

·         str.lower()

·         str.rstrip([chars])

·         str.strip([chars])

·         str.upper()

Searching a String : -

We use the find() function to search for a substring within another string

find() finds the first occurrence of the substring

If the substring is not found, find() returns -1

Remember that string position starts at zero

 

Code : -

>>>demo = 'Techshoot03'

>>> test = demo.find('Te')

>>> print(test)

1 - --  Result

 

You can make a copy of a string in lower case or upper case

Often when we are searching for a string using find() we first convert the string to lower case so we can search a string regardless of case

The replace() function is like a “search and replace” operation in a word processor

It replaces all occurrences of the search string with the replacement string

Sometimes we want to take a string and remove whitespace at the beginning and/or end

lstrip() and rstrip() remove whitespace at the left or right

strip() removes both beginning and ending whitespace

 

Tuesday, 20 February 2024

Python Learning Session –05- Loops and Iteration

 

Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

Loops (repeated steps) have iteration variables that change each time through a loop.  Often these iteration variables go through a sequence of numbers.

There are so many type of looping statement are available to doing various operations

 

Python has two primitive loop commands:

  • while loops
  • for loops

 

While Loops Are:

·         The while Loop

·         The break Statement

·         The continue Statement

·         The else Statement

For Loops Are: -

·         Looping Through a String

·         The break Statement

·         The continue Statement

·         The range() Function

·         Else in For Loop

·         Nested Loops

·         The pass Statement

  

lest we first understand with use case diagram the how the loop works:

 




 

 

Lest we understanding the all of methods one by one in brief are mentioned here

1)     While Loop :

 

The while loop are used in conditional looping i.e when the condition are true then executed the set of statement are alog with condition are masoned

 

Lest we more getting clearance about the syntax of the while loop

 

Code:-

 

x = 1

while x < 5:

print (x)

x += 1




·         The break Statement:

 

·         The break statement ends the current loop and jumps to the statement immediately following the loop

·         It is like a loop test that can happen anywhere in the body of the loop

Code : -

 

while True:

    line = input('> ')

    if line == 'done' :

        break

    print(line)

print(“Done!”)

 

lest we understand with use case diagram how the code is work,

 



The continue Statement : -

 

With the continue statement we can stop the current iteration, and continue with the next: The continue statement ends the current iteration and jumps to the top of the loop and starts the next iteration

Code : -

 

while True:

    line = input('> ')

    if line[0] == '#' :

        continue

    if line == 'done' :

        break

    print(line)

print('Done!')

 

 

lest we understand the continue loops is work

 



·         The else Statement :  ( Repeated Steps )

 

With the else statement we can run a block of code once when the condition no longer is true:

Loops (repeated steps) have iteration variables that change each time through a loop.  Often these iteration variables go through a sequence of numbers.

 

Code :

 

n = 5

while n > 0 :

    print(n)

    n = n – 1

print('Techshoot03!')

print(n)

 

 

 

Indefinite Loops : -

 

         While loops are called “indefinite loops” because they keep going until  a logical condition becomes False

         The loops we have seen so far are pretty easy to examine to see if they will terminate or if they will be “infinite loops”

         Sometimes it is a little harder to be sure if a loop will terminate

 

 

 

         Quite often we have a list of items of the lines in a file - effectively a finite set of things

         We can write a loop to run the loop once for each of the items in a set using the Python for construct

         These loops are called “definite loops” because they execute an exact number of times

 

A Definite Loop with Strings: -

 

In the type of the program user the String value instant of any logic or any of characters ( Special character , numbers )

 

 

 

Code : -

 

frnd = ["encky""mincky""chincky"]
for in frnd:
  
print(x)

The range() Function :

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Using the range() function:

Code: -

for x in range(9):
  print
(x)

 

The is and is not Operators

         Python has an is operator that can be used in logical expressions

         Implies “is the same as”

         Similar to, but stronger than ==

         is not  also is a logical operator

 

Code : -

smallest = None

print('Before')

for value in [13, 141, 112, 19, 714, 115] :

    if smallest is None :

        smallest = value

    elif value < smallest :

        smallest = value

    print(smallest, value)

print('After', smallest)