Python Program Examples – Simple Code Examples for Beginners

freeCodeCamp

freeCodeCamp

Python Program Examples – Simple Code Examples for Beginners

By Shittu Olumide

Mark Twain said that the secret of getting ahead is getting started. Programming can seem daunting for beginners, but the best way to get started is to dive right in and start writing code.

Simple code examples are a great way for beginners to get their feet wet and learn the basics of programming. In this article, I will provide a series of simple code examples that are perfect for Python beginners.

These examples cover a range of programming concepts and will help you develop a solid foundation in programming. Whether you're new to programming or just looking to brush up on your skills, these code examples will help you get started on your coding journey.

If you need to learn some Python basics, I've added some helpful resources at the end of this tutorial.

How to Build a Number Guessing Game in Python

In this project, you will create a simple number guessing game that allows the user to guess a random number between 1 and 100. The program will give hints to the user after each guess, indicating whether their guess was too high or too low, until the user guesses the correct number.

Code:

import random secret_number = random.randint(1, 100) while True: guess = int(input("Guess the number between 1 and 100: ")) if guess == secret_number: print("Congratulations! You guessed the number!") break elif guess < secret_number: print("Too low! Try again.") else: print("Too high! Try again.") 

Explanation:

How to Build a Simple Password Generator in Python

A password generator, as the name implies, generates a random password of a particular length using different combination of characters, and special characters.

Code:

import random import string def generate_password(length): """This function generates a random password of a given length using a combination of uppercase letters, lowercase letters, digits, and special characters""" # Define a string containing all possible characters all_chars = string.ascii_letters + string.digits + string.punctuation # Generate a password using a random selection of characters password = "".join(random.choice(all_chars) for i in range(length)) return password # Test the function by generating a password of length 10 password = generate_password(10) print(password) 

Explanation:

Note that this is a very simple password generator and may not be suitable for use in real-world scenarios where security is a concern.

How to Build a Password Checker in Python

We will build a password checker in this section. Its job is to check if a password is strong enough based on some of the criteria we set. It'll print an error if any of the password criteria isn't met.

Code:

# Define a function to check if the password is strong enough def password_checker(password): # Define the criteria for a strong password min_length = 8 has_uppercase = False has_lowercase = False has_digit = False has_special_char = False special_chars = "!@#$%^&*()-_=+[\|;:',/?" # Check the length of the password if len(password) < min_length: print("Password is too short!") return False # Check if the password contains an uppercase letter, lowercase letter, digit, and special character for char in password: if char.isupper(): has_uppercase = True elif char.islower(): has_lowercase = True elif char.isdigit(): has_digit = True elif char in special_chars: has_special_char = True # Print an error message for each missing criteria if not has_uppercase: print("Password must contain at least one uppercase letter!") return False if not has_lowercase: print("Password must contain at least one lowercase letter!") return False if not has_digit: print("Password must contain at least one digit!") return False if not has_special_char: print("Password must contain at least one special character!") return False # If all criteria are met, print a success message print("Password is strong!") return True # Prompt the user to enter a password and check if it meets the criteria password = input("Enter a password: ") password_checker(password) 

Explanation:

How to Build a Web Scraper in Python

A web scraper scrapes/gets data from webpages and saves it in any format we want, either .csv or .txt. We will build a simple web scraper in this section using a Python library called Beautiful Soup.

Code:

import requests from bs4 import BeautifulSoup # Set the URL of the webpage you want to scrape url = 'https://www.example.com' # Send an HTTP request to the URL and retrieve the HTML content response = requests.get(url) # Create a BeautifulSoup object that parses the HTML content soup = BeautifulSoup(response.content, 'html.parser') # Find all the links on the webpage links = soup.find_all('a') # Print the text and href attribute of each link for link in links: print(link.get('href'), link.text) 

Explanation:

How to Build a Currency Converter in Python

A currency converter is a program that helps users convert the value of one currency into another currency. You can use it for a variety of purposes, such as calculating the cost of international purchases, estimating travel expenses, or analyzing financial data.

Note: we will use the ExchangeRate-API to get the exchange rate data, which is a free and open-source API for currency exchange rates. But there are other APIs available that may have different usage limits or requirements.

Code:

# Import the necessary modules import requests # Define a function to convert currencies def currency_converter(amount, from_currency, to_currency): # Set the API endpoint for currency conversion api_endpoint = f"https://api.exchangerate-api.com/v4/latest/ " # Send a GET request to the API endpoint response = requests.get(api_endpoint) # Get the JSON data from the response data = response.json() # Extract the exchange rate for the target currency exchange_rate = data["rates"][to_currency] # Calculate the converted amount converted_amount = amount * exchange_rate # Return the converted amount return converted_amount # Prompt the user to enter the amount, source currency, and target currency amount = float(input("Enter the amount: ")) from_currency = input("Enter the source currency code: ").upper() to_currency = input("Enter the target currency code: ").upper() # Convert the currency and print the result result = currency_converter(amount, from_currency, to_currency) print(f"  is equal to  ") 

Explanation:

Conclusion

All these projects are very simple and easy to build. If you really want to improve your Python skills, I'd advise you to take the code, modify and edit it, and build upon it. You can turn many of these simple projects into much more complex applications if you want.

If you need to learn some Python basics, check out these helpful resources:

Let's connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.