Tech: Tips, Tricks, and More
Anything from Linux to Python.
Linux
Top 100 Commands
This section provides a list of the top 100 Linux commands. The commands are to the left in bold, their description are to the right.
cal - Calendar (you must first install the calendar via: sudo apt install cald)
cat [file name].ext | sort - sort the contents of a file alphabetically
cat [file name.extension] - read an entire file
cat [file name].txt - See what’s in a file
cd - return home, type “cd” followed by one space
cd .. - go back one directory
cd [folder to switch to] / - change directory (move folders). Enter “cd” followed by the folder name and then “/”
chmod +x [file name.ext] - make a file executable
clear - clear your terminal window, refreshes the terminal window
cmp [file name.extension] [file name.extension] - compare two files, tells you on which line(s) there is/are a difference
cp [file name].txt - copy, copies a file
cp [file name].txt ./[directory] - copies a file to a directory of your choosing
curl [url] - get a file from the internet
df - How much disc space is free
df -H - How much disc space is free (more fancy)
diff [file name.extension] [file name.extension] - shows differences between two files, specifying the lines
echo - Like print() in Python, write something to the screen
echo “[insert new file info]” > [file name].txt - Insert new info into a file, e.g.: echo “This is a test” > test.txt
find / -name “[file name]” - find a file name’s location in a directory
free - How much memory is free
head [file name.extension] - read a file, starting from the top
history - history of all recent commands
htop - The top processes eating up memory (fancy) (must first be installed via: sudo apt apt install htop)
ifconfig - find all of your ip addresses, requires packet installation
ip address - find your ip address(es)
ip address | grep eth0 - find your ethernet ip
ip address | grep eth0 | inet | awk ‘{print $2}’ -
ip address | grep inet - find your internet ip
kill - stops the process (you can search for a process via ps -aux | grep [name of the process])
kill -9 [process id] - enter “kill -9” followed by the process id to find and kill a specific process
less [file name.extension] - read a file, one page at a time
ls - lists all files in current working directory
ls -a - provides a list of everything in the directory, including hidden files
ls -l - provides a list of everything in the directory
man [package] - teaches you about a package, like cal or finger
mk dir [followed by new folder name] - make directory, creates a new folder
mv [file name].txt - move, moves a file
mv [file name].txt ./ [new directory] - moves a file to a directory of your choosing
nano [file name].txt - Edit content of a file (CTRL + X, Y, ENTER to save)
pkill -f [name] - enter “pkill -f” followed by the name of the process to kill it
ps - Processes
ps -aux - All processes
pwd - print working directory (where you’re currently at)
rm [file name].txt - remove, removes a file
rmdir [directory name] - remove directory, removes a folder (directory)
shred [file name].txt - shreds the contents of a file
sudo - super user command, allow users to execute commands with superuser privileges, without having to log in as the root user
sudo apt install [package name] - install a specific package
sudo apt update - Update your packages
sudo find . -type f -name “ .*” - find all hidden files
sudo reboot - reboot machine
sudo shutdown - shut down in 1 min
sudo shutdown -h now - shut down the pc right now
tail [file name.extension] - read a file, starting from the bottom
top - The top processes eating up memory
touch [followed by file names] - Type “touch” followed by words you wish to become file names, separated by a space
touch [name].txt - create a file, typ “touch” followed by the name of the space, and then “.txt” (for text, a file type)
uname - Name of OS
uname -a - OS Details (e.g. Linux pop-os 6.9….)
unzip [file name.extension] - unzip a file
vim [file name].txt - An advanced way of editing a file (requires installation via: sudo apt install vim). Enter “i” , ENTER (for insert) to start entering text. To Exit: ESCAPE : wq, ENTER (to write a quit)
wget [url] - get a file from the internet, type: wget (followed by the url), very helpful for downloading from github
what is - faster than man, teaches you about a package
zip [file name.xtension] - zip a file
Python
Functions & Variables
A TL;DR from CS50's Introduction to Programming with Python, Lecture 0.
- Code is just text, interpreted by the computer. All you need to write code is a text editor. You can interface with your computer (run code) using a command line interface (CLI); on a Mac it’s the Terminal, on Windows it’s the Command Prompt. Programs like Visual Studio Code (VSCode) enable you to both write and run code in the same place, providing both a text editor and a CLI!
- Saving code as a file creates a program. Python files always end with “.py”. The computer reads code, top to bottom, left to right. The result of a program, called a side effect, can be visual or audio. Mistakes in a program are called bugs.
- Python is both a programming language and a program (known as an interpreter); it takes your input and translates it to binary, the language your computer understands.
- Python relies on commands to execute your code. For example, the command code creates a program in VSCode.
- Functions are actions/verbs that let’s you do something in a program. For example, print() will print text, called str in Python, to the screen. Each function comes with its own parameters, which dictate what you can do. When used they are called arguments. Some functions obtain input from the user, and then hand back a return value.
- Variables serve as a container for a value inside a computer/program. It stores a value in the computer's memory. Coders can use descriptive terms to name a variable. For example, naming a variable as "name" instead of just calling it "x". Inputs are assigned to a variable using = (the assignment operator). Python assigns user input from right to left.
- Python allows you to define your own function with the keyword def. You can build custom parameters into your new function. For example: e.g. def hello(to) where to is the parameter, like hello TO a person's name. Since the python interpreter will take you literally, you must first define a new function before you can call it. You can define your program’s main function with def main(). You’ll have to call main at some point in the script, which you can do with main(). Ensure all subsequent code aligns below the colon with a tab (strictly enforced in Python).
- Comments allow a coder to annotate thoughts, instructions, ideas, etc. within their script. In Python, single line comments begin with a hash symbol [#], while multi-line comments start and end with triple quotation marks [“““]. Psuedocode is a methodology that allows the coder to start writing code using comments, creating an initial structure based on thoughts, followed by snippets of code as they progress writing the program.
- Python has various data types including string (str), integer (int), and float.
- Sequences (or strings) of text in Python are called Str (pronounced “stir”). Str functions, like print(), can be manipulated using their respective parameters such as sep (for separator), an escape sequence \ (e.g. \n to create a new line), and even formatted to allow for exceptions using a newer feature called fstring (a format string).
- An fstring starts the string with f before the first quotation mark and identifies the portion to format using curly braces {}. For example: print(f"Hello, {name}") allows a variable to be placed within the string.
- Str can also be modified using methods, such as strip(), capitalize(), title(), and split(). Methods can also be nested for more succinct code! For example: name = name.capitalize().title().split().
- Integers, called int in Python, are whole numbers (no decimal points or fractions). An str can be converted to int. For example: x = int(input("What's x? ")). Note that when nesting functions like this, the inner value of a function becomes the parameters from the outer function.
- A floating point value, called float in Python, is a number with a decimal point (a.k.a. a real number). For example: x = float(input("What's x? ")) will convert the str input to a float, then store it as the variable “x”. You can round floats using a function called round, and even specify the number of digits. For example: round(number[, ndigits]). Note that in Python, square brackets indicate something optional (e.g. the number of digits to round to).
- Python supports interactive mode, allowing you to write and then immediately interact. Just open a terminal window, type "python", then “ENTER”, and you'll get three brackets indicating interactive mode (>>>).
- Python support operators such as + (concatenate), - (subtract), * (multiply), / (divide), and % (Modulo, takes the remainder after one number of another [SHIFT + 5 on windows]).
Python
Conditionals
A TL;DR from CS50's Introduction to Programming with Python, Lecture 1.
- Conditional statements are the ability to ask questions and answer them to decide which line of code to execute
- Python comes with built in syntax: > , >= , < , <= , == , != .
- Asking questions using IF, a Boolean expression that results in a true/false answer. IF begins with a : (colon) and uses indentation for associated conditional.
- Ask follow-up questions using ELIF (else if). ELIF prevents code from asking unnecessary questions, continuing only if you haven't yet received a true response.
- Exit a conditional with ELSE; this decreases complexity, asks one fewer questions, and reduces computation (helpful on larger scripts). You can combine the use of IF and ELSE using !=.
- Combine questions using OR.
- Combine thoughts with AND.
- With conditionals, you can switch the logical order and nest criteria. Just remember: Python enforces indentation (will not work without it), and the colon is necessary.
- A bool (short for Boolean) ends in either true of false. Note that "True" or "False" must be capitalized.
- When a Boolean expression itself has a True or False answer, consider shortening the code using RETURN to just return the value of your Boolean expression.
- The syntax of the keyword MATCH is like SWITCH in other languages: it uses keyword pairs of match/case to find information. The underscore ( _ ) can be used as a catch-all, like the use of else in a conditional statement.
Python
Loops
A TL;DR from CS50's Introduction to Programming with Python, Lecture 2.
- Loops are the ability in Python to do something repeatedly, a cycle of sorts. Loops can also be nested. In Python there are two types of loops: a While loop and a For loop.
- A while loop uses WHILE to allow the coder to repeatedly ask a question. While Python coders typically count up from zero, you can also countdown. Count-up using the Pythonic syntax +=, which increments by the number indicated to the right. For example:+= 1 increments by one. Be careful of creating infinite loops! Use CTRL + C to interrupt.
- A LIST is a a type of data, a way of containing multiple values in the same variable. In Python, square brackets [ ] indicate a list.
- Use the keyword FOR to iterate over a list of items. Very helpful when you have a variable and you know in advance how many times you want the loop to execute.
- RANGE is a function in Python that gives you a list, and returns a range of values that you specify. Range requires at least one argument: the number of values you want returned. It also goes up to, not through, the number you specify, and expects an integer (cannot pass text).
- A Pythonic option when a function requires a variable that you won’t use elsewhere, is to just identify the variable using an _ (underscore). This signals to coders that it’s a necessary variable but we don’t care about the name.
- Another Pythonic option is to just use multiplication to concatenate strings. For example: just use the print function and parameters, combined with the multiplication.
- Use WHILE TRUE (while True) in Python when you want a specific input. This creates an infinite loop; the answer to the question is always True. Note that the “T” in “True” must be capitalized.
- Use CONTINUE (continue), a keyword in Python that keeps the loop going. For example: continue until a non-zero input obtained.
- Use BREAK (break), a keyword in Python to break from the most recently begun loop. For example: break once non-zero input is obtained.
- Use LEN (len, short for length), to get the length of a list. For example: Iterate using numbers, Range takes a number (expects an int), use len to get the length of the string first.
- A DICT (dict, for dictionary) is a data structure that allows the coder to associate one value with another using key/value pairs. For example: keep track of who is where. A dict uses use curly braces and separates by line with "key":"value" ending with a comma. For example: "Optimus Prime":"Autobot",.
Python
Exceptions
A TL;DR from CS50's Introduction to Programming with Python, Lecture 3.
- Exceptions are problems in the code, where something has gone wrong. Exceptions are entirely on the coder to resolve. It's also up to the coder to write code defensively, to accommodate inputs that people type/mistype or enter. Good idea to test for “corner cases”, be defensive in our coding by writing with error handling in mind. This is called exception handling.
- A SyntaxError indicates an error with the text. For example: forgetting to end text with quotes.
- A RuntimeError is an error that occur while the code is running.
- A ValueError indicates the value is something other than what is allowed. For example: entering text when the code expects a number.
- A NameError indicates an error with a variable; doing something with a variable you shouldn’t.
- Scope refers to the portion of the code in which a variable exists.
- Local variables exist only in a function while global variables exist in entire files.
- Two ways of error handling in Python are using TRY (in combination with except) and PASS.
- Try is a a keyword in Python to test for and handle exceptions and must be used in combination with the keyword EXCEPT (except). Complete the error handling with the keyword ELSE (else), which signals to Python that if nothing goes wrong, do the following. When used in conjunction with try an except, else is like using elif in conjunction with if. Another option is to follow else with BREAK (break), to literally break out of the loop, instead of just ending the program. For example: use else break to prompt for new input (using a loop), instead of just ending the program.
- PASS is a keyword in Python for handling an exception by passing on doing anything with it. Pass catches the exception but then ignores it. For example: use pass to identify the error and repeats the input prompt.
- The pythonic method is typically to try something and handle the error if it doesn’t fit/work.
Python
Libraries
A TL;DR from CS50's Introduction to Programming with Python, Lecture 4.
- In Python, a module is a file that contains a collection of related functions, classes, and variables; reusable pieces of code that provide a specific functionality or set of functionalities. Modules can be imported for use by other programs using the import keyword, and typically have a `.py` extension. For example: `math.py`, `string.py`). By default, Python comes with several modules (e.g. Random).
- A Python library is a collection of one or more modules, bundled into a single package. Libraries provide a set of related functionalities that can be used by multiple programs and often have their own structure (directory). Each module within the library has its own `__init__.py` file (tells Python to treat the directory as a package).
- The import keyword imports an entire module. To use its functions, you must specify the module when calling a function. However, you could just use the keyword from to load a specific function (instead of the entire library) into the file in which you’re working. This way you don’t have to keep calling the module each time.
- The Random module comes with Python installation and includes several helpful functions like random which simulates a coin toss, choice, randint which generates a random number between the boundaries established within the parameters, and shuffle which randomized the order of values in a list.
- Another module is Statistics. It comes various functions like mean which calculates the average of numbers you pass into it.
- Another way of interacting with modules are through Command-Line Arguments, a feature of languages in general that allows you to, not just when prompted, provide arguments (input to the program) at the command line. When running programs in a CLI, you can provide any number of words, numbers, or phrases after the command that you’re typing, that will be passed as inputs into the program itself; no need to prompt for one thing at a time by manually calling an input function.
- The SYS module (short for system), gives access to values typed at the command line. It contains multiple functions specific to the system itself and the commands you’re typing. For example, the variable argv gives a list of all the words the human typed at the prompt before hitting ENTER. The Exit function exits the program once the it reaches a specified line of code, instead of continuing the program until the end (where it would automatically end).