0% found this document useful (0 votes)
2 views36 pages

Python Loop Example

The document provides various examples of Python loops, including for and while loops, and demonstrates how to create interactive scripts like a name game and password prompts with limited attempts. It also covers basic Python concepts such as functions, conditionals, and lists, along with some common commands for using Python in the Termux environment. Additionally, it includes a script that collects user information such as name, sex, and age.
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)
2 views36 pages

Python Loop Example

The document provides various examples of Python loops, including for and while loops, and demonstrates how to create interactive scripts like a name game and password prompts with limited attempts. It also covers basic Python concepts such as functions, conditionals, and lists, along with some common commands for using Python in the Termux environment. Additionally, it includes a script that collects user information such as name, sex, and age.
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

3/13/26, 8:38 PM Python Loop Example

Loop name in python

In Python, you can loop over a sequence of items using a for loop. Here's how you can
loop over a list of names, for example:

names = ["Alice", "Bob", "Charlie", "David"]

for name in names:


print(name)

This will output each name in the list names on a new line. If you have a different context
or specific task in mind, feel free to provide more details!

Print loop in python

Here’s an example of how to print numbers in a loop using Python:

Using a for loop:

for i in range(1, 6): # This will loop through numbers 1 to 5


print(i)
Python Run

Using a while loop:

i = 1
while i <= 5: # This will loop while i is less than or equal to 5

[Link] 1/36
3/13/26, 8:38 PM Python Loop Example
print(i)
i += 1
Python Run

Both of these examples will print:

1
2
3
4
5

Print name game in python

If you want to create a name-based game in Python, here's an example of a simple "Name
Game" where it asks for the player's name and repeats it in a fun way:

# Name Game
name = input("Enter your name: ")

# Simple game logic to print the name in a fun way


print(f"{name}, {name}, bo-b{name[1:]}")
print(f"Banana-fana fo-f{name[1:]}")
print(f"Fee-fi-mo-m{name[1:]}")
print(f"{name}!")

Sample Output:
If the user inputs the name "Alice," the output will be:

Alice, Alice, bo-blice


Banana-fana fo-flice
Fee-fi-mo-mlice
Alice!

This game is based on the classic "Name Game" song, where you playfully rhyme the
name. You can modify it or add more complexity depending on how you want to
[Link] 2/36
3/13/26, 8:38 PM Python Loop Example

structure the game!

If answer in python is correct Goto

Python scripts

In Python, there's no built-in goto statement, but you can achieve similar functionality
using functions, loops, and conditionals. Here’s how you can structure your Python script
to "go to" a certain part of the code if a condition is met:

Example 1: Using functions to "goto"


You can use functions to simulate a goto by calling specific sections of your code:

def section1():
answer = input("What is 5 + 3? ")
if answer == "8":
print("Correct! Going to section 2...")
section2() # This simulates a goto to section2
else:
print("Incorrect! Try again.")
section1()

def section2():
print("Welcome to section 2!")
# Continue the game or logic here

section1() # Start at section 1

Example 2: Using a while loop for "goto"-like behavior


You can also use loops to control the flow of the script:

correct = False

[Link] 3/36
3/13/26, 8:38 PM Python Loop Example
while not correct:
answer = input("What is 5 + 3? ")
if answer == "8":
print("Correct! Moving to the next section.")
correct = True # Exit the loop and "go to" the next part
else:
print("Incorrect, try again.")

# This is the next section


print("You made it to the next section!")

This way, you can direct the flow of your program based on conditions without needing a
goto statement. Python encourages using these structures instead of the goto
programming pattern, which is considered bad practice in most modern programming
languages.

2/2

Correct = false while not=correct examples with 3


attempts

Here's an example of a Python script that gives the user three attempts to provide the
correct answer using a while loop. If the user fails after three attempts, it exits the loop:

# Initialize variables
correct = False
attempts = 0
max_attempts = 3

while not correct and attempts < max_attempts:


