Python For The Blinds (Part-1)
Tags: python, beginners, webdev, programming
Published: 2023-09-05 06:41:44

<p data-pm-slice="1 1 []">Python has become one of the most popular programming languages for beginners and experienced developers.</p>
Its simple syntax, vast standard library, and thriving ecosystem of open-source packages make Python a versatile language for building all kinds of applications. Python excels in many domains, from web apps and APIs to data science, machine learning, and automation.

This comprehensive guide covers the fundamentals of Python programming that you need to know as a beginner.

We will explore the key features of the language through examples and also see how to write complete Python programs for different tasks. By the end, you'll have the skills to build real-world projects. Let's get started!
<h4>Setting Up Python</h4>
Before we begin coding in Python, we need to install it on the machine. The latest stable version is <a class="attrlink" href="https://www.python.org/download/releases/3.0/" target="_blank" rel="noopener noreferrer nofollow">Python 3,</a> which has many improvements over <a class="attrlink" href="https://www.python.org/download/releases/2.0/" target="_blank" rel="noopener noreferrer nofollow">Python 2</a>.

Head to <a href="http://python.org" target="_blank" rel="noopener noreferrer nofollow">python.org</a> and download the Python 3 installer for your operating system. This will include the Python interpreter, standard library, and development tools like the IDLE editor.

Be sure to check the box that adds Python to PATH during installation. After installation completes, open the command prompt or terminal and run:

<code>python --version</code>

This should print the installed Python version. Congrats, you now have Python ready for programming on your system!
<h4>Python Interpreter</h4>
The Python command launches the Python interpreter - an interactive shell that can execute code line by line.

For example, try this:

<code>print("Hello World!")</code>

This prints the famous starter message. The interpreter is great for testing snippets and modules in an exploratory manner.

You can do arithmetic like 2 + 3 and assign variables like x = 5. It's also helpful for debugging scripts one statement at a time. Just type Python in the terminal to start the interpreter.

But for larger programs, we'll want to write the code in a file that can be repeatedly executed.
<h4>Python Scripts</h4>
While the interactive shell is great, real applications are written as scripts saved in .py files. Open up your favorite text editor like VS Code, Atom, or Sublime, and create a file named <a href="http://first.py" target="_blank" rel="noopener noreferrer nofollow">first.py</a> with these contents:

<code>print("This is my first Python script!")</code>

This is a simple Python script displaying a message. To execute it, open the terminal and run the following:

<code>python </code><a href="http://first.py" target="_blank" rel="noopener noreferrer nofollow"><code>first.py</code></a>

You should see the print message on the next line. By convention, Python scripts are named using lower_case_with_underscores. Make sure to include the .py extension.

Now that you know how to write and run scripts, let's review the Python programming concepts.
<h4>Python Syntax Basics</h4>
Python has a simple and elegant syntax that is easy to learn. Here are some of the key elements:
<ul>
 	<li>Code is indented using whitespace instead of braces {}</li>
 	<li>Colon: indicates the start of the code block</li>
 	<li>Comments start with the # symbol</li>
 	<li>Semicolons; are optional at the end of statements</li>
 	<li>Parentheses () for function calls and expressions</li>
</ul>
Here's a simple example with these elements:
<pre><code class="language-python"># This is a comment 

x = 5 # Assign 5 to variable x
if x &gt; 0: # Start if code block
  print(x) # Indented - so part of if block
print("Done") # Runs after if block</code></pre>
Some other Python syntax basics:
<ul>
 	<li>Variables don't need explicit declaration</li>
 	<li>Newlines don't matter - one statement per line is the convention</li>
 	<li>Has both single ' ' and double " " quoted strings</li>
 	<li>Supports multiple variable assignment like x, y = 1, 2</li>
</ul>
Python has a clear visual layout, making the code easy to read and understand.
<h4>Variables and Data Types</h4>
Like most languages, Python has variables that can store values in memory for later use.

Variables are named labels that reference a value. For example:
```python
message = "Hello" # String variable
count = 5 # Integer variable 
price = 9.99 # Float variable
```
We can then use these variable names instead of values in the code.

