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" |
If you need to retrieve a string input from the user via the keyboard, the input
function comes in handy:
name = input("Enter 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: ") |
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" |
Conversely, to see if two strings are different, employ the inequality operator (!=
):
sentence = "The cat is brown" |
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): |
A Simple Python Function in Action
To illustrate, let’s look at a function that calculates the square of a number.
#!/usr/bin/python |
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 |
The output will be:
You called multiply(x,y) with the values x = 3 and y = 2 |
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 |
Output:
|
We are by no means limited to single word defintions in the value part. A demonstration:
#!/usr/bin/python |
Output:
|
Manipulating the dictionary
We can manipulate the data stored in a dictionairy after declaration. This is shown in the example below:
#!/usr/bin/python |
Output:
|
If you are new to Python programming, I highly recommend this book.
python cast
Python determines the datatype automatically, to illustrate:
|
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 |
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" |
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:
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 |
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 |
File Modes in Python: A Brief Summary
When working with files, Python offers various modes. Here’s a summary of the essential ones:
Flag | Action |
---|---|
r | Open file for reading |
w | Open file for writing (overwrites if exists) |
a | Open file for appending (retains existing content) |
b | Binary mode |
r+ | Open for both reading and writing |
a+ | Read and append |
w+ | Read and write (overwrites if exists) |
|
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 = ..).
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:
|
If you are new to Python programming, I highly recommend this book.
encapsulation in python
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 |
Output:
Hello |
To clarify method overloading, we can now call the method sayHello() in two ways:
obj.sayHello() |
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.
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 | #!/usr/bin/env python |
Output:
1 | Guido |
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 | #!/usr/bin/env python |
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:
- Inner classes are confined to a local scope, ensuring encapsulation.
- 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.
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 |
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 |
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 |
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 |
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 |
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 |
This will output:
WARNING:root:This is a warning! |
We can easily output to a file:
import logging |
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:
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 |
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 |
Output:
2015-06-25 23:24:01,153 Logging app started |
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 |
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 |
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 |
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 |
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 |
In this case the expression is always true, thus it simply sums up the elements of the list. Another example:
#!/usr/bin/env python |
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 |
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 |
Simple notation
If you use Python version 2.6 or a later version, you can use a simplified notation:
#!/usr/bin/env python |
Set Methods
Clear elements from set
To remove all elements from sets:
#!/usr/bin/env python |
Add elements to a set
To add elements to a set:
#!/usr/bin/env python |
Remove elements to a set
To remove elements to a set:
!/usr/bin/env python |
Difference between two sets
To find the difference between two sets use:
#!/usr/bin/env python |
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 |
Super-set
To test if a set is a super-set:
#!/usr/bin/env python |
Intersection
To test for intersection, use:
#!/usr/bin/env python |
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
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:
|
for Python 2.x use:
|
Debugging
Start debugging with:
|
(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.
You can set breakpoints using the b key. To continue execution until the next breakpoints, press the c key.
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
|
Example
A practical example:
|
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:
|
Press c or continue to go on with the programs execution until the next breakpoint
|
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:
|
Related course
Module enum installation
To use enums module, you need Python 3.4; To install for Python 3.4:
|
For older versions (Python 2.7):
|
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
|
or as a one liner:
|
enum example (without using modules)
The old way of creating enums is:
|