• Latest
  • Trending
Python cheatsheet and snippets for beginners

Python cheatsheet and snippets for beginners

May 31, 2022
Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023
Vice President Dr. Bawumia inaugurates  ICT Hub

Vice President Dr. Bawumia inaugurates ICT Hub

April 2, 2023
Co-Creation Hub’s edtech accelerator puts $15M towards African startups

Co-Creation Hub’s edtech accelerator puts $15M towards African startups

February 20, 2023
Data Leak Hits Thousands of NHS Workers

Data Leak Hits Thousands of NHS Workers

February 20, 2023
EU Cybersecurity Agency Warns Against Chinese APTs

EU Cybersecurity Agency Warns Against Chinese APTs

February 20, 2023
How Your Storage System Will Still Be Viable in 5 Years’ Time?

How Your Storage System Will Still Be Viable in 5 Years’ Time?

February 20, 2023
The Broken Promises From Cybersecurity Vendors

Cloud Infrastructure Used By WIP26 For Espionage Attacks on Telcos

February 20, 2023
Instagram and Facebook to get paid-for verification

Instagram and Facebook to get paid-for verification

February 20, 2023
YouTube CEO Susan Wojcicki steps down after nine years

YouTube CEO Susan Wojcicki steps down after nine years

February 20, 2023
Inaugural AfCFTA Conference on Women and Youth in Trade

Inaugural AfCFTA Conference on Women and Youth in Trade

September 6, 2022
  • Consumer Watch
  • Kids Page
  • Directory
  • Events
  • Reviews
Thursday, 16 July, 2026
  • Login
itechnewsonline.com
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion
Subscription
Advertise
No Result
View All Result
itechnewsonline.com
No Result
View All Result

Python cheatsheet and snippets for beginners

by ITECHNEWS
May 31, 2022
in Data Science, Leading Stories
0 0
0
Python cheatsheet and snippets for beginners

EPTA-Forge-Python

Useful Links:

  • Replit – Online Compiler
  • Download Python
  • Github Repo (in PT-br)

Declaration of Variables and Types:

To declare a variable, just put its name, followed by an =, followed by the value you want to assign to it!

YOU MAY ALSO LIKE

French Telco Orange Hit by Cyber-Attack

ATC Ghana supports Girls-In-ICT Program


my_variable = 150

There are several types of variables, some of them are:

  • int (Integers)
  • str (String – Text)
  • char (Character)
  • float (Decimal numbers)
  • boolean (True or False)

Basic Mathematical Operations:

We can do several mathematical operations with Python, the most basic and most likely to be used are:

  • Addition -> Symbol: +
  • Subtraction -> Symbol: -
  • Multiplication -> Symbol: *
  • Exponentiation -> Symbol: **
  • Division -> Symbol: /
  • Integer Division -> Symbol: //
  • Module (Rest of Division) -> %

Booleans and comparative operators

Booleans are values ​​that can only be True or False. We also have in Python, several comparative operators and they will always return booleans.

  • Greater than -> Symbol: >
  • Less than -> Symbol : <
  • Greater equals -> Symbol: >=
  • Less than equal to -> Symbol: <=
  • Not equal to -> Symbol: !=

Conditional Logic

Conditional logic allows us, programmers, to execute code snippets only if an initial condition is True. Its structure is as follows:


if(CONDITION):
    #things that need to be done if true!
elif(OTHER CONDITION):
    #if you don't enter the first condition, and a second condition is true!
else:
    #if you don't meet any of the conditions

Exercise 1 – Calculation of BMI:

Statement: Our program must calculate the BMI of a user

BMI
FORMULA = WEIGHT/(HEIGHT²)

POSSIBLE RESULTS
< 18.5 = THINNESS
>= 18.5 AND <= 24.9 NORMAL
>= 25 AND <= 29.9 OVERWEIGHT
>29.9 OBESITY

Spoiler Warning



