<jupyter_start><jupyter_text>Truc Huynh Cheat Sheet  round the decimalThe round function round the number to different float<jupyter_code>round(34.5646,1)<jupyter_output><empty_output><jupyter_text>absolute valuereturn the absolute value of a number<jupyter_code>abs(-11)<jupyter_output><empty_output><jupyter_text>check if a string is digitCheck if a string is a integer or not. Only work with integer, not float<jupyter_code>isdigit_list=['11','string','11.2']
for i in isdigit_list:
    print(f"{i} is an integer" if i.isdigit() else f"{i} is not an integer")
'1'.isnumeric()<jupyter_output><empty_output><jupyter_text>check a string is float<jupyter_code>def test_decimal(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
s='3.4'
test_decimal(s)
s='3.sdfs4'
test_decimal(s)<jupyter_output><empty_output><jupyter_text>math.floor(3.46)round a number(float, double) to the base level<jupyter_code>import math
math.floor(3.46)<jupyter_output><empty_output><jupyter_text>inputPrints a string into the console,and asks the user for a string input.<jupyter_code>input("What's your name: ")<jupyter_output>What's your name: <NAME><jupyter_text>string concatenationYou can add strings to string to createa new string. This is called concatenation.It results in a new string.<jupyter_code>"Hello" + "Angela"
#becomes "HelloAngela"<jupyter_output><empty_output><jupyter_text>escaping a stringBecause the double quote is special, itdenotes a string, if you want to use it ina string, you need to escape it with a \<jupyter_code>speech = "She said: \"Hi\""
print(speech)
#prints: She said: "Hi"<jupyter_output>She said: "Hi"<jupyter_text>converting data typesYou can convert a variable from 1 datatype to another.- Converting to float: float()- Converting to int: int()- Converting to string: str()<jupyter_code>n = 354
new_n = float(n)
print(new_n) #result 354.0<jupyter_output>354.0<jupyter_text>checking data typesYou can use the type() functionto check what is the data type of aparticular variable.<jupyter_code>n = 3.14159
type(n)<jupyter_output><empty_output><jupyter_text>arithmetic operatorsYou can do mathematical calculations withPython as long as you know the rightoperators.<jupyter_code>3+2 #Add
4-1 #Subtract
2*3 #Multiply
5/2 #Divide
5**2 #Exponent<jupyter_output><empty_output><jupyter_text>% operator- Often you'll want to know what is the remainder after a division.- e.g. 4 ÷ 2 = 2 with no remainder but 5 ÷ 2 = 2 with 1 remainder- The modulo does not give you the result of the division, just the remainder. It can be really helpful in certain situations, e.g. figuring out if a number is odd or even.  ERROR  zero division errorThis happens when you try to divide by zero,This is something that is mathematicallyimpossible so Python will also complain.<jupyter_code>5 % 0<jupyter_output><empty_output><jupyter_text>syntax errorSyntax errors happen when your codedoes not make any sense to the computer.This can happen because you've misspeltsomething or there's too many brackets ora missing comma.<jupyter_code>print(12+4))<jupyter_output><empty_output><jupyter_text>name error This happens when there is a variablewith a name that the computerdoes not recognise. It's usually becauseyou've misspelt the name of a variableyou created earlier.Note: variable names are case sensitive!<jupyter_code>my_number = 4
my_Number + 2<jupyter_output><empty_output><jupyter_text>FunctionFunction allow proframmer group a set of instruction together (and reuse it). The contents of the function must be indented to signal that it's inside.<jupyter_code>def my_function():
    print("Hello")
    name = input("Your name:")
    print("Hello")
# Calling Fuction:
my_function()
# Functions with Inputs
def add(n1, n2):
    print(n1 + n2)
add(2, 3)
# Function with output
def add(n1, n2):
    return n1 + n2
result = add(2, 3)<jupyter_output><empty_output><jupyter_text>Variable ScopeVariables created inside a function aredestroyed once the function has executed.The location (line of code) that you usea variable will determine its value.Here n is 2 but inside my_function() n is 3.So printing n inside and outside the functionwill determine its value.<jupyter_code>n = 2


def my_function():
    n = 3
    print(n)
    
    
print(n) #Prints 2
my_function() #Prints 3<jupyter_output>2
3<jupyter_text>Keyword Arguments- When calling a function, you can provide a keyword argument or simply just the value.- Using a keyword argument means that you don't have to follow any order when providing the inputs.<jupyter_code>def divide(n1, n2):
    result = n1 / n2
#Option 1:
divide(10, 5)
#Option 2:
divide(n2=5, n1=10)<jupyter_output><empty_output><jupyter_text>if condition ifThis is the basic syntax to test if a condition is true. If so, the indented code will be executed, if not it will be skipped. elseThis is a way to specify some code that will be executed if a condition is false. elifIn addition to the initial if statement condition, you can add extra conditions to test if the first condition is false.Once an elif condition is true, the rest of the elif conditions are no longer checked and are skipped.<jupyter_code>weather = "sunny"
if weather == "rain":
    print("bring umbrella")
elif weather == "sunny":
    print("bring sunglasses")
elif weather == "snow":
    print("bring gloves")<jupyter_output>bring sunglasses<jupyter_text>andThis expects both conditions either side of the and to be true. orThis expects either of the conditions either side of the or to be true. Basically, both conditions cannot be false. notThis will flip the orginal result of the condition comparison operatorsThese mathematical comparison operators allow you to refine your conditional checks.```> Greater than< Lesser than>= Greater than or equal to<= Lesser than or equal to== Is equal to!= Is not equal to```  Loop  whilekeep repeating until the condition become false<jupyter_code>n = 1
while n < 10:
    n += 1
    
print(n)<jupyter_output>10<jupyter_text>forFor loops give you more control than while loops. You can loop through anythingthat is iterable. e.g. a range, a list, a dictionary or tuple.<jupyter_code>all_fruits = ["apple",
"banana", "orange"]
for fruit in all_fruits:
    print(fruit)<jupyter_output>apple
banana
orange<jupyter_text>'_' in a For LoopIf the value your for loop is iterating through, e.g. the number in the range, or the item in the list is not needed, you can replace it with an underscore.  breakThis keyword allows you to break free of the loop. You can use it in a for or while loop.<jupyter_code>scores = [34, 67, 99, 105]
for s in scores:
    if s > 100:
        print("Invalid")
        break
    print(s)<jupyter_output>34
67
99
Invalid<jupyter_text>continueSkip this iteration on the loop and go to the next. The loop will still continue but start from the top  list adding lists togetherYou can extend a list with another list by using the extend keyword, or the + symbol.```list1 = [1, 2, 3]list2 = [9, 8, 7]new_list = list1 + list2list1 += list2```  list slicingUsing the list index and the colon symbol you can slice up a list to get only the portion you want. Start is included, but end is not.<jupyter_code># list[start:end]
letters = ["a","b","c","d"]
letters[1:3]
# Result: ["b", "c"]<jupyter_output><empty_output><jupyter_text>rangeOften you will want to generate a range of numbers. You can specify the start, end and step. Start is included, but end is excluded: start >= range < end<jupyter_code># range(start, end, step)
for i in range(6, 0, -2):
    print(i)
# result: 6, 4, 2
# 0 is not included.<jupyter_output><empty_output><jupyter_text>randomisation- The random functions come from the random module which needs to be imported.- In this case, the start and end are both included start <= randint <= end  Modules import- Some modules are pre-installed with python e.g. random/datetime- Some modules need to be installed from pypi.org aliasing- use keyword to give module a different name```import pandas as pd``` import from module- You can import a specific thing from a module. e.g. a function/class/constant- You do this with the from keyword. It can save you from having to type the same thing many times.```from random import randint``` import everything- Use the wildcard (*) to import everthing from module- This usually reduces code readability (e.g. not sure where the function came from)```from random import *list = [1, 2, 3]choice(list) More readable/understoodrandom.choice(list)```  Class and object classclass is template to create object- class name should be 'capital'```class Car:    def __init__(self, name):        print("Building car")        self.name = name``` Technique for identifying classes: Get written description of the problem domain- May be written by you or by an expert- Should include any or all of the following:```+ Physical objects simulated by the program+ The role played by a person + The result of a business event+ Recordkeeping items``` Identify all nouns in the description, each of which is a potential class- Should include noun phrases and pronouns- Some nouns may appear twice Refine the list to include only classes that are relevant to the problem- Remove nouns that mean the same thing- Remove nouns that represent items that the program does not need to be concerned with- Remove nouns that represent objects, not classes- Remove nouns that represent simple values that can be assigned to a variable objectuse class to create object```my_toyota=Car('Truc')``` Passing Objects as Arguments- When you pass an object as an argument, you are actually passing a reference to the object- The receiving method or function has access to the actual object- Methods of the object can be called within the receiving function or method, and attributes may be changed using mutator methods Class InheritanceWhen you create a new class, you can inherit the methods and properties of another class.- Inherittance is a 'is a' Relatonship- Specialized object has a character of the general object + unique character```Superclass(parent): genearal class -> Subclass(child): specialized class : super().__init__(put parameter that super require)```<jupyter_code>class Animal:
    def __init__(self):
        pass
    
    def breathe(self):
        print("breathing")
class Fish(Animal):
    def __init__(self):
        super().__init__()   # no arguments is almost always best in Python 3
    
    def breathe(self):
        super(Fish,self).breathe()
        print("underwater")
        
        
nemo = Fish()
nemo.breathe()
#Result:
#breathing
#underwater<jupyter_output>breathing
underwater<jupyter_text>String rjust and str()<jupyter_code>i=5
n=10
print(str('#'*i).rjust(n))
# print the string i times with the adjust to the n<jupyter_output>#####<jupyter_text>string manipulationstring in python can be sliced using```str[start_index:stop_index]```  combinationThe total of sum that match the inner condition (s <= a+d <= t)```print(sum(s <= a+d <= t for d in apples))```  Evaluation eval ()evaluate expression. compile() exec()execute can use with if, while, for.  DEBUG  logging modelto filter what information want to see (doc.python/logging model).- DEBUG- INFO- WARNING- ERROR- CRITICAL<jupyter_code>import logging
logging.debug(f"print out the bug")<jupyter_output><empty_output><jupyter_text>Scope - Search orderThe LEGB rule:1. Local(function)2. Enclosing(non-local)3. Global4. Built-in  Decorator Definitionfunction take a function as a parameter and return a function Syntax```@log_function_calldef basic():     something    return    @log_function_call is the decorator```  SETA set can be use to update, intersect, diffrence between 2 set.<jupyter_code>H = set("HackerRank")
R = set("Rang")

# add R to H
H.update(R)
print(H)

# intersect 2 set: collect similar object between 2 set
H = set("HackerRank")
R = set("Rang")
H.intersection_update(R)
print(H)
H = set("HackerRank")
R = set("Rang")
# Update the set by only keeping the element found in set A but not found in set B: syntax A.s_d(B)
H.symmetric_difference(R)<jupyter_output><empty_output><jupyter_text>Python FileRead and write - Read a text file -> Input some text- Open (file, mode, buffering)<jupyter_code>with open("myfile.txt", mode ='w') as file:
    file.write("Happy New Year")
    file.close()<jupyter_output><empty_output><jupyter_text>Python underscoreThe _ is the name of a callable (function, callable object). It's usually used for the gettext function, for example in Django:<jupyter_code>from django.utils.translation import ugettext as _
 print _("Hello!")  # Will print Hello! if the current language is English
                    # "Bonjour !" in French
                    # ¡Holà! in Spanish, etc.<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08590014891449173, 'fraction_numerical': 0.012540167724743319, 'mean_word_length': 4.95426971535231, 'pattern_counts': {'":': 3, '<': 118, '<?xml version=': 0, '>': 114, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '29', 'dir': 'jupyter-structured-clean-dedup', 'id': '612471', 'license': 'MIT', 'n_tokens_mistral': 3960, 'n_tokens_neox': 3739, 'n_words': 1589, 'path': 'src/truc-cheat-sheet.ipynb', 'repo_name': 'jackyhuynh/Python_fundamental', 'size': '12763'}