DEV Community

Cover image for Python Basics: A General Guide for Beginners
Jai Stellmacher
Jai Stellmacher

Posted on • Updated on

Python Basics: A General Guide for Beginners

Photo by shimibee on Pixabay Resized in Canva to Fit!


Python IDE:

print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

Terminal:

>> Hello, World!
Enter fullscreen mode Exit fullscreen mode

README.md

Welcome Python Newcomers, beginners, or Re-learners (learned a legacy Python?). This article will outline basics of Python such as vocabulary, basic examples, and a learning path that you can follow to build your skills! [Vocabulary is at the Bottom]

Why Learn Python?

Python is one of the leading coding languages to learn at the moment of writing. It is useful for many different reasons due to the freedom of what you can do with the language. A few examples are:

  • Write scripts that automate daily processes
  • Create wonderful backend databases due to its server-side logic <2 popular frameworks are: Flask & Django>
  • Build frontend which is unpopular because Javascript is a wonderful and an easier way of building frontend. ---(Python Frameworks for this: Pywebview, Eel)
  • Situate Data Analysis's and Visualizations (My personal favorite use!)(My favorite libraries: Pandas, Numpy, Matplotlib, Seaborn, Scikit-Learn, 3D data analysis: Open3D)
  • Craft Machine Learning and Artificial Intelligence (ML-Libraries I used in college: LightGBM, Statsmodels) & (AutoML-Libraries I also used: PyCaret) & (DeepLearning-Librarie that I used: PyTorch)
  • Engineer Desktop Application Development (These create GUI(graphical user interfaces) that allow for building tools and productivity apps (Frameworks: Tkinter))
  • Pioneer Game Development using libraries like Pygame for 2D games.
  • Initiate web scraping (I used Beautiful soup, but the other popular one is Scrapy)
  • IoT (Internet of Things) This helps communicate with devices like your Roomba (robot vacuum)
  • Network Programming (Library: Socket) This helps you incorporate or work with network protocols
  • DevOps & System Admin (Due to its efficiency to automate)

Python is such a vast language. The list above is just scraping the surface of python. When you start with Python in one of these fields definitely check out the popular frameworks above!

What to download first?

In Python, it is good to know that you can code just "out-of-the-box", but libraries are powerful because it helps with efficiency. I will show an example further down.

