0% found this document useful (0 votes)
6 views13 pages

Python Bootcamp

Uploaded by

rcdd.netflix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Python Bootcamp

Uploaded by

rcdd.netflix
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Python Bootcamp

Contents
Section 1: Syntax......................................................................................2
Topic 1.1: Basic syntax.............................................................................2
Topic 1.2: Conversion Syntax....................................................................2
Topic 1.4: List, Dictionary, and Tuple Syntax............................................3
Topic 1.5: Function Syntax........................................................................5
Topic 1.6: Class Syntax.............................................................................5
Topic 1.7: Basic External File Syntax........................................................6
Topic 1.8: Pandas Module Syntax.............................................................6
Topic 1.9: GUI Syntax................................................................................7
Topic 1.10: Catching Exception Syntax..................................................10
Topic 1.12: JSON Syntax........................................................................10
Topic 1.13: SMTP (Single Mail Transfer Protocol) Module Syntax...........11
Topic 1.14: Datetime Module Syntax.....................................................11
Topic 1.15: API Requests Syntax............................................................11
Topic 1.16: Other Syntax.......................................................................11
Section 2:..................................................................................................12
Topic 2.1: Data Types and Operators......................................................12
Topic 2.2: Terminology............................................................................12
Topic 2.3: Object Oriented Programming................................................13
Section 1: Syntax

Topic 1.1: Basic syntax


- Print:
print(f“value {variable} {variable} \“value\” ”)
- Ask input from user:
Input(“prompt”)
- To find out number of letters or value in variable:
len(value_or_variable)
- To check type of data from a variable:
print(type(variable))
- If and else condition:
if condition:
syntax
elif condition:
syntax
else:
syntax
- Counting specific value on variable:
variable.count(value)
- Generate random integer from specific range of integer:
import random
random.randint(int_start, int_end)
- Generate random integer from specific range of float:
import random
random.uniform(flt_start, flt_end)
- Generate random floating number from 0 to 1:
Import random
random.random()
- Generate random variable in a list:
Import random
random.choice(variable)
- Replace the word in variable:
variable = variable.replace(“word_to_be_replaced”,
“word_replacement”)
- Remove spaces at the beginning and at the end of the string:
variable = variable.strip()
- Sum, max, min integer or float:
sum(variable) or max(variable) or min(variable)

Topic 1.2: Conversion Syntax


- To define, converse, or cast one value data type to other data type:
variable = data_type(value)
- To round float number:
Round to nearest integer:
round(value, number_of_decimal_places)
Roundup:
import math
math.ceil(value)
- Converting string to lower case:
value.lower()
- Converting string to upper case:
value.upper()
- Converting first alphabet of string to upper case:
value.capitalize()
- Converting first alphabet of every word to upper case:
value.title()

Topic 1.3: Loop Syntax

- For loop:
for value in list:
syntax
- While loop:
while condition:
syntax
change_condition

Topic 1.4: List, Dictionary, and Tuple Syntax


- Create a list values in one variable:
variable = [value, value]
- Create a nested list in one variable:
variable = [variable, variable]
- Add another value to a variable:
Add one value:
variable.append(value)
Add more than one value:
variable.extend([value, value])
Add value on specific list position:
variable.insert(list_position, value)
- Remove value in a list:
Remove specific value:
variable.remove(value)
Remove last value or specific value best on location in variable:
variable.pop(location_number)
- Split a value into a list of value:
Split value based on space or other value:
variable = variable.split(value_separator)
Split value based on each char:
variable = list(variable)
- Provide list of value from a range of integer:
range(int_start, int_end_plus_1, distance_between_integer)
- Shuffle a list and recombine them:
import random
random.shuffle(variable)
shuffled_variable = “separator‘’.join(variable)
- Creating list comprehension:
new_list = [new_value for value in list if condition]
- Finding index number of certain value in a list:
new_variable = variable.index(value)
- Creating dictionary:
variable = {key: [value, value], key: [value, value]}
- Print value of one key in the dictionary:
print(variable[key])
- Print all key in the dictionary:
for variable in dictionary_variable:
print(variable)
- Print all key and value in the dictionary:
for variable in dictionary_variable.items():
print(variable)
- Print all value in the dictionary:
for (key, value) in dictionary_variable.items():
print(value)
- Add new key and value to dictionary or edit existing dictionary:
variable[key] = value
- Creating nested dictionary:
variable = [{key: [value, value], key: value}, {key: [value,
value], key: value}]
- Print value of one key in the nested dictionary:
print(variable[key][key][index])
- Add new dictionary to a nested dictionary or edit existing dictionary:
new_variable = [{key: value}, {key: value}]
variable.append(new_variable)
- Creating dictionary comprehension:
new_dictionary = {new_key:new_value for (key, value) in
dict.items() if condition}
- Creating tuple:
tuple = (value, value, value)
- Slicing sequence(list, tuple, etc):
sequence[start:stop:step]

Topic 1.5: Function Syntax