Some rules for Python variables:
<ul>
 	<li>Named using alphanumeric characters A-Z a-z 0-9 and underscores _</li>
 	<li>Case-sensitive - message and Message are different variables</li>
 	<li>Can reassign values to variables at any time</li>
</ul>
Python is a dynamically typed language. This means variables do not need explicit data type declaration. The interpreter infers and sets the type automatically based on value.

Some common Python data types:
<ul>
 	<li>Integers - whole numbers like 10, 100, -50</li>
 	<li>Floats - decimals like 3.14, 9.99</li>
 	<li>Strings - text as a sequence of Unicode characters in 'single quotes' or "double quotes."</li>
 	<li>Boolean - True or False value</li>
 	<li>List - ordered collection in [square brackets]</li>
 	<li>Tuple-ordered immutable collection in (parentheses)</li>
 	<li>Set - unordered collection of unique objects in {curly braces}</li>
 	<li>Dictionary - collection of key-value pairs like {"key1": "value1"}</li>
</ul>
Let's see some examples of different data types:
```python
# Integer

num = 10 


# Float

price = 9.99


# String

message = 'Hello World'


# Boolean

flag = True


# List

numbers = [1, 2, 3]


# Tuple

point = (2, 3) 


# Set

unique = {1, 2, 3}


# Dictionary 

info = {"name": "John", "age": 30}
```
Python is a dynamically typed language so we don't need to specify types explicitly. The interpreter handles that automatically.
<h4>Operators</h4>
Operators are special symbols that perform operations on variables and values. Python includes all standard arithmetic, comparison, logical, and bitwise operators:
<ul>
 	<li>Arithmetic - +, -, <em>, /, %, </em>*, //</li>
 	<li>Comparison - ==, !=, &gt;, &lt;, &gt;=, &lt;=</li>
 	<li>Logical - and, or, not</li>
 	<li>Bitwise - &amp;, |, ~, ^, &gt;&gt;, &lt;&lt;</li>
</ul>
Let's see them in action through some examples:
```python
# Arithmetic

print(2 + 3) # 5

print(10 - 3) # 7 


# Comparison 

print(5 == 5) # True

print(10 != 20) # True


# Logical

print(True and False) # False

print(not False) # True


# Bitwise

print(12 &amp; 5) # 4
```
These operators allow for performing all types of mathematical, comparison, logical, and bitwise operations in Python.
<h4>Control Flow</h4>
Control flow refers to the order in which statements are executed in a program. Python includes several constructs for controlling the flow:

<strong>Conditionals</strong> - Perform different actions based on conditions:
```python
age = 20
if age &gt;= 18:
  print("Eligible to vote")
else:
  print("Not eligible")
```
<strong>Loops</strong> - Repeat code block multiple times:
```python
for i in range(5):
  print(i) # Prints 0 1 2 3 4  

x = 0
while x &lt; 5:
  print(x)
  x = x + 1
```
<strong>Functions</strong> - Reuse code in modules:
```python
def greet(name):
  print("Hello "+ name)
greet("John")
```
Control flow statements like these allow complex and flexible programs in Python.
<h4>Strings</h4>
Text manipulation is an important aspect of any programming language. Python has a set of built-in methods for common string operations:
```python
message = "Hello World" 


# Length
print(len(message)) # 11


# Contains
print("Hello" in message) # True


# Concatenate
print("Hello " + "World") # Hello World


# Uppercase 
print(message.upper()) # HELLO WORLD


# Lowercase
print(message.lower()) # hello world


# Startswith / Endswith
print(message.startswith("H")) # True


# Split into list
print(message.split(" ")) # ['Hello', 'World']
```
Some other common string methods include strip(), replace(), find(), index(), etc. Strings in Python are immutable - i.e., the operations return new strings rather than modifying the original.
<h4>Conditionals and Loops</h4>
Branching and looping constructs enable non-linear program flow based on conditions.

If-else statement checks a condition and executes different blocks:
```python
age = 20
if age &gt;= 18:
  print("Eligible") 
else:
  print("Not eligible")</code></pre>
For loop iterates over items in a sequence:
<pre><code class="language-python">colors = ["red", "green", "blue"]
for color in colors:
  print(color)
```
While the loop executes the block until the condition is false:
```python
count = 5
while count &gt; 0:
  print(count)
  count = count - 1
```
Break and continue statements can change loop execution. Conditionals and loops are found in almost every Python program.
<h4>Functions</h4>
Functions organize code into reusable blocks that perform specific tasks. They take parameters, operate on them, and return results.

