Categories
Python

Quick Intro to Python Loops

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at various kinds of loops that we can use in Python apps to run repeated code.

while Loop Statements

We can use the while loop to run code repeatedly while a condition is True .

It consists of the while keyword, a condition to evaluate, a colon, and then the code to run indented below it.

For example, we can write the following while loop to print a message repeatedly:

x = 0  
while x < 5:  
    print('Hello.')  
    x = x + 1

In the code above, we have x set to 0. Then we use the while loop to print ‘Hello.’. Next, we increment x by 1. We do this repeatedly until x reaches 5.

while loops are useful for looping keeping the loop running until we meet a condition. It doesn’t have to have a finite, determinate amount of iterations.

For example, we can use the while loop until the user guesses the right number as follows:

guess = 0  
while int(guess) != 5:  
  print('Guess a number')  
  guess = input()  
print('You got it')

In the code above, as long as guess doesn’t evaluate to 5 when we convert it to an integer, the while loop will keep running.

Once we entered the right guess, which is 5, the loop will end.

break Statements

The break keyword is used to terminate a loop before the loop ends.

For example, we can rewrite the example above, with break instead of the condition in the while loop as follows:

guess = 0  
while True:  
  if int(guess) == 5:  
    break  
  print('Guess a number')  
  guess = input()  
print('You got it')

In the code above, we have an infinite while loop that has the condition to end the loop with break when we int(guess) returns 5.

The rest of the code works the same way as before.

continue Statements

We can use the continue statement to move on to the next iteration of the loop.

For example, we can use it as follows:

x = 0  
while x < 5:  
  x = x + 1  
  if x == 2:  
    continue  
  print(x)

The code above prints the value of x if it’s not 2. This is because if x is 2, we run continue to skip to the next iteration.

Truthy and Falsy Values

Python has the concept of truthy and falsy values. Truthy values are automatically converted to True when we use them where we have condition checks.

Falsy values are converted to False when we use them for condition checks.

0, 0.0, and '' (the empty string) are all considered False , while all other values are considered True .

For example, we can write a program to prompt users to enter a name and won’t stop until they enter one as follows:

name = ''  
while not name:  
  print('Enter your name:')  
  name = input()  
print('Your name is', name)

In the code above, we use not name to check if name is an empty string or not. If it is, then we keep showing 'Enter your name.' until they enter one.

Once they did, we display the last line with the name .

for Loops and the range() Function

We can use the for loop to loop through a certain number of items.

For example, we can use the for loop with the range function to display numbers from 0 to 4 as follows:

for i in range(5):  
    print(i)

In the code above, the range function returns integers starting from 0 as we and increments the number as we loop up to the number passed into the range function minus 1.

As we can see, the for loop consists of the for keyword, a variable name, the in keyword, a call to the range function, a colon , and then the block of code to run in the loop.

We can also use break and continue statement inside for loops as we did in while loops.

The range function can take 3 arguments, where the first is the starting number and the 2nd argument is the ending number. The loop will terminate when it reaches the ending number minus 1.

The 3rd argument is the increment to increase the variable by in each iteration.

For example, we can write the following code to print all odd numbers between 1 and 10:

for i in range(1, 10, 2):  
    print(i)

We should see:

1  
3  
5  
7  
9

printed because in our range function call, we passed in 1 as the starting number, 10 as the ending number, and 2 to increment i by 2 in each iteration.

Conclusion

We can use while loops to repeatedly run a block of code until a condition is met. This means the loop can run an indeterminate number of iterations.

break is used for ending a loop before it ends. continue is used to skip the loop to the next iteration.

for loops are used for repeatedly run code a finite number of times. It’s used with the range function to do the finite iteration.

Categories
Python

Python String Methods You May Have Missed

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to use Python string methods to manipulate strings.

The upper(), lower(), isupper(), and islower() Methods

The upper method converts all characters of a string to upper case and returns it.

For instance, given the following string:

msg = 'Hello Jane'

Then running msg.upper() returns ‘HELLO JANE’ .

The lower method converts all characters of a string to lower case and returns it.

Therefore, msg.lower() returns ‘hello jane’ .

isupper checks if the whole string is converted to upper case.

For instance, if we have:

msg = 'HELLO JANE'

Then msg.isupper() returns True .

islower checks if the whole string is converted to lower case. For instance, given the following string:

msg = 'hello jane'

Then msg.islower() returns True .

upper and lower can be chained together since they both return strings.

For instance, we can write:

msg.upper().lower()

Then we get:

'hello jane'

returned.

The isX() Methods

There are also other methods for checking for various aspects of the string.

isalpha checks if the whole string consists of only letters and isn’t blank.

For instance, given the following string:

msg = 'hello jane'

Then msg.isalpha() returns False since it has a space in it.

