DEV Community

Cover image for Python cheatsheet and snippets for beginners
Lucas Lima do Nascimento
Lucas Lima do Nascimento

Posted on

Python cheatsheet and snippets for beginners

EPTA-Forge-Python

Useful Links:

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!


my_variable = 150

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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)



Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

Interesting libraries and cool modules :D

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)


Enter fullscreen mode Exit fullscreen mode

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)


Enter fullscreen mode Exit fullscreen mode

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")

Enter fullscreen mode Exit fullscreen mode

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())

Enter fullscreen mode Exit fullscreen mode

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!


Top comments (0)