- Make function and call function:
def function(parameter = default_value, parameter =
default_value):
syntax
return output
function(parameter = argument, parameter = argument)
- Make function that allow unlimited positional argument and call the
function:
def function(*args):
for n in args:
syntax
return output
function(argument, argument, argument)
- Make function that allow unlimited keyword argument and call the
function:
def function(**kwargs):
variable = kwargs.get(parameter)  .get means if the
parameter not exist, syntax
the output will be none instead of error.
return output
function(parameter = argument, parameter = argument)
- Calling and changing global variable attribute in function:
def function():
global variable
variable = value

Topic 1.6: Class Syntax


- Creating and using class (first alphabet in the blueprint name needs
to be capitalize):
Creating class with attributes and method:
class Blueprint:
def __init__(self, parameter, parameter):
self.attribute = parameter
self.attribute = parameter
def function(self, parameter):
parameter.attribute = value
self.attribute = value
Using class and method:
object = Blueprint(argument, argument)
object.function(parameter)
- Creating class inheritance:
class Blueprint(superclass):
def __init__ (self):
super().__init__()
self.superclass_function(value)
def function(self, parameter):
super().function()

Topic 1.7: Basic External File Syntax


- Interacting with external file syntax (“with” make sure that the file is
closed after used):
with open(“file_name.extension”, “w” or “a”) as variable:
variable = variable.read()
variable.write(value)
or
variable = open(“file_name.extension”, “r” or “w” or “a”)
variable = variable.read()
variable.write(value)
variable.close()
- Return all lines in the file as a list:
variable = open(“file_name.extension”)
variable = variable.readlines()
- Interacting with CSV file syntax:
Import csv
with open(“file_name.extension”, “w” or “a”) as variable:
variable = csv.read(variable)

Topic 1.8: Pandas Module Syntax


- Importing pandas module:
import pandas
- Creating DataFrames:
Creating DataFrames from dictionary:
dictionary_variable = {key: [value, value], key: [value, value]}
variable = pandas.dataframe(dictionary_variable)
Creating DataFrames from CSV file:
variable = pandas.read_csv(“file.csv”)
- Selecting a column:
Selecting single column:
variable[“key or column”]
Selecting multiple column:
variable[[“key or column”, “key or column”]]
- Selecting row:
Selecting specific row based on row numbers:
variable.iloc[int:int]
Selecting rows by condition:
variable[variable[“key or column”] condition]
- Column manipulation:
Adding a new column:
variable[“key or column”] = [value, value]
Modifying an existing column:
variable[“key or column”] = value
Dropping column:
variable = variable.drop(columns=[“key or column”])
Renaming column:
variable = variable.rename(columns={“key or column”:
new_name})
- Grouping and aggregating data:
Group by a column and compute the mean or max or sum:
variable = variable.groupby(“key or column”).mean() or max()
or sum()
Group by multiples columns and compute the mean or max or sum:
variable = variable.groupby([“key or column”, “key or
column”]).mean() or max() or sum()
- Writing data to a file:
Write DataFrame to a CSV file:
variable.to_csv(“file.csv”, index = False)
Write DataFrame to a excel file:
variable.to_excel(“file.xlsx”, index = False)
- For loop using Pandas library dataframe:
for (index, row) in data_frame.iterrows():
print(row.index)
- Dictionary comprehension using Pandas library dataframe:
dictionary = {df[“key”]: df[“value”] for (index, df) in
variable.iterrows()
if condition}
- Create nested dictionary using Pandas library dataframe:
dictionary = variable.to_dict(orient=”records”)

Topic 1.9: GUI Syntax


- Create GUI:
from tkinter import *
Create GUI window:
variable = Tk()
variable.title(value)
variable.minsize(width_value, height_value)
variable.config(padx=int, pady=int, bg=background_color)
def function(*args):
print(args)
variable_1 = variable.after(int, function, *args)
variable.after_cancel(variable_1)
syntax
variable.mainloop()
Create Canvas Widget:
variable = Canvas(width=int, height=int,
bg=background_color,
highlightthickness=int)
variable_1 = PhotoImage(file=“image_file”)
variable_2 = variable.create_image(x_location, y_location,
image=variable_1)
variable.create_text(x_location, y_lovation, text=value,
font=(font_type,
font_size, font_model), fill=color, width=int)
variable.itemconfig(variable_2, image=new_image,
text=value)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
- Create component inside GUI windows:
Create label:
variable = Label(text=value, font=(font_type, font_size,
font_model), fg=color)
variable.config(text=value, bg=color)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n” padx=int, pady=int)

Create button:
variable_1 = PhotoImage(file=“image_file”)
variable = Button(text= value, command=syntax_or_function,
image=
variable_1, highlightthickness=int)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)

variable.destroy()

Create input entry bar:


variable = Entry(width=int)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
variable.insert(0 or END, string=“begin_text”)
variable.focus()
variable.delete(0, END)
variable.get()  to get the string of the input but only can be
done when the
input had been made (needs to be combined
with button)
Create text:
variable = Text(height=int, width=int)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
variable.focus()  put cursor in the textbox
variable.insert(0 or END, “begin_text”)
variable.get(“line.starting_character”, END)
Create spinbox:
def function():
print(variable.get())
variable = Spinbox(from_=int, to=int, width=int,
command=function)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
Create scale:
def function(value):
print(value)
variable = Scale(from_=int, to=int, width=int,
command=function)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
Create checkbutton:
def function():
print(variable.get())
variable_1 = IntVar()
variable = Checkbutton(text=value, variable=variable_1,
command=function)
variable_1.get()
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
Create radiobutton:
def function():
print(variable.get())
variable_1 = IntVar()
variable_button_1 = Radiobutton(text=value, value=1,
variable=variable_1,
command=function)
variable_button_2 = Radiobutton(text=value, value=2,
variable=variable_1,
command=function)
variable_button_1.grid(column=int, row=int, columnspan=int,
rowspan=int,
sticky=”w” or “e” or “s” or “n”, padx=int,
pady=int)
variable_button_2.grid(column=int, row=int, columnspan=int,
rowspan=int,
sticky=”w” or “e” or “s” or “n”, padx=int,
pady=int)
Create listbox:
def function(value):
print(variable.get(variable.curselection()))
variable = Listbox(height=int)
variable_list = [value, value, value]
for n in variable_list:
variable.insert(variable_list.index(n), n)
variable.bind("<<ListboxSelect>>", function)
variable.grid(column=int, row=int, columnspan=int,
rowspan=int, sticky=”w” or
“e” or “s” or “n”, padx=int, pady=int)
- Create dialog boxes and pop-ups:
from tkinter import messagebox
messagebox.showinfo(title=value, message=value)
variable = messagebox.askokcancel(title=value,
message=value)
if variable == True:
syntax
else:
syntax
Topic 1.10: Catching Exception Syntax
- Get appropriate input and do print error message while error
occurred:
try:  something that might cause an exception (error)
syntax
except error_type as variable:  do this if there was an
exception
syntax
else:  do this if there were no exceptions
syntax
finally:  do this no matter what happens
syntax
- Creating or raising your own error:
raise error_type(“error_message”)

Topic 1.12: JSON Syntax


- Importing JSON module:
import json
- Open or Write JSON file:
dictionary_variable = {key: {key: value, key: value}}
with open(“file.json”, “w”) as variable:
json.dump(dictionary_variable, variable, indent=4)
- Open and read JSON:
with open(“file.json”, “r”) as variable:
read_variable = json.load(variable)
- Update JSON:
with open(“file.json”, “r”) as variable:
read_variable = json.load(variable)
read_variable.update(new_dictionary_data)
with open(“file.json”, “w”) as variable:
json.dump(read_variable, variable, indent=4)

Topic 1.13: SMTP (Single Mail Transfer Protocol) Module Syntax


- Import module:
import smtplib
- Establish secure connection and send email to other recipients:
with smtplib.SMTP(“email_provider_identity
(ex:smtp.gmail.com)”) as variable:
variable.starttls()  make connection secure
variable.login(user=email_id,
password=email_app_password)
variable.sendmail(from_addr=email_id, to_addrs=email_id,
msg=“subject:message\n\nbody_message”)
Topic 1.14: Datetime Module Syntax
- Import module:
import datetime
- Check current date:
variable = datetime.datetime.now()  check full current date
variable = datetime.date.today()  check current date (YYYY-
MM-DD)
variable_year = variable.year
variable_month = variable.month
variable_day = variable.day
variable_weekday = variable.weekday()
variable_custom_format =
variable.strftime(“%a%A%w%d%b%B%m%y%Y%H%M
%S”)
- Add days to date:
variable = datetime.datetime.now() +
datetime.timedelta(days=amount_of_day)
- Create date:
variable = datetime.datetime(year=int, month=int, day=int,
hour=int)

Topic 1.15: API Requests Syntax


- Import module:
Import requests
- Get access from API endpoint:
variable = requests.get(url=“API_endpoint”,
params=parameter)
- Post through API endpoint:
variable = requests.post(url=“API_endpoint”,
json=parameter, headers=variable)  headers variable
contain API key
- Put (update external value) through API endpoint:
variable = requests.put(url=“API_endpoint”, json=parameter)
- Delete data through API endpoint:
variable = requests.delete(url=“API_endpoint”,
params=parameter)
- Raise error status if API endpoints return error:
variable.raise_for_status()
- Obtain JSON data from the access:
JSON_variable = variable.json()

Topic 1.16: Environment Variable Syntax


- Add environment variable on PyCharm:
Run  Edit Configurations  Edit configuration templates  Python
 Environment variables.
- Add environment variable on .env file:
Create .env file  write the environment_variables = “password”
- Call environment variable:
import os
from dotenv import load_dotenv  Install Python-dotenv
module (for .env file)
load_dotenv()
os.environ[“environment_variable”]

Topic 1.17: Other Syntax


- Copy or paste certain value directly to clipboard:
import pyperclip
pyperclip.copy(variable)
pyperclip.paste(variable)
- Unescape HTML entities:
import html
variable = html.unescape(value)

You might also like