isalnum checks is a string only consists of letters and numbers and returns True if it is.

For example, given the following string:

msg = 'hello'

Then msg.isalnum() returns True .

isdecimal returns True is string consists only of numeric characters and isn’t blank.

For instance, if we have:

msg = '12345'

Then msg.isdecimal() returns True .

isspace returns True if the string only consists of tabs, spaces, and newlines and isn’t blank.

For instance, if we have the following string:

msg = '\n '

Then msg.isspace() returns True .

istitle returns True if the string only has words that begin with an upper case letter followed by only lower case letters.

For instance, if we have the following string:

msg = 'Hello World'

Then msg.istitle() returns True .

The startswith() and endswith() Methods

The startswith method returns True if a string starts with the substring passed in as the argument.

For instance:

'Hello, world'.startswith('Hello')

returns True .

The endswith method returns True if a string ends with the substring passed in as the argument.

For instance:

'Hello, world!'.endswith('world!')

returns True since our string ends with world! .

The join() and split() Methods

The join method combines multiple strings in a string array into one string by the character that it’s called on.

For instance, we can write:

','.join(['apple', 'orange', 'grape'])

which returns ‘apple,orange,grape’.

The string that it’s called on is inserted between the entries.

The split method is used to split a string into a list of substrings by the character that it’s called on.

For instance:

'My name is Jane'.split(' ')

returns [‘My’, ‘name’, ‘is’, ‘Jane’] .

Splitting Strings with the partition() Method

The partition method splits a string into text before and after a separator string.

For instance:

'My name is Jane'.partition('is')

returns:

('My name ', 'is', ' Jane')

We can use the multiple assignment syntax to assign the parts into their own variables since the string is called on is always split into 3 parts.

For instance, we write the folllowing:

before, sep, after = 'My name is Jane'.partition('is')

Then before has the value ‘My name ‘ . sep is 'is' , and after is ' Jane' .

Justifying Text with the rjust(), ljust(), and center() Methods

The rjust method moves a string by the given number of spaces passed in as the argument to the right.

For instance:

'foo'.rjust(5)

returns:

'  foo'

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.rjust(5, ‘-’) returns ‘--foo’

ljust adds spaces by the number of that’s passed into the argument to the right of the text.

For instance:

'foo'.ljust(5)

returns:

'foo  '

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.ljust(5, ‘*’) returns ‘foo**’

The center method adds the number of spaces passed in as the argument to the left and the right of the string.

For instance:

'foo'.center(15)

returns:

'      foo      '

It also takes a second argument to fill in something instead of spaces. For instance, ‘foo’.center(5, ‘*’) returns ‘*foo*’ .

Conclusion

Python has string methods to convert strings to upper and lower case.

We can also add spaces and other characters to the string.

Multiple strings can also be joined together. Also, they can be split off into multiple strings.

There’re also many methods to check strings for various characteristics.

Categories
Python

Using Regex with Python

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to use regex with Python to make finding text easier.

Finding Patterns of Text with Regular Expressions

Regular expressions, or regexes, are descriptions for a pattern of text.

For instance, \d represents a single digit. We can combine characters to create regexes to search text.

To use regexes to search for text, we have to import the re module and then create a regex object with a regex string as follows:

import re  
phone_regex = re.compile('\\d{3}-\d{3}-\d{4}')

The code above has the regex to search for a North American phone number.

Then if we have the following string:

msg = 'Joe\'s phone number is 555-555-1212'

We can look for the phone number inside msg with the regex object’s search method as follows:

import re  
phone_regex = re.compile('\d{3}-\d{3}-\d{4}')  
msg = 'Joe\'s phone number is 555-555-1212'  
match = phone_regex.search(msg)

When we inspect the match object, we see something like:

<re.Match object; span=(22, 34), match='555-555-1212'>

Then we can return a string representation of the match by calling the group method:

phone = match.group()

phone has the value '555-555-1212' .

Grouping with Parentheses

We can use parentheses to group different parts of the result into its own match entry.

To do that with our phone number regex, we can write:

phone_regex = re.compile('(\d{3})-(\d{3})-(\d{4})')

Then when we call search , we can either get the whole search string, or individual match groups.

group takes an integer that lets us get the parts that are matched by the groups.

Therefore, we can rewrite our program to get the whole match and the individual parts of the phone number as follows:

import re  
phone_regex = re.compile('(\d{3})-(\d{3})-(\d{4})')  
msg = 'Joe\'s phone number is 123-456-7890'  
match = phone_regex.search(msg)  
phone = match.group()  
area_code = match.group(1)  
exchange_code = match.group(2)  
station_code = match.group(3)

In the code above, phone should be ‘123–456–7890’ since we passed in nothing to group. Passing in 0 also returns the same thing.