In Python, we define functions using the def keyword:
```python
def multiply(x, y):
  return x * y
print(multiply(2, 3)) # 6
```
Function parameters have a local scope, while variables declared outside have a global scope. Functions can return multiple values as tuple:
```python
def minmax(numbers):
  return min(numbers), max(numbers)
mini, maxi = minmax([1, 2, 3, 4])
```
Functions make code modular and increase reusability.
<h4>Classes and Objects</h4>
Python is an object-oriented language, meaning it supports classes, inheritance, and polymorphism.

A class defines attributes and behaviors for an object:
```python
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def greet(self):
    print(f"Hello, my name is {self.name}")
p1 = Person("John", 30)
p1.greet()
```
__init__() constructor method initializes the object state while other methods define behaviors. Objects can access their attributes and invoke methods.

Classes can inherit from other classes:
```python
class Student(Person):
  pass
s1 = Student("Mary", 20)
s1.greet() # Inherited method
```
OOP allows the modeling of real-world entities and handles complexity through abstraction and polymorphism.
<h4>Modules</h4>
Python enables the modularization of code using modules. A module is simply a .py file containing related classes, functions, etc.

Modules can be imported using the import keyword:
```python
# File: utils.py
def greet(name):

  print("Hello "+ name)

# Main file
import utils
utils.greet("John")
```
The from keyword imports specific objects from a module:

<code>from utils import greet</code>

Modules make code more organized and improve reusability. The Python standard library provides many useful built-in modules.
<h4>Python Standard Library</h4>
Python ships batteries include a large standard library of modules for common tasks:
<ul>
 	<li>sys - system functions and info</li>
 	<li>os - operating system interfaces</li>
 	<li>math - mathematics operations</li>
 	<li>random - generate random numbers</li>
 	<li>datetime - date and time handling</li>
 	<li>JSON - encode and decode JSON</li>
 	<li>re - regular expressions</li>
 	<li>http - HTTP internet protocols access</li>
 	<li>sqlite3 - database access</li>
 	<li>zlib - compression</li>
</ul>
And many more! The full list is in the Python documentation.

Let's see an example of the OS module:
```python
import os
print(os.getcwd()) # Prints current working directory
```
There is no need to install additional packages for common programming tasks.
<h4>External Libraries</h4>
While the standard library is extensive, Python developers rely on a vast ecosystem of open-source third-party libraries for more complex tasks.

Some popular ones:
<ul>
 	<li>NumPy - foundational package for scientific computing</li>
 	<li>Pandas - data analysis and manipulation</li>
 	<li>Matplotlib - 2D plotting and visualization</li>
 	<li>Seaborn - statistical data visualization</li>
 	<li>OpenCV - image and video processing</li>
 	<li>TensorFlow - machine learning</li>
 	<li>Keras - neural networks</li>
 	<li>Scrapy - web scraping framework</li>
 	<li>Django - full-featured web framework</li>
 	<li>Flask - micro web framework</li>
 	<li>PyQt - GUI development</li>
</ul>
These libraries can be installed using Python's pip package manager. They extend Python's capabilities to specialized domains.
<h4>Virtual Environments</h4>
Python virtual environments allow you to isolate project dependencies locally.

They essentially create a self-contained space separate from the global packages for Python packages.

This allows the installation of different versions of libraries for different projects.

Environments can be created using the Venv module:

<code>python -m venv projectenv</code>

This will set up a new environment in the projectenv folder. Activate it:

<code>source projectenv/bin/activate</code>

Now pip will install packages into this virtual environment. Deactivate to exit the environment.

Environments ensure project dependencies don't conflict with each other.
<h4>File I/O</h4>
Reading and writing files is an integral operation in many programs. Python has a built-in open() function to access files.

Files must be opened in read r, write w, or append a mode.

To read a file:
```python
file = open('data.txt', 'r')
content = file.read()
file.close()
```
To write a file:
```python
file = open('data.txt', 'w')  
file.write('Some content')
file.close()
```
Make sure to close files after accessing them. The with statement auto closes files even after exceptions.