answer = input("What is 5 + 3? ")
if answer == "8":
print("Correct! Moving to the next section.")
correct = True
else:
attempts += 1
print(f"Incorrect! You have {max_attempts - attempts} attempts lef

[Link] 4/36
3/13/26, 8:38 PM Python Loop Example
if not correct:
print("Sorry, you've used all your attempts.")

Explanation:
correct = False starts the loop with the assumption that the answer is wrong.
The while not correct and attempts < max_attempts: loop continues until the
answer is correct or the user uses all three attempts.
If the user inputs the correct answer ("8"), the correct variable is set to True , and
the loop breaks.
If the answer is wrong, the attempts variable increments, and the loop tells the
user how many attempts they have left.
If all attempts are used without a correct answer, the script prints a message saying
they've used all their attempts.

Sample Output:

What is 5 + 3? 7
Incorrect! You have 2 attempts left.
What is 5 + 3? 6
Incorrect! You have 1 attempt left.
What is 5 + 3? 8
Correct! Moving to the next section.

Password with 3 attempts

Password with 3 attempts python

Here’s an example of a Python script that asks

Password with 3 attempts python

[Link] 5/36
3/13/26, 8:38 PM Python Loop Example

Here’s an example of a Python script that prompts the user for a password with only 3
attempts. If the correct password is entered within the attempts, access is granted;
otherwise, access is denied after 3 incorrect tries:

# Set the correct password


correct_password = "mysecretpassword"
attempts = 0
max_attempts = 3

# Start the loop


while attempts < max_attempts:
# Ask the user for the password
password = input("Enter the password: ")

# Check if the password is correct


if password == correct_password:
print("Access granted!")
break # Exit the loop
else:
attempts += 1
print(f"Incorrect password! You have {max_attempts - attempts} att

# If the user has used all attempts, deny access


if attempts == max_attempts:
print("Access denied. You've used all attempts.")

Explanation:
The correct password is set as "mysecretpassword" .
The while loop runs as long as the user hasn't exhausted the 3 attempts.
If the correct password is entered, the program prints "Access granted!" and breaks
out of the loop.
If the wrong password is entered, it increments the attempts counter and informs
the user how many attempts remain.
After 3 incorrect attempts, the loop exits and prints "Access denied."

Sample Output:

[Link] 6/36
3/13/26, 8:38 PM Python Loop Example

Enter the password: wrongpassword


Incorrect password! You have 2 attempts left.
Enter the password: notright
Incorrect password! You have 1 attempt left.
Enter the password: mysecretpassword
Access granted!

This structure ensures the user has 3 tries to enter the correct password.

Python examples

Here are a few basic Python examples demonstrating common concepts like loops,
conditionals, functions, and lists.

1. Simple Loop Example:

# Print numbers from 1 to 5


for i in range(1, 6):
print(i)

Output:

1
2
3
4
5

2. If-Else Example:

# Check if a number is positive, negative, or zero


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

if number > 0:
[Link] 7/36
3/13/26, 8:38 PM Python Loop Example
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")

Sample Output:

Enter a number: -3
The number is negative.

3. Function Example:

# A function to calculate the square of a number


def square(num):
return num * num

# Using the function


result = square(4)
print(f"The square of 4 is {result}")

Output:

The square of 4 is 16

4. List Example:

# A list of fruits
fruits = ["apple", "banana", "cherry"]

# Looping through the list


for fruit in fruits:
print(fruit)

Output:

apple
banana

[Link] 8/36
3/13/26, 8:38 PM Python Loop Example
cherry

5. While Loop Example:

Python Run

# Countdown using a while loop


count = 5
while count > 0:
print(count)
count -= 1

print("Liftoff!")

Output:

5
4
3
2
1
Liftoff!

6. Password Input with 3 Attempts:

Python Run

# Password input with 3 attempts


correct_password = "mypassword"
attempts = 0
max_attempts = 3

while attempts < max_attempts:


password = input("Enter password: ")
if password == correct_password:
print("Access granted!")
break
else:
attempts += 1
print(f"Wrong password! {max_attempts - attempts} attempts left.")

if attempts == max_attempts:
print("Access denied!")

[Link] 9/36
3/13/26, 8:38 PM Python Loop Example

Output:

Enter password: wrongpass


Wrong password! 2 attempts left.
Enter password: wrongpass
Wrong password! 1 attempt left.
Enter password: mypassword
Access granted!

These examples cover various Python concepts. Let me know if you'd like more specific
examples!

Python list examples

Termux cmd

Here are some basic and commonly used commands for Termux, a terminal emulator and
Linux environment app for Android:

1. Basic Navigation Commands:


List files and directories:

Bash

ls

Change directory:

Bash

cd /path/to/directory

Print current working directory:

Bash

pwd

[Link] 10/36
3/13/26, 8:38 PM Python Loop Example

Create a new directory:

Bash

mkdir directory_name

2. File Management:
Create a new file:

Bash

touch [Link]

View file content:

Bash

cat [Link]

Remove a file:

Bash

rm [Link]

Move or rename a file:

Bash

mv old_filename.txt new_filename.txt

Copy a file:

Bash

cp [Link] /path/to/destination/

3. Package Management:
Update package list:

Bash

[Link] 11/36
3/13/26, 8:38 PM Python Loop Example
pkg update

Upgrade installed packages:

Bash

pkg upgrade

Install a package:

Bash

pkg install package_name

Search for a package:

Bash

pkg search package_name

4. Networking:
Check IP address:

Bash

ifconfig

ChatGPT Get Plus


Ping a website or IP:

Bash

ping [Link]

Download a file using wget :

Bash

wget [Link]

5. Text Editors:
Edit a file using nano :

[Link] 12/36
3/13/26, 8:38 PM Python Loop Example

Bash

nano [Link]

Edit a file using vim :

Bash

vim [Link]

6. Python in Termux:
Install Python:

Bash

pkg install python

Run a Python script:

Bash

python script_name.py

Start the Python interpreter:

Bash

python

7. Permissions:
Grant storage permissions (needed to access internal storage):

Bash

termux-setup-storage

This command will request storage access permission and create a directory at
/data/data/[Link]/files/home/storage/ that links to the device's storage.

8. Help:
To display help for any command, use:

[Link] 13/36
3/13/26, 8:38 PM Python Loop Example

Bash

command_name --help

These are just a few of the many commands available in Termux. Termux acts as a
lightweight Linux terminal, so most standard Linux commands will work.

What is your name ,sex, and age in python script

Here’s a Python script that asks for your name, sex, and age and then prints the
information:

Python Run

# Ask for user input


name = input("What is your name? ")
sex = input("What is your sex (M/F)? ")
age = input("How old are you? ")

# Print the information


print("\nHere is the information you provided:")
print(f"Name: {name}")
print(f"Sex: {sex}")
print(f"Age: {age}")

Sample Output:

What is your name? Alice


What is your sex (M/F)? F
How old are you? 25

Here is the information you provided:


Name: Alice
Sex: F
Age: 25

This script gathers input from the user, stores it in variables, and then prints out the
information.
[Link] 14/36
3/13/26, 8:38 PM Python Loop Example

What is your name ,sex, and age , are you from


Washington yes or no if yes print to bad in python script

Here's a Python script that asks for your name, sex, age, and whether you're from
Washington. If the answer is "yes," it prints "Too bad."

Python Run

# Ask for user input


name = input("What is your name? ")
sex = input("What is your sex (M/F)? ")
age = input("How old are you? ")
from_washington = input("Are you from Washington? (yes/no): ")

# Print the information


print("\nHere is the information you provided:")
print(f"Name: {name}")
print(f"Sex: {sex}")
print(f"Age: {age}")

# Check if the user is from Washington


if from_washington.lower() == "yes":
print("Too bad.")
else:
print("Nice to meet you!")

Sample Output:

What is your name? John


What is your sex (M/F)? M
How old are you? 30
Are you from Washington? yes

Here is the information you provided:


Name: John
Sex: M
Age: 30
Too bad.

[Link] 15/36
3/13/26, 8:38 PM Python Loop Example

Explanation:
The script first collects user input for their name, sex, age, and whether they are
from Washington.
It then checks if the answer to the Washington question is "yes" (case-insensitive),
and if so, it prints "Too bad."
If the answer is "no," it prints a friendly message, "Nice to meet you!"

What's is your first name


What is your middle name
What is your last name
What is your sex male/female
If male print
Why not Hommie
Do you eat pussy
If female print
Do you suck dick
If not print
Why not it's good
Are you from Washington
If no print To Bad
If yes print where about
If Spokane print The Trap
Else print That's coo
Do you know what's the Dopest? Yes or No
If yes print
What is the Dopest Then
If answer is DopeDick
Print Very Good
Elif print to bad
In python script

Here's a Python script that incorporates all of your requirements, asking for name details,
sex, and additional questions based on the user's input:

[Link] 16/36
3/13/26, 8:38 PM Python Loop Example

Python Run

# Ask for user's name and sex


first_name = input("What is your first name? ")
middle_name = input("What is your middle name? ")
last_name = input("What is your last name? ")
sex = input("What is your sex (male/female)? ").lower()

# Check the user's sex and ask the appropriate question


if sex == "male":
print("Why not, Hommie?")
eats_pussy = input("Do you eat pussy? (yes/no): ").lower()
if eats_pussy == "no":
print("Why not? It's good!")
elif sex == "female":
print("Do you suck dick?")
sucks_dick = input("Yes or No: ").lower()
if sucks_dick == "no":
print("Why not? It's good!")

# Ask if the user is from Washington


from_washington = input("Are you from Washington? (yes/no): ").lower()

if from_washington == "no":
print("Too bad.")
else:
location = input("Where about in Washington? ")
if [Link]() == "spokane":
print("The Trap.")
else:
print("That's coo.")

# Ask about the Dopest


knows_dopest = input("Do you know what's the Dopest? (yes/no): ").lower()

if knows_dopest == "yes":
dopest_answer = input("What is the Dopest then? ")
if dopest_answer.lower() == "dopedick":
print("Very Good!")
else:
print("Too bad.")
else:
print("Too bad.")

Explanation:

[Link] 17/36
3/13/26, 8:38 PM Python Loop Example

1. Name and Sex Input: The script first collects the user's first, middle, and last names,
followed by asking the user's sex.
2. Conditional Questions Based on Sex:
If the user is male, it asks if they eat pussy. If they respond "no," it prints a
follow-up response.
If the user is female, it asks if they suck dick. If the response is "no," it also prints
a follow-up response.
3. Washington Check:
If the user is from Washington, it asks for their location. If the user specifies
"Spokane," it prints "The Trap." Otherwise, it prints "That's coo."
If they’re not from Washington, it prints "Too bad."
4. Dopest Question: It asks if the user knows what's the "Dopest." If they say yes and
respond with "DopeDick," it prints "Very Good." Otherwise, it prints "Too bad."

Sample Output:

What is your first name? John


What is your middle name? Michael
What is your last name? Doe
What is your sex (male/female)? male
Why not, Hommie?
Do you eat pussy? (yes/no): no
Why not? It's good!
Are you from Washington? (yes/no): yes
Where about in Washington? Spokane
The Trap.
Do you know what's the Dopest? (yes/no): yes
What is the Dopest then? DopeDick
Very Good!

This script combines various checks and responses based on the user’s input, making it
interactive as per your request.

nmap with python

[Link] 18/36
3/13/26, 8:38 PM Python Loop Example

To use Nmap (a popular network scanning tool) with Python, you can utilize the python-
nmap library. This library allows you to automate network scanning with Nmap directly
from Python scripts.

Installation
1. First, install Nmap on your system (if not already installed). On Linux, use:

Bash

sudo apt-get install nmap

2. Next, install the python-nmap package using pip:

Bash

pip install python-nmap

Example of Using Nmap with Python:


Here’s a Python script that uses python-nmap to scan an IP or a range of IPs and prints
the scan results.

Python Run

import nmap

# Create an nmap scanner object


nm = [Link]()

# Scan a specific IP or range of IPs


ip_to_scan = input("Enter the IP address or range to scan: ")
print(f"Scanning {ip_to_scan}...\n")

# Perform the scan


[Link](ip_to_scan, '1-1024') # Scanning ports 1-1024

# Loop through all hosts found


for host in nm.all_hosts():
print(f"Host: {host} ({nm[host].hostname()})")
print(f"State: {nm[host].state()}")

# Loop through all protocols


for proto in nm[host].all_protocols():
print(f"\nProtocol: {proto}")

[Link] 19/36
3/13/26, 8:38 PM Python Loop Example
# Get the list of open ports for the protocol
ports = nm[host][proto].keys()
for port in ports:
print(f"Port: {port}, State: {nm[host][proto][port]['state']}"

Explanation:
The script starts by importing the nmap module and creating a PortScanner object.
The user is prompted to input an IP address or range (e.g., [Link]/24 ).
The script scans ports 1-1024 on the target(s).
It then prints out the state (open/closed) of each port.

Sample Output:

Enter the IP address or range to scan: [Link]


Scanning [Link]...

Host: [Link] (router)


State: up

Protocol: tcp
Port: 22, State: open
Port: 80, State: open
Port: 443, State: open

Scan Options:
You can modify the scan command [Link](ip_to_scan, '1-1024') to include
various Nmap options such as:
-sP for a ping scan (host discovery).

-O for OS detection.

-sV for version detection.

Example: OS Detection with Nmap

Python Run

[Link](ip_to_scan, arguments='-O')
if 'osclass' in nm[ip_to_scan]:
for osclass in nm[ip_to_scan]['osclass']:
print(f"OS Type: {osclass['osfamily']}")

[Link] 20/36
3/13/26, 8:38 PM Python Loop Example

Notes:
You need to have Nmap installed on your system for this to work.
Running Nmap with elevated permissions may be necessary for some types of scans.

This script helps automate Nmap scans using Python, providing an easy way to integrate
network discovery or security checks into larger Python projects.

python codes

Here are some basic Python code examples covering various concepts like loops,
conditionals, functions, and working with files.

1. Simple Calculator
A basic calculator using if statements to perform arithmetic operations.

Python Run

# Simple Calculator
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
result = num1 / num2
else:
result = "Invalid operator"

print("Result:", result)

[Link] 21/36
3/13/26, 8:38 PM Python Loop Example

2. Factorial of a Number
A function to calculate the factorial of a number using recursion.

Python Run

# Function to calculate factorial


def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

# Example usage
num = int(input("Enter a number: "))
print("Factorial:", factorial(num))

3. FizzBuzz
Prints numbers from 1 to 100, but:
For multiples of 3, prints "Fizz" instead.
For multiples of 5, prints "Buzz" instead.
For multiples of both 3 and 5, prints "FizzBuzz".

Python Run

for i in range(1, 101):


if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)

4. Palindrome Checker
Checks if a word is a palindrome (reads the same forwards and backwards).

[Link] 22/36
3/13/26, 8:38 PM Python Loop Example

Python Run

# Function to check for palindrome


def is_palindrome(word):
return word == word[::-1]

# Example usage
word = input("Enter a word: ")
if is_palindrome(word):
print(f"{word} is a palindrome!")
else:
print(f"{word} is not a palindrome.")

5. Reading and Writing to a File


Writes to a file and then reads the contents back.

Python Run

# Writing to a file
with open("[Link]", "w") as file:
[Link]("Hello, this is an example file.\nWelcome to Python program

# Reading from a file


with open("[Link]", "r") as file:
content = [Link]()
print(content)

6. List Comprehensions
An example of generating a list of squares from 1 to 10 using list comprehension.

Python Run

# List of squares from 1 to 10


squares = [x**2 for x in range(1, 11)]
print("Squares from 1 to 10:", squares)

7. Random Password Generator


[Link] 23/36
3/13/26, 8:38 PM Python Loop Example

Generates a random password of specified length.

Python Run

import random
import string

# Function to generate a random password


def generate_password(length):
characters = string.ascii_letters + [Link] + [Link]
password = ''.join([Link](characters) for i in range(length))
return password

# Example usage
length = int(input("Enter password length: "))
print("Generated Password:", generate_password(length))

8. Basic HTTP Request


Using requests library to make a basic GET request.

Python Run

import requests

# Making a GET request


response = [Link]("[Link]
print("Status Code:", response.status_code)
print("Response Content:", [Link]())

Note: You may need to install the requests library first with pip install requests .

9. Exception Handling
Basic exception handling with try , except , and finally .

Python Run

try:
number = int(input("Enter a number: "))
result = 10 / number

[Link] 24/36
3/13/26, 8:38 PM Python Loop Example
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")

10. Class and Objects


A simple class with methods and an instance.

Python Run

# Define a class
class Dog:
def __init__(self, name, age):
[Link] = name
[Link] = age

def bark(self):
return "Woof!"

# Create an object
my_dog = Dog("Buddy", 3)
print(f"My dog's name is {my_dog.name} and he is {my_dog.age} years old.")
print("He says:", my_dog.bark())

These examples cover a range of topics, giving you a foundation in Python syntax, control
flow, and basic programming concepts. Let me know if you'd like any further detail on any
of these examples!

complex python codes

[Link] 25/36
3/13/26, 8:38 PM Python Loop Example

Here are some examples of more advanced Python scripts that incorporate concepts like
object-oriented programming, data processing, and network programming. Each example
is designed to demonstrate more complex logic.

1. Data Analysis with Pandas: Filtering and Aggregation


This script demonstrates data filtering and aggregation on a CSV file of sales data using
pandas .

Python Run

import pandas as pd

# Load data from CSV


data = pd.read_csv("sales_data.csv")

# Filter rows with sales above a certain threshold


threshold = 1000
high_sales = data[data["sales"] > threshold]

# Calculate total sales by region


sales_by_region = [Link]("region")["sales"].sum()

print("High sales data:")


print(high_sales)
print("\nTotal sales by region:")
print(sales_by_region)

Explanation:
This script reads a CSV file with sales data.
It filters out sales above a given threshold.
Then, it aggregates and displays total sales by region.

2. Web Scraper with BeautifulSoup and Requests


A script to scrape the titles of articles from a news website using BeautifulSoup and
requests .

Python Run

[Link] 26/36
3/13/26, 8:38 PM Python Loop Example
import requests
from bs4 import BeautifulSoup

# URL to scrape
url = "[Link]

# Send a GET request to the page


response = [Link](url)

# Parse the HTML content


soup = BeautifulSoup([Link], "[Link]")

# Find all article titles


titles = soup.find_all("a", class_="storylink")

print("Latest news articles:")


for title in titles:
print(title.get_text())

Explanation:
The script sends an HTTP GET request to a news site.
It parses the HTML to extract and display article titles.

3. Multi-Threaded Web Server


A simple multi-threaded HTTP server built using socket and threading .

Python Run

import socket
import threading

# Handle individual client requests


def handle_client(client_socket):
request = client_socket.recv(1024)
print(f"Received: {[Link]('utf-8')}")

# Send an HTTP response


response = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nHello f
client_socket.send([Link]('utf-8'))
client_socket.close()

# Set up server
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](("[Link]", 8080))
[Link] 27/36
3/13/26, 8:38 PM Python Loop Example
[Link](5)
print("Server listening on port 8080...")

# Accept connections
while True:
client, addr = [Link]()
print(f"Accepted connection from {addr}")
client_handler = [Link](target=handle_client, args=(client,)
client_handler.start()

Explanation:
The script creates a basic multi-threaded HTTP server.
It listens for incoming connections, handles each in a separate thread, and returns a
simple HTTP response.

4. Image Processing with OpenCV: Detect Faces in an Image


This example uses OpenCV to detect faces in an image file.

Python Run

import cv2

# Load pre-trained face detector


face_cascade = [Link]([Link] + "haarcascade_

# Read an image
image = [Link]("[Link]")
gray = [Link](image, cv2.COLOR_BGR2GRAY)

# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=

# Draw rectangles around faces


for (x, y, w, h) in faces:
[Link](image, (x, y), (x+w, y+h), (255, 0, 0), 2)

# Show the output


[Link]("Faces found", image)
[Link](0)
[Link]()

[Link] 28/36
3/13/26, 8:38 PM Python Loop Example

Explanation:
The script loads an image and detects faces using OpenCV’s Haar Cascade classifier.
It draws rectangles around detected faces and displays the modified image.

5. Simulating a Stock Price with the Geometric Brownian Motion Model


Simulates stock price movements using the Geometric Brownian Motion model, a
common model for stock prices in finance.

Python Run

import numpy as np
import [Link] as plt

# Parameters
S0 = 100 # Initial stock price
mu = 0.1 # Expected return
sigma = 0.2 # Volatility
T = 1.0 # Time in years
n = 1000 # Number of steps

# Generate random prices


dt = T / n
t = [Link](0, T, n)
W = [Link].standard_normal(size=n)
W = [Link](W) * [Link](dt) # Brownian motion
S = S0 * [Link]((mu - 0.5 * sigma**2) * t + sigma * W)

# Plot the simulated stock price path


[Link](t, S)
[Link]("Simulated Stock Price Using Geometric Brownian Motion")
[Link]("Time (years)")
[Link]("Stock Price")
[Link]()

Explanation:
The script simulates a stock price using random values in the Geometric Brownian
Motion formula.
It visualizes the result as a time series plot of the simulated stock price.

[Link] 29/36
3/13/26, 8:38 PM Python Loop Example

6. API Request and JSON Parsing


Making a GET request to an API and parsing JSON data, e.g., fetching weather data from
an API.

Python Run

import requests

# API endpoint for current weather data (example uses OpenWeatherMap)


api_url = "[Link]
params = {
"q": "London",
"appid": "your_api_key", # Replace with your actual API key
"units": "metric"
}

response = [Link](api_url, params=params)

# Parse JSON data


if response.status_code == 200:
data = [Link]()
city = data["name"]
temp = data["main"]["temp"]
weather_desc = data["weather"][0]["description"]
print(f"The weather in {city} is {temp}°C with {weather_desc}.")
else:
print("Error:", response.status_code)

Explanation:
This script fetches weather data for a given city using the OpenWeatherMap API.
It parses JSON data and displays the current temperature and weather description.

Note: Replace "your_api_key" with an actual API key from OpenWeatherMap.

7. WebSocket Client with websockets Library


A WebSocket client that connects to a WebSocket server, sends a message, and prints the
response.

Python Run

import asyncio
import websockets
[Link] 30/36
3/13/26, 8:38 PM Python Loop Example

async def websocket_client():


uri = "[Link]
async with [Link](uri) as websocket:
await [Link]("Hello, WebSocket!")
response = await [Link]()
print("Received:", response)

# Run the client


[Link](websocket_client())

Explanation:
This script connects to a WebSocket server, sends a message, and waits for a
response.
It uses the websockets library for asynchronous WebSocket communication.

These scripts demonstrate more complex and useful patterns in Python, ranging from
data analysis and web scraping to network programming and real-world simulations. Each
example is designed to give you a taste of advanced Python programming and different
application areas. Let me know if you’d like more detail on any specific example!

pythpn codes

Here are various Python code examples, ranging from basic programming concepts to
more advanced techniques.

1. Basic Calculator
A simple calculator that performs addition, subtraction, multiplication, and division based
on user input.

Python Run

[Link] 31/36
3/13/26, 8:38 PM Python Loop Example
# Basic Calculator
num1 = float(input("Enter first number: "))
operation = input("Enter operation (+, -, *, /): ")
num2 = float(input("Enter second number: "))

if operation == "+":
print("Result:", num1 + num2)
elif operation == "-":
print("Result:", num1 - num2)
elif operation == "*":
print("Result:", num1 * num2)
elif operation == "/":
print("Result:", num1 / num2)
else:
print("Invalid operation")

2. Simple Password Validator


A script that checks if a password meets certain criteria.

Python Run

# Password Validator
password = input("Enter your password: ")

if len(password) >= 8 and any([Link]() for char in password) and any


print("Password is strong.")
else:
print("Password should be at least 8 characters, include a number and

3. File I/O: Writing and Reading Files


Writing data to a file and reading it back.

Python Run

# Writing to a file
with open("[Link]", "w") as file:
[Link]("This is a sample file.\nIt contains some text data.")

# Reading from a file


with open("[Link]", "r") as file:
[Link] 32/36
3/13/26, 8:38 PM Python Loop Example
content = [Link]()
print(content)

4. Fibonacci Sequence
Generate a sequence of Fibonacci numbers up to n terms.

Python Run

# Fibonacci Sequence
def fibonacci(n):
sequence = [0, 1]
for i in range(2, n):
[Link](sequence[i-1] + sequence[i-2])
return sequence

n_terms = int(input("Enter the number of terms: "))


print("Fibonacci sequence:", fibonacci(n_terms))

5. Class and Object Example: Creating a Bank Account


Defines a class with methods to handle basic account operations.

Python Run

class BankAccount:
def __init__(self, account_name, balance=0):
self.account_name = account_name
[Link] = balance

def deposit(self, amount):


[Link] += amount
print(f"{amount} deposited. New balance is {[Link]}")

def withdraw(self, amount):


if amount > [Link]:
print("Insufficient balance.")
else:
[Link] -= amount
print(f"{amount} withdrawn. New balance is {[Link]}")

# Create a bank account


account = BankAccount("John's Account", 100)
[Link] 33/36
3/13/26, 8:38 PM Python Loop Example
[Link](50)
[Link](30)
[Link](150)

6. Prime Number Checker


Check if a given number is prime.

Python Run

# Prime Number Checker


def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

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


if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")

7. Dictionary Operations: Student Grades


Store and retrieve student grades using a dictionary.

Python Run

# Student Grades
grades = {"Alice": 85, "Bob": 92, "Charlie": 78}

# Add a new student's grade


grades["Diana"] = 90

# Print all grades


for student, grade in [Link]():
print(f"{student}: {grade}")

# Retrieve a grade

[Link] 34/36
3/13/26, 8:38 PM Python Loop Example
student_name = input("Enter student name to get grade: ")
print(f"{student_name}'s grade:", [Link](student_name, "Student not fo

8. Palindrome Checker
Check if a word or phrase is a palindrome.

Python Run

# Palindrome Checker
def is_palindrome(text):
cleaned_text = ''.join([Link]() for char in text if [Link]()
return cleaned_text == cleaned_text[::-1]

phrase = input("Enter a word or phrase: ")


if is_palindrome(phrase):
print("It's a palindrome!")
else:
print("Not a palindrome.")

9. Random Number Guessing Game


A simple game where the user tries to guess a random number.

Python Run

import random

# Number Guessing Game


number = [Link](1, 100)
attempts = 0

print("Guess the number between 1 and 100.")

while True:
guess = int(input("Enter your guess: "))
attempts += 1
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")

[Link] 35/36
3/13/26, 8:38 PM Python Loop Example
else:
print(f"Congratulations! You guessed it in {attempts} attempts.")
break

10. Bubble Sort Algorithm


A basic implementation of the bubble sort algorithm.

Python Run

# Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr

# Example usage
numbers = [64, 34, 25, 12, 22, 11, 90]
sorted_numbers = bubble_sort(numbers)
print("Sorted list:", sorted_numbers)

These scripts cover a variety of programming concepts including loops, conditionals, file
handling, functions, and basic data structures like lists and dictionaries, providing a solid
foundation in Python programming. Let me know if you’d like further explanation or
more examples!

[Link] 36/36

You might also like