area_code should be '123' since we passed in 1 to group , which returns the first group match.

exchange_code should be '456' since we passed in 2 to group , which returns the 2nd group match.

Finally, station_code should be '7890' since we passed in 3 to group , which returns the 3rd group match.

If we want to pass in parentheses or any other special character as a character of the pattern rather than a symbol for the regex, then we have to put a \ before it.

Matching Multiple Groups with the Pipe

We can use the | symbol, which is called a pipe to match one of many expressions.

For instance, we write the following to get the match:

import re  
name_regex = re.compile('Jane|Joe')  
msg = 'Jane and Joe'  
match = name_regex.search(msg)  
match = match.group()

match should be 'Jane' since this is the first match that’s found according to the regex.

We can combine pipes and parentheses to find a part of a string. For example, we can write the following code:

import re  
snow_regex = re.compile(r'snow(man|mobile|shoe)')  
msg = 'I am walking on a snowshoe'  
snow_match = snow_regex.search(msg)  
match = snow_match.group()  
group_match = snow_match.group(1)

to get the whole match with match , which has the value 'snowshoe' .

group_match should have the partial group match, which is 'shoe' .

Optional Matching with the Question Mark

We can add a question mark to the end of a group, which makes the group optional for matching purposes.

For example, we can write:

import re  
snow_regex = re.compile(r'snow(shoe)?')  
msg = 'I am walking on a snowshoe'  
msg_2 = 'I am walking on snow'  
snow_match = snow_regex.search(msg)  
snow_match_2 = snow_regex.search(msg_2)

Then snow_match.group() returns 'snowshoe' and snow_match.group(1) returns 'shoe' .

Since the (shoe) group is optional, snow_match_2.group() returns 'snow' and snow_match_2.group(1) returns None .

Conclusion

We can use regexes to find patterns in strings. They’re denoted by a set of characters that defines a pattern.

In Python, we can use the re module to create a regex object from a string.

Then we can use it to do searches with the search method.

We can define groups with parentheses. Once we did that, we can call group on the match object returned by search.

The group is returned when we pass in an integer to get it by their position.

We can make groups optional with a question mark appended after the group.

Categories
Python

Organize Code with Python Functions

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to define and use Python functions.

Functions

A function is a piece of code that we can invoke repeatedly in different places.

It’s defined with the def keyword as follows:

def greet(name):  
  print('Hello', name)

The greet function above has one parameter. We can pass in an argument to set the value of the parameter when we call it.

Functions always start with the def keyword, then the function name, then parentheses and zero or more parameters inside. Then the first line ends with a colon.

The code for the function is indented inside the function block.

For example, we can call greet as follows:

greet('Joe')

Then we see:

Hello Joe

displayed on the screen since we passed in 'Joe' as the argument of the greet function call.

Functions can call other functions. For example, we can write the following code to make our greet function call another function:

def greet(first_name, last_name):  
  print('Hello', full_name(first_name, last_name))

def full_name(first_name, last_name):  
  return '%s %s' % (first_name, last_name)

greet('Jane', 'Smith')

In the code above, our greet function calls the full_name function which returns the full name constructed by combining first_name and last_name .

In the full_name function, we use the return keyword to return the computed result of combining the first_name and last_name parameters into one string.

The function ends whenever we use the return keyword. Nothing below it will run.

Therefore, we can use it as follows to return the values that we want to return conditionally by using multiple return statements as follows:

import random

def crystal_ball(num):  
  if num == 1:  
    return 'It is a great day'  
  elif num == 2:  
    return 'It is a lucky day'  
  elif num == 3:  
    return 'It is an auspicious day'

r = random.randint(1, 4)  
fortune = crystal_ball(r)  
print(fortune)

In the code above, we have if statements to return something whenever the value of num is 1, 2, or 3.

If num is 1, then crystal_ball returns 'It is a great day' .

If num is 2, then crystal_ball returns 'It is a lucky day' .

If num is 3, then crystal_ball returns ‘It is an auspicious day’ .

Once something is returned, crystal_ball function stops running.

We can then assigned the returned value to another variable for storage as we did by writing:

fortune = crystal_ball(r)

Then we printed out the value of fortune .

The None Value

In Python, we have the value None to represent no value. None has the type NoneType .

None has the capital N .

We can use it as a return value of something that shouldn’t have a value.

For example, the print returns None since there’s nothing to return. It just prints a value on the screen.

If we write:

foo = print('Hello!')  
print(None == foo)

In the code above, we should see:

Hello!  
True

printed on the screen since print returns None , so the value that’s assigned to foo would be None .

Therefore, None == foo returns True .

Keyword Arguments

Python functions can have named arguments. This way, we know what values the arguments are set when we’re passing them.

For example, we can pass in named parameters as follows:

def full_name(first_name, last_name):
  return '%s %s' % (first_name, last_name)

print(full_name(first_name='Jane', last_name='Smith'))

In the code, we called full_name by writing:

full_name(first_name='Jane', la_name='Smith')

Now we know that we’re passing 'Jane' as the value of the first_name parameter and 'Smith' as the value of the last_name parameter.

The Call Stack

The call stack is a data structure that tells us what function we’ve called in the order they’re called.

The earliest called function is at the bottom of the stack, and the later ones are higher in the stack.

For example, in the example we have earlier:

def greet(first_name, last_name):
  print('Hello', full_name(first_name, last_name))

def full_name(first_name, last_name):
  return '%s %s' % (first_name, last_name)

greet('Jane', 'Smith')

Our call stack would have the greet function at the bottom and full_name at the top.

Local and Global Scope

Variables that are inside a function has a local scope. It’s only available inside the function and nested function inside it.

They can’t be referenced outside the function.

Anything at the top level of a Python file has global scope.

Variables with global scope can be accessed inside anything located in a lower function like a block or function.

For example, if we have:

x = 1

def show_x():
  print(x)

show_x()

Then we can reference x inside the show_x function as x has global scope.

On the other hand, if we have:

def show_x():  
  x = 1

print(x)

We’ll get an error saying x isn’t defined.

Having scopes lets us narrow down the scope of the code that can cause a bug. We don’t have to search through the whole program to troubleshoot everything.

Conclusion

Functions are used to organize code into reusable pieces. They take parameters and we call them by passing in arguments.

They can return something with the return keyword. Returned values from a function can be assigned to other variables.

Variables inside functions have a local scope. They can’t be accessed from outside the function.

On the other hand, variables at the top level have global scope, which can be accessed inside functions.

Categories
Python

Quick Intro to Python Modules

Python is a convenient language that’s often used for scripting, data science, and web development.

In this article, we’ll look at how to define and use modules to separate large programs into small pieces.

Importing Modules

Most programs are more than a few lines long. This means that they have to split into multiple small pieces for them to be manageable.

Python programs can be split into modules. Each module is a Python program. For example, the math module has math functions and the random module has random number-related functions.

To use Python modules in another module, we have to use the import keyword and the name of the module.

If we want to import more than one module, we can separate the module names by commas.

For example, we can import the random module and then print out a randomly generated number by calling the randrange function as follows:

import random  
print(random.randrange(0, 101, 2))

In the code above, we import the random module and called the randrange function with the start and end numbers of the number we want to generate as the first 2 arguments.

The end number is excluded from the range of numbers that can be generated.

The last argument has the number of steps to skip between the start and end numbers.

The code above will generate an even number in the range of 0 to 100 inclusive.

from import Statements

We can just import one member of a Python module with the from keyword.

For example, we can just import the randrange function from the random module as follows:

from random import randrange  
print(randrange(0, 101, 2))

In the code above, we just import the randrange function instead of the whole module.

But the rest of the logic is the same.

This is more efficient since we didn’t import everything.

Create Our Own Modules

Anything that is at the top level of a Python file can be imported from a Python module.

For example, we can create a module called foo.py as follows:

x = 1

Then in main.py , we can import and use it as follows:

import foo  
print(foo.x)

We should see 1 on the screen since we have x set to 1 and imported it.

The Module Search Path

Python modules are searched in the code directory, the path set as the value of the PYTHONPATH environment variable, and the default directory that’s set when Python is installed.

The dir() Function

The dir function is used to list the members of a Python module.

For example, we can print a list of members of the math module as follows:

import math  
print(dir(math))

Then we get the following on the screen:

['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

We can see the functions that we can call from the array above.

Packages

We can put Python files in directories to organize them into packages.

For example, we can put foo.py in the package folder, add __init__.py to it.

Then we can import and use package’s members as follows:

from package import foo  
print(foo.x)

Importing * From a Package

The asterisk character indicates that we import all the members from a package.

For example, if we write:

from sound.effects import *

we import all the members from the effects module in the sound package.

This is bad practice because the code is inefficient because we import everything. Also, we may have clashing names since we import more members than we’re supposed to.

Import as

We can use the as keyword to import a module with an alias name. This helps us avoid clashes of names from different modules where we have members that have the same name in different modules.

For example, we can write the following code:

import random as r  
print(r.randrange(0, 101, 2))

to import the random module with an alias r and reference that instead of random .

We can also import a member with as an alias as follows:

from random import randrange as rr  
print(rr(0, 101, 2))

We can call rr instead of randrange to call randrange .

Conclusion

We can define and import Python modules by creating a Python code file and then we can import the members of the Python file.

This lets us divide code into small pieces.

Also, we can organize Python modules into packages by putting module files in folders and add __init__.py to each directory.