CSV and JSON modules process these data formats. Overall, Python makes working with files very straightforward.
<h4>Exception Handling</h4>
Exceptions are errors that disrupt program flow, like missing files, network failure, etc.

Python has built-in exception classes, and we can define custom exceptions by inheriting from Exception.

Exceptions can be handled using try-except blocks:
```python
try:
  file = open('data.txt') # May raise IOError
  content = file.read() 
except IOError:
  print("Could not open file")
```
This prevents the program from crashing. Multiple except blocks can handle different exceptions.

Finally, clause executes cleanup code regardless of exception. Proper exception handling makes programs robust.
<h4>Comprehensions</h4>
List, set, and dictionary comprehensions provide a concise way to create collections from sequences.
```python
nums = [1, 2, 3]
squares = [x**2 for x in nums] # [1, 4, 9]
```
Set and dictionary comprehensions:
```python
names = ["John", "Mary"] 
unique = {name[0] for name in names} # {'J', 'M'}
person = {"name": "John", "age": 20}
copy = {k:v for k,v in person.items()}
```
Comprehensions are a clean way to transform and initialize collections.
<h4>Decorators</h4>
Python decorators are constructs that wrap a function to modify its behavior without permanently changing it.
```python
def uppercase(func):
  def wrapper():
    original_result = func()
    modified_result = original_result.upper()
    return modified_result
  return wrapper


@uppercase
def greet():
  return "Hello!"
print(greet()) # HELLO!
```
The decorator @uppercase applies wrapper() function on greet() to convert the result to uppercase.

Decorators are commonly used to add logging, permissions, or caching to functions.
<h4>Conclusion</h4>
This concludes our comprehensive guide to Python programming for beginners. We started with syntax, data types, operators, variables, control flow, and functions.

Then, we covered more advanced topics like strings, modules, file and exception handling, classes, and objects. Finally, I saw some of Python's unique aspects - comprehension and decorators.

After reviewing these concepts with examples, you should feel comfortable reading and writing basic Python programs.

The next step is to apply these skills to build projects, contribute to open-source packages, and join the Python community!

The key is to keep practicing by coding regularly. Python has a vibrant ecosystem of frameworks and tools that enable you to build complex applications.

The Python documentation and communities like StackOverflow are great resources for troubleshooting errors and learning best practices.

I hope you enjoyed reading this guide and feel motivated to start your Python programming journey. If you find this post exciting, find more exciting posts on <a class="attrlink" href="http://blog.learnhub.africa/" target="_blank" rel="noopener noreferrer nofollow">Learnhub Blog</a>; we write everything tech from <a class="attrlink" href="https://blog.learnhub.africa/category/cloud-computing/" target="_blank" rel="noopener noreferrer nofollow">Cloud computing</a> to <a class="attrlink" href="https://blog.learnhub.africa/category/frontend/" target="_blank" rel="noopener noreferrer nofollow">Frontend Dev</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/security/" target="_blank" rel="noopener noreferrer nofollow">Cybersecurity</a>, <a class="attrlink" href="https://blog.learnhub.africa/category/data-science/" target="_blank" rel="noopener noreferrer nofollow">AI</a>, and <a class="attrlink" href="https://blog.learnhub.africa/category/blockchain/" target="_blank" rel="noopener noreferrer nofollow">Blockchain</a>.
<h4>Resource</h4>
<ul>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/05/26/20-essential-python-extensions-for-visual-studio-code/" target="_blank" rel="noopener noreferrer nofollow">20 Essential Python Extensions for Visual Studio Code</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/04/27/using-python-for-web-scraping-and-data-extraction/" target="_blank" rel="noopener noreferrer nofollow">Using Python for Web Scraping and Data Extraction</a></li>
 	<li><a class="attrlink" href="https://blog.learnhub.africa/2023/06/06/13-powerful-python-snippets-to-automate-tasks/" target="_blank" rel="noopener noreferrer nofollow">13 Powerful Python Snippets To Automate Tasks</a></li>
 	<li><a class="attrlink" href="https://www.python.org/about/gettingstarted/" target="_blank" rel="noopener noreferrer nofollow">Getting Started with Python</a></li>
</ul>