height = float(input("Enter your height"))
weight = float(input("Enter your weight "))

bmi = weight / (height ** 2)

if(bmi < 18.5):
    print("thinness")
elif (bmi >= 18.5 and bmi <= 25):
    print("normal")
elif (bmi > 25 and bmi <= 29.9):
    print("overweight")
else:
    print("obesity")

Lists

The list (or array) is an amazing data structure for storing multiple values ​​in sequence!
We have several methods that can help us in our day-to-day with lists, they are:

  • append() -> Add to the end of the list
  • remove() -> Remove an item from the list
  • insert() -> Insert at a specified position
  • sort() -> Sort the list

Examples with list:


list_of_numbers = [1,2,3,4,5]
list_of_numbers.remove(4)


shopping_list = ["banana","street","milk","cookie"]
shopping_list.append("onion")
shopping_list.sort()
print(shopping_list)



Loops:

In order to be able to execute the same code several times, we use loops.
These are: for and while.

Examples with for and while:

For:


shopping_list = ["banana","street","milk","cookie"]

for purchase in shopping_list:
    print(purchase)

for counter in range(10):
    print(counter)

for purchase in shopping_list:
    if (purchase == "milk"):
        print("I found the milk!")
        continues
    print(purchase)

for purchase in shopping_list:
    if (purchase == "milk"):
        print("I found the milk!")
        break
    print(purchase)

Watch out for break and continue reserved words

While:

counter = 0
while(counter < 4):
    counter = counter + 1
    print(counter)

counter = 0
while(True):
    counter = counter + 1
    print(counter)
    if (counter > 10):
        break

Watch out for infinite loops too!

Functions:

In order to encapsulate our code and organize ourselves better, we can separate code blocks into functions

Examples of functions:


def hello():
    print("Hello!")


def hello_with_parameters(name):
    print("Hello!" + " " + name)

hello()

hello_with_parameters("Lucas")

Exercise 2 – Encapsulating the BMI calculation code in a function

The idea of ​​this exercise is simply to encapsulate all the logic of the BMI exercise in a function, so that we can make our code more organized!

Spoiler Warning



height = float(input("Enter your height"))
weight = float(input("Enter your weight "))

def calculate_bmi(weight, height):
    bmi = weight / (height ** 2)
    if (bmi < 18.5):
        print("thinness")
    elif (bmi >= 18.5 and bmi <= 25):
        print("normal")
    elif (bmi > 25 and bmi <= 29.9):
        print("overweight")
    else:
        print("obesity")
    return bmi


final_value = calculate_bmi(weight, height)
print(final_value)

Recursive Functions

Recursive functions are functions that call themselves while in themselves. (It’s a complex concept and takes time to digest and understand properly! You can read more here).
The important thing is to remember the stop condition (also called the base case), which is a case of our function that will be the moment of return, where the function ends so we don’t end up with an infinite loop.

Example of recursive function:


def factorial(number):
    print(number)
    if number == 1: #<- BASE CASE
        return 1
    else:
        return(number*factorial(number-1))

factorial(10)

Interesting libraries and cool modules 😀

In this section, I’ll introduce some modules and cool stuff that python provides for us to work with. These are just a few examples of things that Python can do, but in general, there are many things beyond that. You can check some things out here.

Randomness

For randomness, we normally use the random module.


import random
#random https://docs.python.org/3/library/random.html

dice_6_sides = random.randint(1,6)
print(dice_6_sides)


Unit tests

It is important to keep tests of our code automated, ensuring that our code actually produces the desired result without having to manually check, for this we can use the unittest module.


import random
import unittest
#unittest https://docs.python.org/3/library/unittest.html

dice_6_sides = random.randint(1,6)
print(dice_6_sides)


def dice_unit_test(dice_value):
    assert dice_value <= 6,"The value of the dice obtained was greater than 6"
    print("The dice has the value <= 6 :D")
    print("All tests passed!")

