How to find the smallest number in Python

In this post, we will learn how to find the smallest number. The first program uses the if statement to achieve that. The second program, the recommended way, uses the built-in min function and a list. Code using the if…

How to add two numbers in Python

Let’s see how two perform a very common and simple task when learning a programming language: adding two numbers. In python the code for adding two numbers is very straightfoward. Adding numbers directly first_number = 32 second_number = 8 total…

Scope in Python

There are two scopes: local and global. Global Scope A global scope allows you to use the variable anywhere in your program. If your variable is outside a function, it has a global scope by default. name = "Bob" def…

isalpha(): checking letters only in a string in Python

Use the isalpha() method to check if a string only contains letters. word = 'beach' print(word.isalpha()) #output: True word = '32' print(word.isalpha()) #output: False word = 'number32' print(word.isalpha()) #output: False word = 'Favorite number is blue' #notice the space between…

How to check leap year in Python

The rules to check a leap year are: The year has to be divisible by four, that is, the remainder of the division is 0. The year cannot be divisible by 100, that is, the remainder of the division is…

How to check if a number is prime in Python

A prime number is an integer greater than one that is only divisible by one and itself. def check_prime(number): if number <= 1: return False for divisor in range(2, int(number**0.5)+1): if (number % divisor) == 0: print(divisor,'*', number//divisor, '=', number)…

How to swap two items in a list in Python

In this post, I’m gonna show how to swap two items in a list. This post is an extension of How to swap two variables in Python. Swap by index This first code snippet assumes you already know the index…

isdecimal(): checking decimals only in a string in Python

Use the isdecimal() method to check if a string only contains decimals, that is, only numbers from 0 to 9 and combinations of these numbers. Subscript, superscript, roman numerals, and other variations will be returned as False. word = '32'…