python logo


Category: beginner

Introduction

python if string equals

A string in Python represents a sequence of characters and is a fundamental data type in the language. Strings are predominantly utilized for displaying and manipulating text.

Strings can be defined by enclosing text within quotes. Python supports various types of quotes, including single ('), double ("), and triple (''' or """).

Related Course:
Python Programming Bootcamp: Go from zero to hero

Displaying and Receiving String Input


To display a string on the screen, you can use the print function. For instance:

s = "hello world"
print(s)

If you need to retrieve a string input from the user via the keyboard, the input function comes in handy:

name = input("Enter name: ")
print(name)

Note: If you are utilizing an older version of Python (2.x), the raw_input function is used instead of input:

name = raw_input("Enter name: ")
print(name)

To ascertain your Python version, you can execute the command:
python –version

Comparing Strings in Python


In Python, the equality operator (==) lets you check if two strings are identical. For example:

sentence = "The cat is brown"
q = "cat"

if q == sentence:
print('strings are identical')

Conversely, to see if two strings are different, employ the inequality operator (!=):

sentence = "The cat is brown"
q = "cat"

if q != sentence:
print('strings are not identical')

Enhance your Python skills further with exercises:
Download Python Exercises

For more tutorials, navigate:

python string slice

variables in python

python lists

if statement python

python function

Python functions are powerful tools in programming. They enable you to create reusable blocks of code, thereby enhancing the efficiency and readability of your programs.
Python is renowned for its simplicity and functions play a vital role in this. By leveraging functions, programmers can reduce repetition, increase code clarity, and simplify testing and modifications.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Understanding Python Functions

To comprehend the power and structure of functions in Python, it’s essential to first understand their syntax and formation.

In Python, the def keyword signals the beginning of a function. This is followed by the function name and any parameters the function might need. The body of the function contains the operations to be carried out, and the function may or may not return a value.

Here’s a basic structure:

def function_name(parameters):
# Body of the function
return value

A Simple Python Function in Action

To illustrate, let’s look at a function that calculates the square of a number.

#!/usr/bin/python

def square(x):
return x * x

print(square(3))

This will produce the output:

9

The above example demonstrates a function with a single parameter, x. It’s worth noting that while functions can return a value (like our square function), not all functions are required to.

Delving Deeper: Multiple Parameters in Python Functions

Functions in Python can be more intricate. They can accept multiple parameters, making them incredibly versatile.

Consider this example:

#!/usr/bin/python

def multiply(x, y):
print(f'You called multiply(x,y) with the values x = {x} and y = {y}')
print(f'x * y = {x * y}')

multiply(3, 2)

The output will be:

You called multiply(x,y) with the values x = 3 and y = 2
x * y = 6

The key takeaway here is the versatility of functions in Python. Whether you’re working with a single parameter or multiple ones, Python functions are designed to streamline your programming efforts.

Dive deeper with Python exercises here

python global variable

what is scope in python

python for loop

python range

python tuple

python dictionary

A dictionary can be thought of as an unordered set of key: value pairs.

A pair of braces creates an empty dictionary: {}.  Each element can maps to a certain value.  An integer or string can be used for the index. Dictonaries do not have an order.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Dictionary example


Let us make a simple dictionary:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words["Hello"])
print(words["No"])

Output:


Bonjour
Non

We are by no means limited to single word defintions in the value part. A demonstration:

#!/usr/bin/python

dict = {}
dict['Ford'] = "Car"
dict['Python'] = "The Python Programming Language"
dict[2] = "This sentence is stored here."

print(dict['Ford'])
print(dict['Python'])
print(dict[2])

Output:


Car
The Python Programming Language
This sentence is stored here.

Manipulating the dictionary


We can manipulate the data stored in a dictionairy after declaration.  This is shown in the example below:

#!/usr/bin/python

words = {}
words["Hello"] = "Bonjour"
words["Yes"] = "Oui"
words["No"] = "Non"
words["Bye"] = "Au Revoir"

print(words) # print key-pairs.
del words["Yes"] # delete a key-pair.
print(words) # print key-pairs.
words["Yes"] = "Oui!" # add new key-pair.
print(words) # print key-pairs.

Output:


{'Yes': 'Oui', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}
{'Yes': 'Oui!', 'Bye': 'Au Revoir', 'Hello': 'Bonjour', 'No': 'Non'}

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

python cast

Python determines the datatype automatically, to illustrate:


x = 3
y = "text"

It finds x is of type integer and y of type string.

Functions accept a certain datatype. For example, print only accepts the string datatype.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Datatypes casting


If you want to print numbers you will often need casting.

In this example below we want to print two numbers, one whole number (integer) and one floating point number.

x = 3
y = 2.15315315313532

print("We have defined two numbers,")
print("x = " + str(x))
print("y = " + str(y))

We cast the variable x (integer) and the variable y (float) to a string using the str() function.

What if we have text that we want to store as number? We will have to cast again.

a = "135.31421"
b = "133.1112223"

c = float(a) + float(b)
print(c)

In the example above we cast two variables with the datatype string to the datatype float.

Conversion functions


To convert between datatypes you can use:

Download Python Exercises

random number

How to Read a File in Python

Python File Writing

Python supports writing files by default, meaning no special modules are required. This built-in functionality ensures a smooth experience for developers. One can easily write to a file using the .write() method, which requires a parameter containing the text data.

Before diving into file writing, it’s important to understand the basics:

  • Opening a File: Use the open(filename, 'w') function. Here, filename can be either the actual filename or its path.
  • Writing Data: After opening, you can use the .write() method to input your desired content.
  • Closing a File: Don’t forget to close the file once you’ve finished to ensure data integrity and to free up system resources.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Creating or Overwriting a File in Python

The code below demonstrates how to create a new file or overwrite an existing one:

Function Description
int(x) Converts x to an integer
long(x) Converts x to a long integer
float(x) Converts x to a floating point number
str(x) Converts x to an string. x can be of the type float. integer or long.
hex(x) Converts x integer to a hexadecimal string
chr(x) Converts x integer to a character
ord(x) Converts character x to an integer
#!/usr/bin/env python

# Specify the filename
filename = "newfile.txt"

# Open the file with write permissions
myfile = open(filename, 'w')

# Add content to the file
myfile.write('Written with Python\n')

# Ensure the file is closed post operations
myfile.close()

An important note: the ‘w’ flag will cause Python to truncate the file if it already exists. In simpler terms, existing file content will be replaced.

Appending Content to an Existing File

If you wish to retain the existing content and merely add more to a file, the ‘a’ parameter is your go-to:

#!/usr/bin/env python

# Define the filename for appending
filename = "newfile.txt"

# The 'a' flag instructs Python to preserve the file contents and add new content at the end.
myfile = open(filename, 'a')

# Add your desired line
myfile.write('Appended with Python\n')

# Always close the file after operations
myfile.close()

File Modes in Python: A Brief Summary

When working with files, Python offers various modes. Here’s a summary of the essential ones:

📥 Download Python Exercises

python class

python class tutorial

Everything in Python is an object. Every object can contain methods and variables (with unique values). Objects are created (often called instantiated) from classes.

Related courses
Python Programming Bootcamp: Go from zero to hero

Class example
Consider the example below:

Flag Action
rOpen file for reading
wOpen file for writing (overwrites if exists)
aOpen file for appending (retains existing content)
bBinary mode
r+Open for both reading and writing
a+Read and append
w+Read and write (overwrites if exists)

class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

We create one object called ‘duck’ from the class Animal. The class has a method (walk) that can be called on each object. We also have a method called init(), this is a method that is always called when a new object is created. The self keyword is required for every method. We set the variables with the class (self.name = ..).

python class Python class and object drawn using the modeling language UML

Once the object is created, we can call its methods and use its variables indefinitely. Every object of the same class has the same methods, but its variables contents may differ.

A Python program may consists of many classes and objects. To demonstrate that, we create two objects from one class:


class Animal:
def __init__(self,name):
self.name = name

def walk(self):
print(self.name + ' walks.')

duck = Animal('Duck')
duck.walk()

rhino = Animal('African Rhino')
rhino.walk()

If you are new to Python programming, I highly recommend this book.

Download Exercises

encapsulation in python

Method overloading

method overloading Several ways to call a method (method overloading)

In Python you can define a method in such a way that there are multiple ways to call it.

Given a single method or function, we can specify the number of parameters ourself.

Depending on the function definition, it can be called with zero, one, two or more parameters.

This is known as method overloading. Not all programming languages support method overloading, but Python does.

Related course
Python Programming Bootcamp: Go from zero to hero

Method overloading example


We create a class with one method sayHello(). The first parameter of this method is set to None, this gives us the option to call it with or without a parameter.

An object is created based on the class, and we call its method using zero and one parameter.

#!/usr/bin/env python

class Human:

def sayHello(self, name=None):

if name is not None:
print('Hello ' + name)
else:
print('Hello ')


# Create instance
obj = Human()

# Call the method
obj.sayHello()

# Call the method with a parameter
obj.sayHello('Guido')

Output:

Hello
Hello Guido

To clarify method overloading, we can now call the method sayHello() in two ways:

obj.sayHello()
obj.sayHello('Guido')

We created a method that can be called with fewer arguments than it is defined to allow.

We are not limited to two variables, your method could have more variables which are optional.

If you are new to Python programming, I highly recommend this book.

Download Exercises

python class inheritance

Polymorphism

python inner class

An inner class, also known as a nested class, is a class that’s defined within the scope of another class. When an object is instantiated from an outer class, the object inside the nested class can also be used. It’s possible for a class to contain multiple nested classes, though they’re often used sparingly.

Python’s ability to nest classes within other classes is one of its many versatile features. A nested class inherits all attributes and methods from its enclosing class.

Related Course: Python Programming Bootcamp: Go from zero to hero

Inner Class in Python: A Simple Example

In Python, inner classes or nested classes can be defined inside the scope of another class. These inner classes can access all the members of their enclosing class.

Proper indentation is crucial when defining inner classes. Typically, each inner class is indented by 4 spaces to adhere to PEP 8, Python’s style guide.

Below is an example where we define a Human class with a nested Head class. We then create an instance of the Human class and call a method from the nested Head class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python

class Human:
def __init__(self):
self.name = 'Guido'
self.head = self.Head()

class Head:
def talk(self):
return 'talking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())

Output:

1
2
Guido
talking...

In the example above, the inner Head class possesses its own method. Inner classes can encapsulate both methods and variables. The constructor of the Human class (__init__) initializes a new head object.

Multiple Inner Classes in Python

Python doesn’t impose a limitation on the number of inner classes. Here’s an example that includes two nested classes within the Human class:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python

class Human:
def __init__(self):
self.name = 'Guido'
self.head = self.Head()
self.brain = self.Brain()

class Head:
def talk(self):
return 'talking...'

class Brain:
def think(self):
return 'thinking...'

if __name__ == '__main__':
guido = Human()
print(guido.name)
print(guido.head.talk())
print(guido.brain.think())

Utilizing inner classes allows for more organized and object-oriented code. A single outer object can comprise multiple sub-objects, enabling a more structured programming approach.

Benefits of Using Inner Classes

Grouping classes within other classes through the use of inner classes can offer several benefits:

  1. Inner classes are confined to a local scope, ensuring encapsulation.
  2. It becomes more evident which classes share a relationship, enhancing code readability.

Although inner or nested classes provide structural benefits, they’re not as commonly used in Python compared to other OOP languages.

Download Exercises

python factory

recursion in python

Recursion is a widely-discussed concept not just in programming, but also in day-to-day language. An example from the English language that beautifully captures recursion is “To understand recursion, you must first understand recursion”. Similarly, the saying “A human is someone whose mother is human” offers another simple explanation.

Now, pivoting to programming, you may ask: How is this relevant?

In the realm of problem-solving, often there’s a need to break down a large, intricate problem into smaller, manageable parts. While you might be accustomed to using loops or iterations for such purposes, sometimes, recursion provides a more elegant and intuitive solution.

So, what exactly is recursion in Python? A function is termed as recursive when it makes a call to itself, but it’s imperative that this function has a stopping point or a termination condition. This ensures that the function doesn’t end up calling itself endlessly.

Related Course: Python Programming Bootcamp: Go from zero to hero

Recursion in Practice

List-Based Recursion Example

Consider a simple task of summing all numbers in a given list. A non-recursive approach to achieve this would be:

#!/usr/bin/env python

def sum(list):
sum = 0

# Iteratively add each number in the list.
for i in range(0, len(list)):
sum = sum + list[i]

# Return the computed sum.
return sum

print(sum([5,7,3,8,10]))

The above approach is straightforward: we iterate through each element and accumulate the sum. But how can we approach this using recursion?

#!/usr/bin/env python

def sum(list):
if len(list) == 1:
return list[0]
else:
return list[0] + sum(list[1:])

print(sum([5,7,3,8,10]))

Here, if the list contains just one element, that element is returned (acting as the termination condition). Otherwise, the function adds the first element to the sum of the rest of the list (achieved through a recursive call).

Factorial Using Recursion

Factorials are often calculated using recursion in programming. The mathematical definition states: n! = n * (n-1)!, given n > 1 and f(1) = 1. For instance, 3! = 3 x 2 x 1 = 6. Here’s how you can compute factorials recursively in Python:

#!/usr/bin/env python

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

print(factorial(3))

In the above code, as long as the input is greater than 1, the function keeps calling itself, thus calculating the factorial in a recursive manner.

Constraints of Using Recursion

It’s essential to understand the limitations of recursion. Each time a function calls itself, it uses some memory to store return values. Because of this, a recursive function can sometimes use a lot more memory compared to its iterative counterpart. In Python, recursion is limited to a depth of 1000 calls. If you try to surpass this, as demonstrated below:

#!/usr/bin/env python

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

print(factorial(3000))

You’ll be met with the error:

RuntimeError: maximum recursion depth exceeded

Some languages might crash your program under such conditions. While you can tweak the maximum recursion depth in Python, as shown:

#!/usr/bin/env python
import sys

sys.setrecursionlimit(5000)

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

print(factorial(3000))

Remember that this isn’t a foolproof solution. There will always be a threshold, and for problems like calculating large factorials, a recursive function might not be the most efficient choice. However, for tasks like directory traversal, recursion can be quite handy.

Related Course: Python Programming Bootcamp: Go from zero to hero

python logging

Python logging


We can track events in a software application, this is known as logging. Let’s start with a simple example, we will log a warning message.

As opposed to just printing the errors, logging can be configured to disable output or save to a file. This is a big advantage to simple printing the errors.

Related course
Python Programming Bootcamp: Go from zero to hero

Logging example

import logging

# print a log message to the console.
logging.warning('This is a warning!')

This will output:

WARNING:root:This is a warning!

We can easily output to a file:

import logging

logging.basicConfig(filename='program.log',level=logging.DEBUG)
logging.warning('An example message.')
logging.warning('Another message')

The importance of a log message depends on the severity.

Level of severity


The logger module has several levels of severity. We set the level of severity using this line of code:

logging.basicConfig(level=logging.DEBUG)

These are the levels of severity:

The default logging level is warning, which implies that other messages are ignored. If you want to print debug or info log messages you have to change the logging level like so:

Type Description
DEBUG Information only for problem diagnostics
INFO The program is running as expected
WARNING Indicate something went wrong
ERROR The software will no longer be able to function
CRITICAL Very serious error
import logging

logging.basicConfig(level=logging.DEBUG)
logging.debug('Debug message')

Time in log


You can enable time for logging using this line of code:

logging.basicConfig(format='%(asctime)s %(message)s')

An example below:

import logging

logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
logging.info('Logging app started')
logging.warning('An example logging message.')
logging.warning('Another log message')

Output:

2015-06-25 23:24:01,153 Logging app started
2015-06-25 23:24:01,153 An example message.
2015-06-25 23:24:01,153 Another message

Related course
Python Programming Bootcamp: Go from zero to hero

python subprocess

python threading

python lambda if

We can create anonymous functions, known as lambda functions. Lambda functions are different from normal Python functions, they originate from Lambda Calculus. It allows you to write very short functions.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Lambda function example
This code shows the use of a lambda function:

#!/usr/bin/env python

f = lambda x : 2 * x
print f(3)

A return statements is never used in a lambda function, it always returns
something. A lambda functions may contain if statements:

#!/usr/bin/env python

f = lambda x: x > 10
print(f(2))
print(f(12))

map function


The definition of map is map(function,iterable). It applies a function to every item in the iteratable. We can use map() on a lambda function with a list:

#!/usr/bin/env python

list = [1,2,3,4,5]
squaredList = map(lambda x: x*x, list)
print(squaredList)

Anywhere you use lambda functions, you could use normal functions instead. A lambda function is not a statement, it is an expression. Lambda functions do not support a block of statements.

filter function


filter(function,iterable) creates a new list from the elements for which the function returns True. Example:

#!/usr/bin/env python

list = [1,2,3,4,5,6,7,8,9,10]
newList = filter(lambda x: x % 2 == 0, list)
print(newList)

The returning list returns contains only the elements for which the lambda expression “lamba x: x % 2 == 0” is true.

reduce function


The reduce function, reduce(function, iterable) applies two arguments cumulatively to the items of iterable, from left to right. Example:

#!/usr/bin/env python

list = [1,2,3,4,5]
s = reduce(lambda x,y: x+y, list)
print(s)

In this case the expression is always true, thus it simply sums up the elements of the list. Another example:

#!/usr/bin/env python

list = [10,6,7,5,2,1,8,5]
s = reduce(lambda x,y: x if (x > y) else y, list)
print(s)


Related Course:
Python Programming Bootcamp: Go from zero to hero

 

python create set

Sets in Python


A set in Python is a collection of objects. Sets are available in Python 2.4 and newer versions. They are different from lists or tuples in that they are modeled after sets in mathematics.

Related course
Python Programming Bootcamp: Go from zero to hero

Set example
To create a set, we use the set() function.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

If we add the same item element multiple times, they are removed. A set may not contain the same element multiple times.

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram", "Postcard"])
print(x)

Simple notation


If you use Python version 2.6 or a later version, you can use a simplified notation:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
print(x)

y = {"Postcard","Radio","Telegram"}
print(y)

Set Methods


Clear elements from set
To remove all elements from sets:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.clear()
print(x)

Add elements to a set
To add elements to a set:

#!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.add("Telephone")
print(x)

Remove elements to a set
To remove elements to a set:

!/usr/bin/env python

x = set(["Postcard", "Radio", "Telegram"])
x.remove("Radio")
print(x)

Difference between two sets
To find the difference between two sets use:

#!/usr/bin/env python
x = set(["Postcard", "Radio", "Telegram"])
y = set(["Radio","Television"])
print( x.difference(y) )
print( y.difference(x) )

Be aware that x.difference(y) is different from y.difference(x).

Subset
To test if a set is a subset use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issubset(y) )<b>
</b>

Super-set
To test if a set is a super-set:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.issuperset(y) )

Intersection
To test for intersection, use:

#!/usr/bin/env python

x = set(["a","b","c","d"])
y = set(["c","d"])
print( x.intersection(y) )

Related course
Python Programming Bootcamp: Go from zero to hero

python modules tutorial

python graph

python state machine

python tree

python binary number

python debugger

We can use debugging tools to minimize and find bugs. In this article you will learn the best Python debugging tricks.

PuDB - A console-based Python debugger

python-debugging-pudb Python Debug with PuDB

A graphical interface is shown using the PuDB terminal.

Related course:
Python Programming Bootcamp: Go from zero to hero

Installation
to install with Python 3:


sudo pip3 install pudb

for Python 2.x use:


sudo pip install pudb

Debugging
Start debugging with:


$ pudb3 program.py

(or sudo if you don’t have the right permissions)

You can take step by step through the program. Use the n key to take a step through the program. The current variable contents are shown on the right top.

pudb-debug debug with python

You can set breakpoints using the b key. To continue execution until the next breakpoints, press the c key.

python-breakpoint Breakpoint in Python program

Related course:
Python Programming Bootcamp: Go from zero to hero

PDB - The Python Debugger


The module pdb supports setting breakpoints. A breakpoint is an intentional pause of the program. where you can get more information about the programs state.

To set a breakpoint, insert the line


pdb.set_trace()

Example
A practical example:


import pdb

x = 3
y = 4
pdb.set_trace()

total = x + y
pdb.set_trace()

We have inserted a few breakpoints in this program. The program will pause at each breakpoint (pdb.set_trace()). To view a variables contents simply type the variable name:


$ python3 program.py
(Pdb) x
3
(Pdb) y
4
(Pdb) total
*** NameError: name 'total' is not defined
(Pdb)

Press c or continue to go on with the programs execution until the next breakpoint


(Pdb) c
--Return--
> program.py(7)<module>()->None
-> total = x + y
(Pdb) total
7

Related course:
Python Programming Bootcamp: Go from zero to hero

python enum

An enum (enumeration) is a set of symbolic names bound to unique constant values.

We can use enums by referring to their names, as opposed to an index number. The constant value can be any type: numeric or text. As the example below:


currency = enum(EUR='Euro',USD='United States Dollar', GBP='Great British Pound')
print(currency.USD)

Related course

Module enum installation
To use enums module, you need Python 3.4; To install for Python 3.4:


sudo pip install enum34

For older versions (Python 2.7):


sudo pip install aenum

enum example (using enum/aenum)
We can create an Enum after importing the class Enum from either the module enum or aenum.
After importing the list


#from enum import Enum
from aenum import Enum

class Numbers(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 4

print(Numbers.ONE.value)
print(Numbers.THREE.value)

or as a one liner:


#from enum import Enum
from aenum import Enum

class Numbers(Enum):
ONE, TWO, THREE, FOUR = 1,2,3,4

print(Numbers.ONE.value)
print(Numbers.THREE.value)

enum example (without using modules)
The old way of creating enums is:


def enum(**enums):
return type('Enum', (), enums)

Numbers = enum(ONE=1,TWO=2, THREE=3, FOUR=4, FIVE=5, SIX=6)
print(Numbers.ONE)