top of page
Search

Strip bare Python with examples

  • Writer: Kapil Dua
    Kapil Dua
  • Jan 25, 2023
  • 6 min read

Updated: Feb 16, 2023

This article is for those who have experience with another programming language and want to learn Python in no time. One can also use this article as a quick reference for basic Python syntax and library methods and functions.


Lists

In Python, square brackets ([]) denote a list. Commas separate individual elements in the list.

Some salient points:

  • Index Positions Start at 0, Not 1

  • Item at index -1 returns the last element. Similarly, the item at index -2 returns the second element from the end of the list

# List methods and functions with examples
cars = ['bmw', 'audi']

# appending an item at the end
cars.append('tata')

# inserting an item at the end
cars.insert(0, 'ferrari')

# removes the last item but returns it value
last_car = cars.pop()

# removes the first item
first_car = cars.pop(0)

# removes the first occurance of an item
cars.remove('audi')

# changes the list permanently to aphabetical order
cars.sort()

# sorts in reverse aphabetical order
cars.sort(reverse=True)

# sorts in reverse chronological order
cars.reverse() 

# functions with examples
# deletes the first item i.e. 'bmw'
del cars[0]

# displays without affecting actual order
print(sorted(cars))

# returns the length of the list
len(cars)


Using Lists

Each indented line following the for statement is part of the for loop.

# Basic for loop
cars = ['bmw', 'audi', 'tata', 'ferari', 'mercedes', 'toyota']
for car in cars:
    print(car)

# Basic range function
# Prints values from 1 through 5
for value in range(1, 6):
    print(value)

# Returns a list of numbers
numbers = list(range(1, 6))

# Third argument in range function is step size
# Returns a list of even numbers
even_numbers = list(range(2, 11, 2))

# Simple List functions
min(numbers)
max(numbers)
sum(numbers)

# List comprehensions combines for loop and list creation
# Returns a list of squares from 1 to 10
squares = [value**2 for value in range(1, 11)]

Slicing

A subset of a list is called a slice in Python.

# Examples of Slicing
# Slices items at index 0 and 1
my_cars = cars[0:2]

# Slices items at index 1 and 2
my_cars = cars[1:3]

# Slices items at index 0 and 1
my_cars = cars[:2]

# Slices items from index 2 till the end of the list
my_cars = cars[1:]

# Slices last two items of the list
my_cars = cars[-2:]

# Slices items from begining and skips 2 items
my_cars = cars[0:6:2]

# Copying a list by value
my_cars = cars[:]

Tuples

An immutable list is called a tuple. A tuple works just like a list, but is written using parentheses instead of square brackets.

# Example of tuple
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])


if Statements

if-else block

# example of a simple if-else block
if car == 'bmw':
    print(car.upper())
else:
    print(car.title())

if-elif-else block

#  example of a simple if-elif-else block
if car == 'bmw':
    print(car.upper())
elif car == 'tata':
    print(car.upper())
else:
    print(car.title())

Operators

==, !=, <, <=, >, >=, in, not in, and, or

# example
cars = ['bmw', 'audi', 'tata', 'ferrari']

for car in cars:
    if (car == 'bmw') or (car == 'tata'):
        print(car.upper())
    else:
        print(car.title())

Dictionaries

A dictionary in Python is a collection of key-value pairs.

# Starting with an empty dictionary
cars = {}

cars = {
    'bmw': 'green',
    'tata': 'blue',
    'ferrari': 'red',
    'hyundai': 'green',
    'Suzuki': 'red',
    }

# Accessing a dictionary item
print(cars['ferrari'])

# Adding new key-value pairs
cars['toyota'] = 'white'

# Removing key-value pairs
del cars['tata']

# Use get() function instead of square brackets
# If there is a chance that the key may not exist
my_car = cars.get('tata', "This car doesn't exist in your garage")
print(my_car)

# Looping through the dictionary items
for key, value in cars.items():
    print(f"\nKey: {key.title()}")
    print(f"Value: {value.title()}")

# Looping through all the keys in a dictionary
# Keys are returned in the order they were inserted
for car in cars.keys():
    print(car.title())

# Looping through all the keys in a sorted order
for car in sorted(cars, reverse=True):
    print(car.title())

# Looping through all the values in a dictionary
for car in cars.values():
    print(car.title())

# Returning only unique values through set function
for car in set(cars.values()):
    print(car.title())

While Loops

cars = ['bmw', 'audi', 'tata', 'ferari', 'mercedes', 'toyota', 'audi']
my_cars = []
i = 0

# Basic while loop
while i < 5:
    i = i + 1
    print(i)

# Exit the while loop using break
while True:
    i = i + 1

    if i == 5:
        break

# Use continue in a while loop
while True:
    i = i + 1

    if i % 2 == 0:
        continue
    
    if i > 20:
        break

    print(i)

# Displaying items of a list
while cars:
    car = cars.pop()
    print(f"You are looking at a {car.title()}")

# Removing all instances of a specific value from a list
while 'audi' in cars:
    cars.remove('audi')

print(cars)

# Moving items from one list to another
while cars:
    car = cars.pop()
    response = input(f"\nIs {car.title()} part of my fleet (yes/no)? :")
 
    if response == 'yes':
        my_cars.append(car)

print (my_cars)

Functions


# A simple function
def display_car(carname):
    """Display a simple greeting."""
    print(f"Hello, {carname.title()}!")

display_car("Toyota")

# Calling function with keyword arguments, default value, return value, and optional value
# Default value argument always comes after mandatory agruments
# Optional arguements must be last argument
def car_info (manufacturer, model_name, body_type='Sedan', make_year=''):
    """Display car info"""
    if make_year == '':
        message = f"{manufacturer.title()} {model_name.title()} {body_type.title()}"
    else:
        message = f"{manufacturer.title()} makes {make_year} {model_name.title()} {body_type.title()}"

    return message

# print(car_info(manufacturer='toyota', model_name='lexus', make_year='1975'))

def car_info_dict (manufacturer, model_name, body_type, make_year):
    """Create a dictionay with car info"""
    car = {}
    car['manufacturer'] = manufacturer
    car['model_name'] = model_name
    car['body_type'] = body_type
    car['make_year'] = make_year
    return car

my_cars = []
my_car = {}
print("Please create a collections of your cars. Enter 'q' to quit")

while True:
    manufacturer = input("\nEnter the car company name: ")
    if manufacturer == 'q':
        break
    
    model_name = input("\nEnter the car brand name: ")
    if model_name == 'q':
        break
    
    body_type = input("\nEnter the car body type: ")
    if body_type == 'q':
        break

    make_year = input("\nEnter the car make year: ")
    if make_year == 'q':
        break

    my_car = car_info_dict(manufacturer, model_name, body_type, make_year)
    my_cars.append(my_car)

print(my_cars)

# Passing a list argument to the function
def display_cars(cars):
    """Print a simple car info in the list."""
    for car in cars:
        print(car.title())

cars = ['bmw', 'toyota', 'tata']
display_cars(cars)

# Function taking normal and arbitrary arguments
# Arbitrary argument should come last
def service_car(car_name, *services):
    """Print the list of services requested for the car"""
    print(f"The list of services requested for your {car_name.title()}:")
    for service in services:
        print(f"- {service}")

service_car('lexus', 'washing')
service_car('land rover', 'washing', 'buffing', 'oil change')

# Function using arbitrary keyword arguments
def car_registration_details(car_name, car_type, **car_info):
    """Builds a dictionary containing all car details"""
    car_info['car_name'] = car_name
    car_info['car_type'] = car_type
    return car_info

car_details = car_registration_details('lexus', 'saloon',
                                        manufacturer='toyota',
                                        make_year='2005')

print(car_details)

# Use import keyword to import a file
# Use as keyword to give an alias to a file name
import cars as c

car_details = c.car_registration_details('lexus', 'saloon',
                                        manufacturer='toyota',
                                        make_year='2005')
print(car_details)

# Use from and import keywords to import a function from a file
# Use as keyword to give an alias to a function name
from cars import car_registration_details as register

car_details = register('lexus', 'saloon',
                                        manufacturer='toyota',
                                        make_year='2005')
print(car_details)

Classes


# A simple implementatino of a class
class Car:
    """A simple implementation of a Car class"""

    # Constructor implementation
    def __init__(self, car_manufacturer, car_model) -> None:
        """Initialize car manufacturer and model name"""
        self.car_manufacture = car_manufacturer
        self.car_model = car_model
        self.odometer_reading = 0
        self.gas_tank_size = 25

    def drive(self):
        """Strat driving the car"""
        print(f"{self.car_model.title()} is now driving.")

    def launch_new_model(self):
        """Launch a new model of the car"""
        print(f"{self.car_manufacture.title()} is launching a new model of {self.car_model.title()}")

    def update_odometer(self, mileage):
        """
        Set odometer attribute to the given value
        Reject rollback of odometer value
        """

        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("Can't rollback odometer reading.")

    def display_odometer(self):
        print(f"This car has {self.odometer_reading} miles on it.")

    def display_gas_tank(self):
        print(f"This car has a gas tank of {self.gas_tank_size} gallons.")

my_car = Car('tata', 'jaguar')
my_car.update_odometer(25)
my_car.drive()
my_car.launch_new_model()
my_car.display_odometer()
my_car.update_odometer(20)

class ElectricCar(Car):
    """Representation of an electric car"""

    def __init__(self, car_manufacturer, car_model) -> None:
        """Initializes attributes of the super class
            and creates an instance of the Battery class"""
        super().__init__(car_manufacturer, car_model)
        self.battery = Battery(battery_size=65)
       
    def display_gas_tank(self):
        """Overloads the function with the same name from Car class"""
        print("This is an electric car. It doesn't need gas.")

class Battery:
    """Separting features of a battery from the ElectricCar class"""
    
    def __init__(self, battery_size=40):
        """Initialize the battery's attributes"""
        self.battery_size = battery_size

    def display_battery_info(self):
        """Displays the battery size"""
        print(f"The battery size of this car is {self.battery_size}")

    def display_range(self):
        """Displays the range of the electric car on a full battery charge"""
        if self.battery_size == 40:
            range = 200
        elif self.battery_size == 65:
            range = 300

        print(f"This car can travel about {range} on a full battery charge.")

    def upgrade_battery(self):
        """Upgrades the battery to 65kWH from 40kWH"""
        if self.battery_size == 40:
            self.battery_size = 65
        else:
            print(f"The battery is already upgraded.")

my_electric_car = ElectricCar('tata', 'nexon')
my_electric_car.battery.display_battery_info()
my_electric_car.battery.display_range()
my_electric_car.display_gas_tank()

Recent Posts

See All
The TOGAF Enterprise Architect

An enterprise is the groups of organizations that share a common goal. Architecture describes how an enterprise's business processes are...

 
 
 

Comentários


bottom of page