dice_unit_test(dice_value)


Normally, tests are in another file (which can be run separately, via terminal). Also, there is a test-driven software development method called TDD, which you can learn more about here.

Scientific Mathematics

Python is amazing with math and you can use the math module, the numpy lib and the matplotlib lib to generate a lot of scientific content in terms of math! Here are some examples:


import math
#math https://docs.python.org/3/library/math.html
#matplotlib https://matplotlib.org/
#numpy https://numpy.org/

#math -> Some more complicated calculations


print(math.sqrt(15))
print(math.sin(math.pi/6))
print(math.cos(math.radians(60))))


#numpy more advanced math and amazing helper functions
#matplotlib plotting charts

import matplotlib.pyplot as plt
import numpy as np

plt.style.use('_mpl-gallery')

# make date
x = np.linspace(0, 10, 100)
y = 4 + np.sin(x)

# plot
fig, ax = plt.subplots()

ax.plot(x, y, linewidth=2.0)

ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
       ylim=(0, 8), yticks=np.arange(1, 8))

# plt.show()
plt.savefig("matplotlib.png")

Object Oriented Programming (OOP)

In this paradigm, we use the idea of ​​a class to create new types of data structures that can help us build an application.
The __init__ method is called a constructor.
OOP is very extensive and this section is just an idea to pop into your head! OOP is widely used in games and more robust applications precisely because of its greater ease in leaving large codebases organized and with a certain ease in terms of maintenance.
When we create a new variable based on a class we created, we call this process instantiating an object of the class.
Examples:


class Person:
    def __init__(self, name:str, age:int):
        self.name = name
        self.age = age

    def hello(self):
        print("Hello, I'm "+self.name+ " and I'm " + str(self.age) + " years old")

lucas = Person(name="Lucas",age=23) #<- lucas is an instance of person
print(lucas.age)
lucas.hello()



class Rectangle:
    def __init__(self, height:float, width:float):
        self.height = height
        self.width = width

    def area(self):
        return(self.height * self.width)

    def perimeter(self):
        return(self.height * 2 + self.width * 2)

my_first_rectangle = Rectangle(height = 10, width = 20) #<- my_first_rectangle is an instance of Rectangle
my_second_rectangle = Rectangle(height = 5, width = 12) #<- my_second_rectangle is another Rectangle instance
print(my_first_rectangle.area())
print(my_second_rectangle.area())

You can check the original PT-br material here.

Thanks for reading and if you enjoyed this kind of material, leave a comment or a reaction!

Source: Lucas Lima do Nascimento
Tags: Python cheatsheet and snippets for beginners
ShareTweet

Get real time update about this post categories directly on your device, subscribe now.

Unsubscribe

Search

No Result
View All Result

Recent News

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025
ATC Ghana supports Girls-In-ICT Program

ATC Ghana supports Girls-In-ICT Program

April 25, 2023

About What We Do

itechnewsonline.com

We bring you the best Premium Tech News.

Recent News With Image

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa

July 29, 2025
French Telco Orange Hit by Cyber-Attack

French Telco Orange Hit by Cyber-Attack

July 29, 2025

Recent News

  • Absa and Visa Extend Strategic Partnership to Advance Growth and Innovation Across Africa July 29, 2025
  • French Telco Orange Hit by Cyber-Attack July 29, 2025
  • ATC Ghana supports Girls-In-ICT Program April 25, 2023
  • Vice President Dr. Bawumia inaugurates ICT Hub April 2, 2023
  • Home
  • InfoSec
  • Opinion
  • Africa Tech
  • Data Storage

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In

Add New Playlist

No Result
View All Result
  • Home
  • Tech
  • Africa Tech
  • InfoSEC
  • Data Science
  • Data Storage
  • Business
  • Opinion

© Copyright 2026, All Rights Reserved | iTechNewsOnline.Com - Powered by BackUPDataSystems

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
Go to mobile version