Create a directory with os.mkdir()

Create a directory with os.mkdir()

EasyOS Module Programs · 5 of 49

Write a Python program to create a directory with os.mkdir().

Output
True

Approach

  1. os.mkdir() creates one folder; it fails if it already exists.

Solution

Python
import os if not os.path.exists("reports"):    os.mkdir("reports")print(os.path.isdir("reports"))
Output
True

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

List environment variables

List environment variables

EasyOS Module Programs · 4 of 49

Write a Python program to get the list of environment variables with os.environ.

Output
True
True

Approach

  1. os.environ behaves like a dictionary.

Solution

Python
import os names = sorted(os.environ)print(len(names) > 0)print("PATH" in names)for name in names[:0]:    print(name, "=", os.environ[name])
Output
True
True

Line by line

Line 3

sorted() of the mapping gives the variable names.

Watch out

The loop is limited to [:0] here on purpose: environment values often contain paths, user names and secrets, so print them only on your own machine.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Set an environment variable

Set an environment variable

EasyOS Module Programs · 3 of 49

Write a Python program to set an environment variable for the current process.

Output
testing
child sees: testing

Approach

  1. Assign to os.environ; child processes inherit it.

Solution

Python
import osimport subprocessimport sys os.environ["APP_MODE"] = "testing"print(os.environ["APP_MODE"])child = subprocess.run([sys.executable, "-c", "import os; print(os.environ['APP_MODE'])"],                       capture_output=True, text=True)print("child sees:", child.stdout.strip())
Output
testing
child sees: testing

Line by line

Line 5

The value lives only in this process and the processes it starts; it does not change system settings.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Get the current working directory

Get the current working directory

EasyOS Module Programs · 1 of 49

Write a Python program to get the current working directory.

Output
1
True

Approach

  1. os.getcwd() returns the folder the program runs in.

Solution

Python
import os cwd = os.getcwd()print(os.path.basename(cwd))print(os.path.isabs(cwd))
Output
1
True

Line by line

Line 3

The full path depends on your computer, so the example prints only the last folder name.

Line 5

getcwd() always returns an absolute path.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Read an environment variable

Read an environment variable

EasyOS Module Programs · 2 of 49

Write a Python program to read an environment variable.

Output
True
development

Approach

  1. os.environ.get(name, default) or os.getenv(name, default).

Solution

Python
import os print("PATH" in os.environ)print(os.getenv("APP_MODE", "development"))
Output
True
development

Line by line

Line 4

APP_MODE is not set, so the default is returned instead of an error.

Learn the concept

New to this topic? Read the lesson, then come back.

More os module programs

← All 49 OS Module Programs

Median of a list

Python Practice › List Programs › Program 100

Median of a list

EasyList Programs · 100 of 100

Write a Python program to get the median of all the elements of a list.

Input
[2, 4, 6, 7, 5, 8, 3, 11]
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Approach

  1. Sort; for an even count average the two middle values.

Solution

Python
import statistics items = [2, 4, 6, 7, 5, 8, 3, 11]s = sorted(items)mid = len(s) // 2median = s[mid] if len(s) % 2 else (s[mid - 1] + s[mid]) / 2print(s, median, statistics.median(items))
Output
[2, 3, 4, 5, 6, 7, 8, 11] 5.5 5.5

Line by line

Line 5

Eight values, so the median is the average of the 4th and 5th sorted values, 5 and 6.

Learn the concept

New to this topic? Read the lesson, then come back.

More list programs

← All 100 List Programs

Dog inherits from Animal

Python Practice › OOP Programs › Program 48

Dog inherits from Animal

EasyOOP Programs · 48 of 48

Create Dog (inherits Animal) with breed and weight, and a method to print all details.

Output
Bruno is brown, a Labrador weighing 28 kg

Approach

  1. Override show and reuse the parent’s message with super().

Solution

Python
class Animal:    def __init__(self, name, color):        self.name, self.color = name, color     def show(self):        return f"{self.name} is {self.color}" class Dog(Animal):    def __init__(self, name, color, breed, weight):        super().__init__(name, color)        self.breed, self.weight = breed, weight     def show(self):        return super().show() + f", a {self.breed} weighing {self.weight} kg" print(Dog("Bruno", "brown", "Labrador", 28).show())
Output
Bruno is brown, a Labrador weighing 28 kg

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Animal class

Python Practice › OOP Programs › Program 47

Animal class

EasyOOP Programs · 47 of 48

Create Animal with name and colour and a method to print them.

Output
Bruno is brown

Approach

  1. Store and print.

Solution

Python
class Animal:    def __init__(self, name, color):        self.name, self.color = name, color     def show(self):        print(f"{self.name} is {self.color}") Animal("Bruno", "brown").show()
Output
Bruno is brown

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

ShoppingCart class

Python Practice › OOP Programs › Program 46

ShoppingCart class

EasyOOP Programs · 46 of 48

Create ShoppingCart with items and total cost, and methods to add and remove items and calculate the total.

Output
{'pen': (10, 5)} 50

Approach

  1. Store items in a dict of name -> (price, quantity).

Solution

Python
class ShoppingCart:    def __init__(self):        self.items = {}     def add(self, name, price, qty=1):        old_qty = self.items.get(name, (price, 0))[1]        self.items[name] = (price, old_qty + qty)     def remove(self, name):        self.items.pop(name, None)     def total_cost(self):        return sum(price * qty for price, qty in self.items.values()) cart = ShoppingCart()cart.add("pen", 10, 3)cart.add("bag", 650)cart.add("pen", 10, 2)cart.remove("bag")print(cart.items, cart.total_cost())
Output
{'pen': (10, 5)} 50

Line by line

Lines 5-7

Adding an item again increases its quantity instead of replacing it.

Lines 12-13

The total is calculated when needed, so it is always up to date.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

EBook with open and close

Python Practice › OOP Programs › Program 45

EBook with open and close

EasyOOP Programs · 45 of 48

Create EBook (inherits Book) with file_size and format, and methods to open and close the book.

Output
Opened Python Basics (PDF, 3.4 MB)
Closed Python Basics

Approach

  1. Track whether the e-book is open.

Solution

Python
class Book:    def __init__(self, title, author, pages):        self.title, self.author, self.pages = title, author, pages class EBook(Book):    def __init__(self, title, author, pages, file_size_mb, fmt):        super().__init__(title, author, pages)        self.file_size_mb, self.format = file_size_mb, fmt        self.is_open = False     def open(self):        self.is_open = True        return f"Opened {self.title} ({self.format}, {self.file_size_mb} MB)"     def close(self):        self.is_open = False        return f"Closed {self.title}" e = EBook("Python Basics", "SQA Tools", 220, 3.4, "PDF")print(e.open())print(e.close())
Output
Opened Python Basics (PDF, 3.4 MB)
Closed Python Basics

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs