Categories

## Super Simple Python: Simple Calculator

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to build a simple calculator in under 30 lines of Python!

For a video version:

Unlike some of the Super Simple Python examples we’ve done, these don’t require any libraries!

## Defining the Calculator Functions

Since this is an episode of Super Simple Python, we’re going to be creating a Super Simple Calculator. This calculator will just perform addition, subtraction, multiplication, and division. Each of these functions will simply take two parameters, `a` and `b` and return the specified operation on `a` and `b`.

``````def add(a, b):
return a + b

def subtract(a, b):
return a - b

def multiply(a, b):
return a * b

def divide(a, b):
return a/b
``````

## Mapping the Calculator Functions

Once we’ve defined our functions, we’ll use a dictionary to map strings to the functions. One of the really nice things that’s unique to Python is that we can pass functions in as values in our dictionary. We’ll use an `ops` dictionary that contains our set of four operations mapped as a key-value pair of string to function.

Other than our dictionary of operations, we’ll also need a way to perform the specified operation on the two passed in values. Let’s create a function that takes three parameters: the first number, a string value corresponding to the operation, and the second number. This function will use the dictionary to map the string value to a function and then call that function on the numbers.

``````ops = {
"subtract": subtract,
"divide": divide,
"multiply": multiply
}

def perform(a, op, b):
function = ops[op]
return function(a, b)
``````

## Performing the Calculation

Everything is set up. Let’s do the calculation. We ask the user for three inputs, the numbers and the desired operation. Note that I wrapped the inputs of the numbers in an `int()` function, that is to turn these inputs from strings to integers. If you’d like to work with floating point numbers, you’ll have to use `float()` instead of `int()`. After we receive input from the user, we simply print out the returned value from the `perform` function we created earlier.

``````print("Input two numbers and an operator")
a = int(input("What is the first number? "))
op = input("Which operation would you like to perform?(add, subtract, multiply, or divide?) ")
b = int(input("What is the second number? "))
print(perform(a, op, b))
``````

An example printout should look like this:

What a coincidence:

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’re going to make a Python Madlib in under 15 lines of code.

We don’t need to import any libraries for this program, we’re just going to create a simple Python Madlib script. Much like the Inigo Montoya Introduction, we’ll be creating a set of texts to prompt the user. Unlike the introduction though, there will be no randomization. We’ll be taking string input and using it like we did in Rock, Paper, Scissors.

## Creating Text Prompts for Python Madlib

The first thing we need to do to create a Madlibs-like game is to create the text prompts. These are the sentences that are pre-created in Madlibs. We’ll create pieces of text that can have words attached to the end. For this example, we’ll be playing with the Humpty Dumpty nursery rhyme.

In a Madlibs game you are given a blank to fill in. For our example, we’ll create five text prompts.

``````text1 = "Humpty Dumpty sat on a"
text2 = "Humpty Dumpty had a great"
text3 = "All the king's men and all the king's"
text4 = "couldn't"
text5 = "Humpty Dumpty back"``````

Now that we’ve created the text prompts, we have to create a way for the user to “fill in the blanks”. We’ll simply use the Python `input` function which takes one parameter, a string to prompt the user with, and allows input from the user. In our case, we’ll use the texts we created earlier with an extra space for readability as the prompt. After each sentence, the user has a chance to complete the phrase.

``````word1 = input(text1+" ")
word2 = input(text2+" ")
word3 = input(text3+" ")
word4 = input(text4+" ")
word5 = input(text5+" ")``````

## Showing the Final Constructed Python Madlib

Once we have each of the five words or phrases that will finish each phrase, we can print out the final results to show the user their completed story. We’ll do this with a simple print statement. Notice that we don’t have any spaces at the end of each of the text prompts or the words. The print statement will add spaces by default when we separate the variables with commas.

``print(text1, word1, text2, word2, text3, word3, text4, word4, text5, word5)``

When we run our simple script, we should get an output like the one below. I answered with the words “doll”, “shawl”, “malls”, “ball”, and “on his doll”.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Basic Python: How to do Math in Python

If you’re doing anything data science or machine learning related in Python, you should know some math. This post is for anyone looking to get into a Python role working with data or machine learning. First, we’ll cover how to use base Python (no imported libraries) to do basic math on floats and integers. Then, we’ll cover how to use some of the functions in the `math` library in Python. This is by no means a comprehensive guide and there will be more advanced guides in the future, so be on the lookout!

## Basic Python Math Operators

There are four basic math operations – addition, subtraction, division, and multiplication. We actually went over all of these in our post on How to Build Your Own Simple Calculator. Here we’ll go over what the operators are. The operators are pretty much the same as you’d expect as if you were writing them in WolframAlpha. The add symbol is “+”, the subtract symbol is “-”, the multiply symbol is “*”, and the divide symbol is “/”.

``````def add(a, b):
return a + b

def subtract(a, b):
return a - b

def multiply(a, b):
return a * b

def divide(a, b):
return a/b
``````

## Operators for Integer Math in Python

Great, those were all the basics, let’s take a look at some less intuitive operators. In traditional math, these are used only on integers. In Python, you can actually use these on floats too (except integer divide) but you may not get an exact answer. The operators we’ll look at in this section are integer divide (“//”), modulo (“%”), and exponent (“**”). The modulo operator gives you the remainder of `a%b`, and the exponent operator, `a**b`, will give you `a` raised to the `b` power.

``````def integer_divide(a, b):
return a//b

def modulo(a, b):
return a%b

def exponent(a, b):
return a**b
``````

## Python Math Module Functions You Need to Know

These aren’t the only math module functions, but these are pretty much the only ones you need to know for data science and machine learning. To use these functions you’ll need to import the `math` library. We’re going to go over eight functions that you’ll need to know.

1. Square Root – takes a square root of `a`
2. Power – raise `a` to the `b` power, it’s the same as `a**b`
3. Custom Logarithm – allows you to take a logarithm of `a` in base `b`
4. Exponential – returns `e` to the `a` power. The number `e` is Euler’s Number
5. Natural Logarithm – the opposite of the exponential, gives the logarithm in base `e`.
6. Base 10 Logarithm – takes a logarithm of `a` in base 10
7. Base 2 Logarithm – takes a logarithm of `a` in base 2
8. Hyperbolic Tangent – this one is specific to ML, as this is the activation function used in Recurrent Neural Networks, an important part of Natural Language Processing.

``````import math

def _sqrt(a):
return math.sqrt(a)

def _pow(a, b):
return math.pow(a, b)

def _log(a, b):
return math.log(a, b)

def _exp(a):
return math.exp(a)

def natural_log(a):
return math.log(a)

def _log10(a):
return math.log10(a)

def _log2(a):
return math.log2(a)

def _tanh(a):
return math.tanh(a)``````

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Tower of Hanoi

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering the Tower of Hanoi puzzle game in 10 lines of Python!

We’ve covered many different types of games in the Super Simple Python series so far including the High Low Guessing Game, Rock Paper Scissors, and Hangman. This is the first game that we’re covering that has a recursive solution. The recursive solution is not the only solution, just the simplest.

The rules of the game are simple:

1. Only 1 disk may be moved at a time
2. Each move consists of taking the top disk from one stack and placing it onto another
3. No disk may be placed on top of a disk that is smaller than it

In this post, we will cover:

• The Recursive Tower of Hanoi Solution in Python
• Tower of Hanoi with 3 Disks Python Solution

## Recursive Tower of Hanoi Solution

To build a recursive solution to the Tower of Hanoi, we will build a function that takes four parameters. The parameters we’ll need are the number of disks, and representations of the start, middle, and end rods. If there’s only 1 disk, we’ll simply move that disk from the start rod to the end rod and return. Otherwise, we’ll run the recursive function on the set of disks minus 1 on two setups. First we’ll move a disk from the start to the middle rod, then from the middle to the end rod.

Why can we simply run this function recursively on the Tower of Hanoi puzzle but with one less disk? Solving the puzzle for `n` disks is the same as solving it for `n-1` disks. This recursive solution allows us to apply that `n-1` logic by moving the `n-1` disks from the start to the middle and then the middle to the end.

``````def tower_of_hanoi(disks, start, middle, end):
if disks == 1:
print(f"Move disk 1 from {start} to {end}")
return
tower_of_hanoi(disks-1, start, end, middle)
print(f"Move disk {disks} from {start} to {end}")
tower_of_hanoi(disks-1, middle, start, end)``````

### Showing the Tower of Hanoi Solution for Three Disks

Okay, now that we’ve created our recursive solution to the Tower of Hanoi, let’s take a look at it. For this example, we’ll take a three disk puzzle and take a look at the solution. We’ll label our rods as `A`, `B`, and `C`.

``````number_of_disks = 3
tower_of_hanoi(number_of_disks, 'A', 'B', 'C')``````

When we run our program, it will show us a solution like the one below. This is the same as the solution shown in the gif above.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Word Count

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to get the word count from a text in under 5 lines of code!

Video version:

So far in the Super Simple Python series, we’ve mostly covered programs using the `random` library like the Password Generator, or building and using functions like the Simple Calculator or Generating a Card Deck. This episode is going to be on building and using a function. The text we’ll be using is taken from this post on Agrivoltaics, the combination of agriculture and solar panels.

## Test Text

text = “More broadly, agrivoltaic systems create a number of dual-use synergies between the solar panels and agricultural crops, which unlocks benefits for all aspects of the system: solar panel PV performance, crop yields, and economic benefits for the farmer. Solar PV panel performance increases for a number of reasons. Firstly, because the panels are placed above the crops, this means they are farther off the ground (and closer to the sun) so they will have increased efficiency of power generation. Secondly, because the land under the solar panel is now cropland, it stays cooler and prevents the ground under the solar panel from heating up too much, which in turn increases the efficiency of the solar panel. Agrivoltaic systems also generate significant benefits for crop yield. The solar panels can function as a protective foil, decreasing the destructive impacts of weather and wind on crop yield. Furthermore, the solar panels can be placed in a way to optimize light availability for the crops. Finally, agrivoltaic systems introduce a number of direct economic benefits for farmers (aside from the cheap irrigation process described above). The presence of the solar panel can actually reduce unnecessary wind and solar radiation impacts on crops, which enables them to better retain water, which reduces the need for irrigation for farmers. The solar panels can also collect rainwater, which can further decrease irrigation costs. Finally, the presence of solar panels will increase property values for the land, which could enable the farmer to sell for a higher value. All of these benefits showcase the dual-use synergies between solar PV panels and agricultural operations present within an agrivoltaic system. In fact, pilot projects have shown substantial land use efficiency increases as a result of installing agrivoltaic systems (ranging from 60% to 186% increase) There is no doubt that we must scale up this application here in the US.”

https://www.greenshareenergy.com/blog/what-are-agrivoltaics

## Counting the Words

We don’t have any imports to deal with in this program. Let’s start off by creating our function, `word_count`. The function will take one input, the text, which we expect to be a string. In the function, we will use the `split` function of strings to split the input string on spaces. We’ll save the split string into a list and return the length of the list. This should give us the number of words in a text.

``````def word_count(text: str):
_list = text.split(" ")
return len(_list)

print(word_count(text))
``````

Finally, we run our program and we should see the number of words within the passed in text.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Prime Factorization

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to prime factorize a number in less than 25 lines of Python!

For the video version of making a prime factorizer in Python:

The Super Simple Python series has been pretty focused on simple games and simulators like the Dice Roll Simulator, the High Low Guessing Game, and Rock Paper Scissors. This is the second piece in this series about math after the post about checking if a number is a square.

# Check for Factors in Order

How do we do a prime factorization? We simply loop through the numbers less than the square root of our number and divide out all the prime numbers in order. Let’s create a function that takes one parameter, `num`, that we expect to be an integer.

We’ll start by handling the edge case the `num` is 1. Why anyone would ever prime factor 1, I have no idea. We’ll start by creating an empty list of factors and starting off the loop at `n=2`, the smallest prime. Instead of checking if `n` is less than the square root of `num`, we’ll check if the square of `n` is less than or equal to `num`. While `n` squared is less than the num we’ll check if the number is divisible by `n`. If it is, then we will append `n` to our list of factors and divide `num` by `n`. Else, we’ll increment `n` by one.

At the end of our loop, if `num` is not 1, then the remaining factor must be prime, and we’ll append that to our list of factors before we return the list.

``````def prime_factorization(num: int):
# deal with edge cases
if num == 1:
return [1]
# set up empty list of factors
factors = []
# start at 1
n = 2
# factor up to sqrt num - there's no prime factors
# above the sqrt of a number
while n**2 <= num:
# check if the number is divisible by the factor
if num % n == 0:
factors.append(n)
num //= n
else:
n += 1
# if we have a number greater than 1 at the end
# that number is a prime factor
if num > 1:
factors.append(num)

return factors``````

## Check some Prime Factorizations

We can really prime factorize any number we want. I chose these 5 for fun.

``````print(prime_factorization(225))
print(prime_factorization(1776))
print(prime_factorization(2012))
print(prime_factorization(893))
print(prime_factorization(7392))``````

When we prime factor these numbers we’ll see an output like the one below.

Final note: we can increment `n` by 1 each time in the while loop because any non-primes will be skipped automatically, they won’t divide `num`. My question for you is why? Drop a comment below to let me know.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Two Ways to Get LCM

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering two ways to get the Least Common Multiple (LCM) of two numbers in under 10 lines of Python each!

We’ve covered a lot of different kinds of programs in the Super Simple Python series. We’ve covered programs using the `random` library like the Password Generator, functional programs like the Unit Convertor, and math programs like the Prime Factorizer. This one falls in the math category.

We’re going to cover:

• What is a Least Common Multiple?
• How to do LCM with GCD
• How to do Iterative LCM in Python
• Testing our LCM Functions

## What is the Least Common Multiple?

The Least Common Multiple of two numbers is the smallest number that is divisible by both numbers. There are a few ways to calculate this. For this post we’re going to cover two of the simplest ways to calculate this. The first way we’ll go over is by calculating the product of both numbers and dividing by their Greatest Common Denominator. The second way is to iteratively add the smallest number to itself until we reach a number that is divisible by the larger number.

## LCM with GCD in Python

In a recent Super Simple Python post, we covered how to get the Greatest Common Denominator. For this example, we’ll use the recursive GCD function to calculate our LCM. To do this we’ll first create a recursive GCD function. That function will take two integers as input and recursively calculate the GCD.

Our LCM function will also take two integers as parameters. It will simply return the product of the two inputs divided by the GCD. I wrap this in an `int()` function simply to make the return look pretty, otherwise it will return a float trailing with `.0`. Another way to do this is to use the integer divide operator, `//` instead of `/`.

``````def gcd(x: int, y: int):
if y == 0:
return x
return gcd(y, x%y)

def lcm_w_gcd(x: int, y: int):
return int(x * y/gcd(x, y))``````

## Iterative LCM in Python

To iteratively calculate the LCM we will also need two parameters. We could enforce that `x` must always be bigger than `y` or vice versa, but we won’t. We’ll simply start off the function by finding which one of them is larger. Once we know which number is larger, we start off our Least Common Multiple with the smaller number and iteratively add the smaller number to it until the sum is divisible by the larger number. Finally, we return that number as the LCM.

``````def iterative_lcm(x: int, y: int):
if x < y:
small = x
big = y
else:
small = y
big = x
lcm = small
while lcm % big != 0:
lcm += small
return lcm``````

## Testing

I’ve prepared three test cases for us to test with both functions. I’ve commented the expected output next to each number.

``````print(lcm_w_gcd(27, 3)) # 27
print(lcm_w_gcd(15, 55)) # 165
print(lcm_w_gcd(21, 99)) # 693

print(iterative_lcm(27, 3)) # 27
print(iterative_lcm(15, 55)) # 165
print(iterative_lcm(21, 99)) # 693``````

When we run the function we get output like the image below, as expected.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Two Ways to Get GCD

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering two ways to get the Greatest Common Denominator (GCD) of two numbers in just 3 lines of Python each!

We’ve covered a lot of different kinds of programs in the Super Simple Python series. We’ve covered programs using the `random` library like the Dice Roll Simulator, infrastructural programs like the Card Deck Generator, and math programs like the Prime Factorizer. This one falls in the math category.

Watch the video here:

# Euclidean Algorithm

Euclid is a famous Greek mathematician. He came up with countless numbers of math theories, including the Euclidean Algorithm. The Euclidean Algorithm is a simple way to find the Greatest Common Denominator of two integers. Given two integers, we subtract the smaller from the larger until one of the numbers is equal to 0. The remaining positive integer is the Greatest Common Denominator. Let’s take a look at the Euclidean Algorithm in practice.

## Iterative Implementation in Python

The first implementation of the Euclidean Algorithm in Python that we’ll take a look at is how to iteratively get the GCD of two numbers. This function will take two integers, `x`, and `y`, and return the Greatest Common Denominator. It doesn’t matter if you pick `x` or `y` for the condition in the `while` loop, for this example, we’ll pick `y`. While `y` is not yet 0, we’ll set the new values of `x` and `y` to `y` and the remainder when `x` is divided by `y`. At the end of the loop, `y` will be 0, and we return `x` as the GCD.

``````def iterative_gcd(x: int, y: int):
while(y):
x, y = y, x%y
return x
``````

## Recursive Implementation in Python

The second implementation of the Euclidean Algorithm in Python we’ll implement is the recursive implementation. Looking at the iterative function above, it looks like it does the same thing every single step right? That’s a surefire sign that there is a way to recursively implement this function. Just like our iterative function, our recursive function will take two integers, `x` and `y`, as input.

In this case, we’ll build in an `if` statement to stop the recursion when one of the numbers is equal to 0. Once again, we choose `y` arbitrarily. We swapped `x` and `y` with `y` and the remainder when `x` is divided by `y` in the iterative version. In the recursive version, we’ll just return the function when the inputs `x` and `y` are swapped with `y` and the remainder when `x` is divided by `y`.

``````def recursive_gcd(x: int, y: int):
if y == 0:
return x
return recursive_gcd(y, x%y)``````

## Testing

Now let’s take a look at some examples of our implementations. I’ve written 5 examples that we’ll test with both implementations. I’ve also commented the expected output next to them.

``````print(iterative_gcd(10, 20)) # 10
print(iterative_gcd(33, 41)) # 1
print(iterative_gcd(48, 64)) # 16
print(iterative_gcd(99, 81)) # 9
print(iterative_gcd(210, 70)) # 70

print(recursive_gcd(10, 20)) # 10
print(recursive_gcd(33, 41)) # 1
print(recursive_gcd(48, 64)) # 16
print(recursive_gcd(99, 81)) # 9
print(recursive_gcd(210, 70)) # 70``````

When we run our program we should see something like the following image. Just like we expected.

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: Is this a Square Number?

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to check if a number is a square in just 5 lines of Python!

For the video version of checking if a number is a square in Python:

So far, this series has covered a lot of posts using the `random` library like the Random Number Generator, the Dice Roll Simulator, and the Password Generator. This is the first episode of Super Simple Python that is under 10 lines of code. We’re going to do this with the help of the `math` library.

## Check if a Number is Square

There are many ways to check if a number is a square in real life. What’s the easiest way? Take a square root and check if the square root is an integer or not. Luckily, we can just use the `sqrt` function from the `math` Python library to do that. We don’t even have to know how to do the actual math for this program.

We’ll start off our program by importing the `math` library. The `math` library is native to Python so we don’t have to install it. Next, let’s create a function to check if a number is a square or not. The function will take one parameter, `num`, which we expect to be an integer. This is the cool part. We can handle all the logic in one line using the `math` library. We use the `sqrt` function to get the square root of the number, and then we call the `is_integer()` function on that to check if the result is an integer. If the result is an integer, we return True. If it’s not, then we return `False` by default. Note that we can also choose to use an `else` statement to return False, but we don’t need to.

``````import math

def is_square(num: int):
if math.sqrt(num).is_integer():
return True
return False

print(is_square(20))
print(is_square(100))
print(is_square(625))
print(is_square(1337))
print(is_square(2025))``````

If we test the above numbers, 20, 100, 625, 1337, and 2025 we should get False, True, True, False, True as shown in the image below:

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$

Categories

## Super Simple Python: The Perfect Introduction

Super Simple Python is a series of Python projects you can do in under 15 minutes. In this episode, we’ll be covering how to build a randomized perfect introduction using the Inigo Montoya method in 25 lines of Python.

For a video version:

As with many of the Super Simple Python projects, this one uses the `random` library. Other projects we’ve done that have also used the `random` library include Rock Paper Scissors, a Dice Roll Simulator, and the Password Generator

Before we get into the code, we should cover what the Inigo Montoya method is. Inigo Montoya is a character from the Princess Bride. He delivers the perfect introduction. “Hello. My name is Inigo Montoya. You killed my father. Prepare to die.” This introduction is easily broken down into four parts: a greeting, his name, a relevant personal link, and expectations.

## Set Up the Inigo Montoya Method

Of course we will begin our program by importing the `random` library. After importing the library, let’s set up how we’ll execute on the Inigo Montoya method. As covered above, there are four parts to his perfect greeting. We’re going to have a little fun, and create a randomized perfect introduction with these parts. To do this, we’ll create four lists, each corresponding to one part of the introduction.

``````import random

greetings = []
intros = []
expectations = []
``````

Now that we’ve set up our list containers, let’s set up some ways to introduce ourselves. I picked two possible greetings, two possible name introductions, three possible links, and four expectations. This sets up a possible `2 x 2 x 3 x 4 = 48` possible perfectly structured introductions. If you are a close friend or follow me on Tik Tok, you’ll recognize the second name introduction. Everything else is just about my online blogging and my goal of teaching you how to be a true engineer.

``````greetings.append("Hello. ")
greetings.append("Yo, what's up. ")

intros.append("My name is Yujian Tang. ")
intros.append("It's ya boi Ra. ")

links.append("You may know me from Super Simple Python. ")
links.append("I'm the owner of the Social Techies Discord server. ")
links.append("You may have seen my articles on Medium. ")

expectations.append("I'm going to teach you how to become a software engineer.")
expectations.append("I create the best software content in the world.")
expectations.append("I will show you how to actually learn engineering skills.")
expectations.append("If you want to truly learn Python in a useable manner, you should follow me.")``````

Now that we’ve set up the possible choices for the four parts of our perfect introduction let’s create it. We’ll use the `random.choice()` function from Python to randomly choose an element from each list. All we need to do is get one random choice from each list and add them up in order. Adding strings in Python concatenates them.

``````full_greeting = random.choice(greetings) + random.choice(intros) + random.choice(links) + random.choice(expectations)

print(full_greeting)
``````

When we print our greeting it will look something like this:

{{#message}}{{{message}}}{{/message}}{{^message}}It appears your submission was successful. Even though the server responded OK, it is possible the submission was not processed. Please contact the developer of this form processor to improve this message. Learn More{{/message}}

Submitting…

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

I started my professional software career interning for IBM in high school after winning ACSL two years in a row. I got into AI/ML in college where I published a first author paper to IEEE Big Data. After college I worked on the AutoML infrastructure at Amazon before leaving to work in startups. I believe I create the highest quality software content so that’s what I’m doing now. Drop a comment to let me know!

One-Time
Monthly
Yearly

#### Make a yearly donation

Choose an amount

\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00
\$5.00
\$15.00
\$100.00

Or enter a custom amount

\$