Steps:

  1. First download VSCode. (An IDE (Integrated Development Environment - It is a place to code that has tools to use) that is currently the most popular to use to code. VsCode Link
  2. Download Python onto your computer. Follow the steps in the popup window after it downloads.
  3. Next Open up VSCode and on the left side bar, click 'extension' or click on an icon that looks like a square of squares with the top left square rotated slightly.
  4. Once there, type in 'Python' and download the top of the list. (There is better documentation on the official vscode site linked here)
  5. On your keyboard press the buttons, "ctrl + n" (mac: cmd + n) This will create a new file. In the little word snippet at the top it will say "Select a language, or fill with template, or open a different editor to get started. Start typing to dismiss or don't show this again." In this snippet, click the "select a language". A dropdown menu will open and type in 'python'. Press enter if it is selected.
  6. Now, your file will be a python file. Here, we can code in python.

Wow time for your first project just to prove you can do it!

You should have your python file open in your vscode if you followed the steps above!

Here, we will type in the following on line 1.

print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

It should look like the image below:

Image description

Next hit "ctrl + s" (mac: cmd + s) It will look like the below picture. In the space where it says, "name", change that to 'hello.py'. Go ahead and click 'enter' on your keyboard.

Image description

Wow! You created and saved your first python file! (They should end in a '.py'. There are other variations but we will talk about those in a different blog)

So what do we do now?

Well, nothing happens right? How do we actually make it do something? Do we just yell at it, "Do the roar" "Do the roar"?

The answer is, no, we do not just tell it to do the roar. What we do is run the script (what you just made) in the terminal!

On your keyboard, hit the buttons "ctrl + j" (mac: cmd + j). A terminal will magically pop up in the lower half of your VSCode!

In the terminal type what is shown below:

python hello.py
Enter fullscreen mode Exit fullscreen mode

On the next line after you click 'Enter' on your keyboard should be the same as shown in the following:

Hello, World!
Enter fullscreen mode Exit fullscreen mode

Congratulations! You just wrote and ran your first Python program! Easy, Right?


Now What?

Well, we need to learn the fundamentals!
There are many basics to Python that should be known to understand the language as a whole. Once these fundamentals are learned, you can start specializing in one of the fields that were mentioned above in the section labeled "Why Learn Python?".

Outline of Fundamentals

  1. Syntax & Indentation: Python uses indentation for the compiler to know what the code is trying to do. It is necessary to pay attention to it. Learning code is learning a new language, so it will take time to learn the syntax as well! Do not be too hard on yourself! We all have struggled and confused the coding languages. (Even if you have not learned a different language, all coding language's syntax is hard to keep straight unless you specialize in only one!) Below is an example of indentation and using the correct syntax!(The >> means it is the outcome if it were to be run through the terminal. Which you can do if you type "python filename.py" in the terminal):
for i in range(1, 5):
    print(i)
>> 1, 2, 3, 4
Enter fullscreen mode Exit fullscreen mode

Note: To comment code out in Python use the # symbol! You can comment out a lot of code by highlighting a piece of code and pressing on your keyboard, "crtl + /"(mac: cmd + /)

2. Variables and data types: Variables store data of different types, such as numbers, strings, and booleans. Example:

name = "Max" #quotation's content in python are called strings!
age = 25 # defining a number variable! (SEE NOTE BELOW)
is_student = True #boolen truth or false
Enter fullscreen mode Exit fullscreen mode

Note: Numbers in Python: In python there are 3 types of numbers - plain integers are just positive or negative whole numbers, floats represent real numbers: decimal points, complex numbers: IDK they are complex (lol) don't ask me! Here is a good article for it Geeksforgeeks Website)

3. Operators and expressions: Operators perform actions on values and variables, and expressions combine variables, operators and values. Example:

x = 4
y = 5
result = x + y
print(result)  # Output: 9
Enter fullscreen mode Exit fullscreen mode

Above is an example of code. The operator here is the "+" plus sign. Below is an expression example. The expression is the "full sentence of the math being put together - here it is the z = 2 * (x + y) - 1 portion"

x = 6
y = 5
z = 2 * (x + y) - 1
print(z)  # Output: 21
Enter fullscreen mode Exit fullscreen mode

4. Control flow statements (loops & conditionals): A loop will repeat code until a condition is not true. A conditional is (if, elif, else). They dictate the flow of execution of the code based on conditions that you-the creator can place. Example of loop:

foods = ["Sushi", "Pizza", "Crepe"]

for food in foods:
    print(food)
Enter fullscreen mode Exit fullscreen mode

Terminal Will Print

Sushi
Pizza
Crepe
Enter fullscreen mode Exit fullscreen mode

What is happening in the code above? We are defining foods with a data structure called a list. This is denoted by the square brackets []. Note: If you are coming from a different language, make sure you do not mix up your curly brackets and your square brackets!

After we define the list of foods (it contains sushi, pizza, and crepe), we loop through the list. In python, this means that it reads the first item in our list, "sushi" then prints it out, then it goes through again, reads the next and prints it, lastly it reads the "crepe" and prints it. It is good to understand what the sentence means. "for food in foods:" This means that each "food" item is being assigned and counted in the list of "foods"

A separate example of this could be, "for i in range(1, 5):"
What is happening here is that "i" defines the place holder and the range(1, 5) means that the loop will go through each number 1 by 1, starting at the number 1 and going to the number 4. (It is weird, I know. Why does it say 5, and the loop will only print 4?? If I remember from college correctly, its because it starts at 0) If you want to see this in action look at the gif below:

Image description
Below is the terminal outcome:

Image description

Example of conditional:

age = 16

if age >= 18:
    print("You are an adult.")
else:
    print("You are not yet an adult.")
Enter fullscreen mode Exit fullscreen mode

In the above example, this is a conditional. The age defined in the program is 16. The "if" statement will print "You are an adult." if the age is above or equal to 18. If your age is less than 18 then the "else" portion of your code will occur.

Image description
Below is how it executes in the terminal:

Image description

5. Functions and modular programming: Functions are reusable blocks of code. They can perform tasks. Modular programming helps with organization and reusability. Example:

def greet(name):
    print("Hello, " + name + "!")

greet("John Doe")
Enter fullscreen mode Exit fullscreen mode

If we wanted, we could greet someone other than John Doe if we do the following:

greet("Max Smith")
Enter fullscreen mode Exit fullscreen mode

The outcome of the first code block will be "Hello John Doe" and now with the change, the second code-block if ran will be "Hello Max Smith".

The beauty of this type of coding is that it is less redundant and its easier and more "dynamic". (Which is part of python's current best practices)


Phew! That was a LOT!

I suggest that you get up and go take a break! Let that information sink in, and try doing some other basic examples! I would start with assigning variables to numbers and doing math in order to get familiar with how Python can work. I suggest this site to try just seeing Python do stuff. Site: https://codingexplained.com/coding/python/basic-math-operators-in-python


If you have taken a break and are ready to learn on, Lets Go!

What do we learn now? Well, there are other aspects of Python such as Data structures and Algorithms. If you want a job at the big MAANG(Meta, Apple, Amazon, Netflix, and Alphabet[Google]) companies, then knowing these will help a lot!

So what are they?

Data structures: Special boxes that hold different kinds of data. Each data structure has its own unique way of storing and accessing data. Types: lists, tuples, dictionaries, and sets. Note: data structures start at 0! So if you are looking for something in "first place" it usually is the zeroth place! Below you will see examples such as [0]. This will look at the place you think is "1st place"! Also, notice the difference in syntax! ie. curly brackets or square brackets and the content within them!

List Example:
When to use? : Use when you need to store and access an ordered collection of items.

# Creating a list
foods = ["sushi", "pizza", "crepe"]

# Accessing elements in a list
print(foods[0])  # Output: "sushi"

# Modifying elements in a list
foods[1] = "pizza"
print(foods)  # Output: ["sushi", "pizza", "crepe"]

# Adding elements to the end of a list
foods.append("steak")
print(foods)  # Output: ["sushi", "pizza", "crepe", "steak"]

# Removing elements from a list
foods.remove("sushi")
print(foods)  # Output: ["sushi", "pizza", "crepe"]
Enter fullscreen mode Exit fullscreen mode

Tuples Example:
When to use? : Use when you want to store a collection of related values that will not change.

# Creating a tuple
point = (1, 4)

# Accessing elements in a tuple
print(point[0])  # Output: 1

# Tuples cannot be altered, so modifying is not possible
# point[0] = 4  # This will result in an error

Enter fullscreen mode Exit fullscreen mode

Dictionaries Example:
When to use? : Use when you need to store data as key-value pairs. This helps with efficient lookup and retrieval. (Fun Fact: This is a good thing to remember for learning SQL!)

# Creating a dictionary to represent a college student
student = {
    "name": "Max",
    "age": 22,
    "major": "Marketing",
    "year": 3
}

# Accessing values in the dictionary using keys
print("Name:", student["name"])  # Output: "Name: Max"
print("Age:", student["age"])  # Output: "Age: 22"
print("Major:", student["major"])  # Output: "Major: Marketing"
print("Year:", student["year"])  # Output: "Year: 3"

# Modifying values in the dictionary
student["age"] = 22
student["year"] = 4
print("Updated Age:", student["age"])  # Output: "Updated Age: 21"
print("Updated Year:", student["year"])  # Output: "Updated Year: 4"

# Adding new key-value pairs to the dictionary
student["university"] = "XYZ University"
print("University:", student["university"])  # Output: "University: XYZ University"

# Removing a key-value pair from the dictionary
del student["major"]
print(student)  # Output: {'name': 'Max', 'age': 23, 'year': 4, 'university': 'XYZ University'}

Enter fullscreen mode Exit fullscreen mode

Sets Example:
When to use? : Use sets when you want to store a collection of unique elements. This will have no particular order.

# Creating a set of food items
foods = {"sushi", "pizza", "crepe"}

# Adding elements to the set
foods.add("burger")
print(foods)  # Output: {"sushi", "pizza", "crepe", "burger"}

# Removing elements from the set
foods.remove("pizza")
print(foods)  # Output: {"sushi", "crepe", "burger"}

# Sets automatically remove duplicate elements
foods.add("sushi")
print(foods)  # Output: {"sushi", "crepe", "burger"}
Enter fullscreen mode Exit fullscreen mode

Simple right? Good job on learning the basics in data structures! Software Engineers should understand data structures because they dictate the speed of grabbing data! In the grand scheme of things, this is good to know if you are trying to build efficiency and speed in your apps. (Which is what you should strive to do!)

Algorithms!

What are they? : They are step-by-step instructions that help you solve a puzzle or issue! Being someone in the field of coding should be able to logically go step by step in their processes! (Computers essentially progress from beginning to end) The most common example is instructions for building a peanut butter and jelly sandwich!

There are special algorithms in code though! They help by breaking up your problems into smaller and more manageable steps!

Knowing all of these algorithms is a bit intermediate so do not worry about committing all of these to memory! They are great to know though for any coding interviews you do!

The types of Algorithms:

  1. Sorting Algorithms: -- Merge Sort: Efficient for sorting large lists or arrays. -- Quick Sort: Efficient for sorting large lists or arrays, widely used in practice. -- Bubble Sort: Simple but inefficient for large lists. -- Selection Sort: Efficient for small lists or partially sorted data. -- Insertion Sort: Efficient for small or partially sorted lists.

2. Searching Algorithms:
-- Binary Search: Efficient for sorted lists, dividing the search space in half at each step.
-- Depth-First Search (DFS): Used for traversing or searching in tree or graph structures.
-- Breadth-First Search (BFS): Used for traversing or searching in tree or graph structures, exploring neighbors first.

  • Linear Search: Simple but not efficient for large lists.

3. Graph Algorithms:
-- Prim's Algorithm: Finding the minimum spanning tree in a weighted graph.
-- Kruskal's Algorithm: Finding the minimum spanning tree in a weighted graph.
-- Dijkstra's Algorithm: Finding the shortest path in a graph with non-negative weights.

4. Recursion:
-- Tower of Hanoi: Solving the Tower of Hanoi puzzle using recursion.
-- Factorial: Calculating the factorial of a number using recursion.

5. Hashing:
-- Hashing Algorithms: Understanding different hashing techniques like MD5, SHA-1, and SHA-256. This is for passwords!

6. String Algorithms:
-- String Matching Algorithms: Understanding algorithms like Brute Force, Knuth-Morris-Pratt (KMP), and Rabin-Karp for pattern matching.

7. Tree Traversal:
-- In-order, Pre-order, and Post-order Traversal: Visiting nodes in a tree in different orders.

8. Dynamic Programming:
-- Fibonacci Sequence: Solving the Fibonacci sequence efficiently using memoization or bottom-up approaches.
-- Knapsack Problem: Solving the knapsack problem using dynamic programming.

So Much To Learn!!!

I will not include these, but you should study up on the following as well!

  1. Error Handling: This is a way to debug or find where your coding logic does not make sense. It helps break apart your code and makes it "easier" (not many things are easy in coding) to find the issues.
  2. Input/Output and File Handling: A way to let users or testers input information into your code (interact with it) and the outputs of that. This is most commonly seen in command-line-interface apps as well as backend database manipulation. The File handling is just ways to "read" and "write" files!

Moving Forward - What should I do?

Continue to practice, practice, and practice! The best way to learn any language is to move to a country that speaks it majorly and be immersed. (People trying to learn Spanish, may live in Spain and become more in touch with it! In our case, just start coding. I know it may be scary, but there are so many examples and resources out on the internet to help! (Youtube is amazing for coders!)

Below are some resources I use for learning more:

Glossary & Terms

Word Definition
Python A high-level, interpreted programming language.
Script A set of instructions or commands written in Python.
Backend The server-side of a web application or software system.
Frontend The client-side of a web application or software system.
Framework A reusable set of libraries or tools for developing software.
Database A structured collection of data stored and accessed electronically.
Flask A popular Python web framework for building web applications.
Django A high-level Python web framework for rapid development and clean design.
Pywebview A Python library for creating web-based desktop applications.
Eel A Python library for creating desktop applications with HTML, CSS, and JavaScript.
Data Analysis The process of inspecting, cleaning, transforming, and modeling data to discover useful information.
Visualization The representation of data or information in graphical or visual format.
Pandas A Python library for data manipulation and analysis.
Numpy A powerful library for scientific computing with Python.
Matplotlib A plotting library for creating static, animated, and interactive visualizations.
Seaborn A data visualization library based on Matplotlib.
Scikit-Learn A machine learning library for Python.
Open3D A library for 3D data processing and visualization.
Machine Learning A subset of artificial intelligence that enables systems to learn from data and make predictions or decisions.
Artificial Intelligence The simulation of human intelligence in machines that are programmed to think and learn.
LightGBM A gradient boosting framework for machine learning tasks.
Statsmodels A library for statistical modeling and analysis.
PyCaret An open-source library for automated machine learning.
PyTorch A deep learning library for Python.
Tkinter A standard Python interface to the Tk GUI toolkit.
Pygame A set of Python modules for game development.
Web scraping The extraction of data from websites.
Beautiful Soup A Python library for web scraping and parsing HTML and XML.
Scrapy A Python framework for web scraping.
IoT Internet of Things - The interconnection of everyday objects via the internet.
Socket A low-level network programming interface in Python.
DevOps A set of practices combining software development (Dev) and IT operations (Ops).
System Admin A person responsible for the upkeep, configuration, and reliable operation of computer systems.

Where to now?

Check out this great Roadmap for becoming a Python Developer!(https://roadmap.sh/python)
I suggest that you start building basic apps. Then once you are comfortable with everything mentioned in this article, move onto finding what specialty of Python you want to learn!

If you have any questions or need help on your journey, post a comment!

Good luck and have fun!
-Jai

Top comments (1)

Collapse
 
matthewjroche profile image
M-Joseph-Roche

Excellent Python depiction at the top of the page.