Python 102! Python Basics for Web Development
Tags: webdev, python, beginners, tutorial
Published: 2024-01-18 10:51:41

## Introduction to Python basics
Learning the fundamentals of any programming language simplifies the learning curve for advanced concepts in that language. Learning Python basics will make the journey of learning advanced concepts in software development, data science, and artificial intelligence more accessible and fulfilling.

In this article, you will learn:

 
- <a href= "#print" >Printing in Python</a>

    Learn how to display text-based information using a 
    `print` statement

- <a href= "#Installation" >How to Configure your development environment</a>

     Steps of configuring your development environment so 
     that you're ready to learn Python for web development.

- <a href= "#variable-datatypes" >Variables, Data Types, and Operators</a>
 
     Grasp the essentials of variable assignment, data 
     types, and operators in Python.

- <a href= "#control-flow" >Control Flow</a>

     Dive into the foundational concepts of control flow
 

- <a href= "#function-modules" >Functions and Modules:</a>

      Learn how to structure code using functions and 
      modules, promoting modular and reusable design.
 

- <a href= "#input-output" >Input/Output in Python:</a> 
      Explore input and output mechanisms, crucial for 
      interaction between the user and the program.

- <a href= "#project" >How to build a simple program</a>

      Build a basic calculator program that incorporates 
     `control flow` and `functions`.




<h3 id="Installation">How to Configure your development environment</h3>

 Follow these steps:

- Install Python:

 Download and install the latest version of Python from the official [Python website.](https://wiki.python.org/moin/BeginnersGuide/Download)

- [Code Editor:](https://pyflo.net/ide/)

Select a code editor that aligns with your preferences. Popular choices include [Visual Studio Code](https://visualstudio.microsoft.com/), [PyCharm](https://www.jetbrains.com/pycharm/download/?section=linux), and [Atom](https://atom-editor.cc/).

- [Virtual environment:](https://realpython.com/python-virtual-environments-a-primer/)

 Create a virtual environment to manage project dependencies and maintain a clean environment for each project:

`python3 venv venv`

Activate the virtual environment based on your operating system:

```
On Windows

.\venv\Scripts\activate

```
```
On macOS and Linux

source venv/bin/activate

```
Now that your environment is set up. Let's delve into the basics of Python.

<h3 id="print">Printing in Python</h3>

In the field of computer programming, interactions mainly involve inputs and outputs. This article specifically focuses on generating text-based output. The Python 'print' statement is a key tool for displaying information on the screen, serving as an essential starting point for running programs.

![Diagram that show the process of input and output in a computer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a1iy0uzto0rj5wxd0aa.png)


_Syntax of the 'print' Statement:_

In Python, the 'print' statement is used to display output. It allows programmers to communicate with users by presenting text-based outputs.

```
print('Hello, world!')
```

![Python code that prints 'Hello, world'](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qs6gf376vcbz6os4bcin.png)
Learn more about the 'print' statement [here](https://pyflo.net/print/)


<h3 id="variable-datatypes">Variable in Python</h3>

A variable is a named location in memory where a programmer can store and retrieve data. Choosing variable names is at the discretion of the programmer.

_Variable Assignment:_

The process involves two steps:

1. Declaration: Choose a name for the variable.
2. Assignment: Associate a value with the variable using the '=' operator.

```
# Declaration and Assignment
name = 'John Doe'
age = 25
```
In this example, the variable 'age' is assigned the value of 25, and the variable 'name' is assigned the value of 'John Doe'. Learn more about [Python Variable here](https://www.w3schools.com/python/python_variables.asp)

### Data Types

Data types in Python define the nature of the values that a variable can hold. A variable can hold various data types, each serving a specific purpose and allowing for different operations. Here are some common data types in Python:

```
# Numeric data types
num1 = 10  # integer
num2 = 3.14  # float

# Text data type
name = "John Doe"  # string

# Boolean data type
is_active = True  # boolean

# List data type
fruits = ["apple", "banana", "orange"]  # list

# Tuple data type
coordinates = (10, 20)  # tuple

# Dictionary data type
person = {"name": "John", "age": 30, "city": "New York"}  # dictionary

# Set data type
unique_numbers = {1, 2, 3, 4, 5}  # set

# None data type
empty_value = None  # None
```

You can determine the data type of any variable using the built-in type() function:

```
name = 'John Doe'

print(type(name))
```
Learn more about Data types [here](https://www.w3schools.com/python/python_datatypes.asp)

### Operators

Operators in Python are symbols or keywords that perform operations on variables and values. They enable:


- Arithmetic operators

```
x = 10
y = 3

addition = x + y
subtraction = x - y
multiplication = x * y
division = x / y
modulus = x % y
exponentiation = x ** y
floor_division = x // y

```
- Comparison operators

```
a = 5
b = 7

equal = a == b
not_equal = a != b
greater_than = a > b
less_than = a < b
greater_than_or_equal = a >= b
less_than_or_equal = a <= b
```

- Logical operators

```
p = True
q = False

logical_and = p and q
logical_or = p or q
logical_not = not p
```
- Assignment operators

```
num = 10

num += 5  # equivalent to num = num + 5
num -= 3  # equivalent to num = num - 3
num *= 2  # equivalent to num = num * 2
num /= 4  # equivalent to num = num / 4
num %= 3  # equivalent to num = num % 3
num //= 2  # equivalent to num = num // 2
num **= 3  # equivalent to num = num ** 3
```
- Membership operators

```
list1 = [1, 2, 3, 4, 5]

is_member = 3 in list1
is_not_member = 6 not in list1
```
- Identity operators

```
x = 10
y = 10

is_same = x is y
is_not_same = x is not y
```
_**Understanding variables, data types, and operators provides the fundamental knowledge required to write effective Python programs. These concepts serve as the building blocks for more advanced topics in programming and data manipulation**_





<h3 id="control-flow">Control Flow in Python</h3>

Control flow in Python refers to the order in which statements are executed in Python. It allows you to make decisions, repeat actions, and control the flow of your program. Python provides several control flow statements, including conditional statements(if, Elif, else), loops(for, while), and other flow control constructs.

- _Conditional Statements(if, elif, else):_

Conditional statements allow you to execute different code based on whether a certain conditional is true or false.

Example1 Simple `if` statement:

```
x = 10

if x > 0:
   print("x is positive")
```
_In this example, the code inside the `if` block is executed only if the condition `x > 0` is true._

Example2 `if-else ` statement:

```

x = -5

if x > 0:
    print("x is positive ")
else:
   print("x is non-positive")
```
_In this case, if the condition x > 0 is true, the first block is executed; otherwise, the block inside else is executed._

Example 3: `if-elif-else` statement:

```
score = 85

if score >= 90:
    print("B")
elif 80 <= score < 90:
    print("B")
else:
    print("C")
```

This example demonstrates a chain of conditions. If the first condition is unmet, it checks the next condition (`elif`). If none of the conditions are true, the `else` block is executed.

- _Loops (for, while)_

Loops allow you to repeatedly execute a block of code

Example1 `while` loop:

```
count = 0 

while count < 5:
    print(count)
    count += 1
```

_This `while` loop prints numbers from 0-4. The loop continues as long as the condition `count < 5` is true._

Example2 `for` loop:

```
fruits = ["apple", "banana", "cherry"]

for fruits in fruits:
    print(fruits)
```
_This loop iterates over each element in the fruits list, printing each fruit._


- _Break and Continue Statement_

example1 `break` statement:

numbers= [1,3,4,5,5]

```
for num in numbers:
    if num == 4:
       break
    print(num)
```
_This loop prints numbers until it encounters 4, at which point the break statement exits the loop._

Example2 `continue` statement:

```
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue
    print(num)
```
_The continue statement skips the code below it for the current iteration if the condition is met. In this case, it skips printing 3._

Learn more about control flow [here](https://www.w3schools.com/python/python_conditions.asp) 


_**These control flow statements and conditional statements provide the flexibility to create complex programs by altering the flow of execution based on conditions and iterations.**_




<h3 id="function-modules">Functions and Modules in Python</h3>

A function is a block of organized, reusable code that performs a specific task. It only runs when it is called. You can pass data, known as parameters, into a function.

_Defining a function_

In Python a function is defined using the def keyword:

```
def greet(name):
    # This function greets the person passed in as a parameter.
    print("hello, " + name + "!")

# Callin the function
greet("Alice")
```
_In this example, greet is a simple function that takes a name parameter and prints a greeting._   

_Return statement_:

The function can also return data:

```
def add_numbers(a,b):
    # This function adds two numbers and returns the result
    result = a + b
    return result

sum_result = add_numbers(3,4)
print("Sum:", sum_result)
```
_The add_numbers function returns the sum of two numbers, and we store the result in the sum_result variable._


### Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix `.py`. The module helps organize code into separate files, promoting code reusability.

Creating a module:

let's say we have a module named `math_operations.py`:

```
# math_operations.py

def add(a,b):
    return a + b

def subtract(a,b):
    return a-b
```
Now, we can use this module in another script.

Using a Module:

```
# main_script.py

# Importing the math_operations module
import math_operations

# Using functions from the module
result_add = math_operations.add(5, 3)
result_subtract = math_operations.subtract(8, 2)

print("Addition Result:", result_add)
print("Subtraction Result:", result_subtract)
```
_In this example, we import the math_operations module and use its functions in the main_script.py._

Here is the result in `VScode` editor:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb8vlcdbxyhv2kyj5nfb.png)

<h3 id="input-out">Standard Input and Output</h3>

- `input()` function

The `input()` function is used to take user input from the keyboard. It reads a line of text from the user as a string.

```
name = input("Enter your name: ")
print("Hello, " + name + "!")
```
_In this example, the user is prompted to enter their name, and the input is stored in the name variable._

- `print()` function

As we discussed earlier, the `print()` function is used to display output on the console

```
age = 25
print("Your age is:", age)
```
_This example prints the value of the age variable._

<h3 id= "project">Final project:</h3>

Build a basic calculator program on your own that incorporates control flow and functions.

If you are stuck you can check an example [here](https://github.com/kihuni/Explore-Backend/blob/main/Intro-to-Python-article/Python_Web_Development/Final-project/calculator.py)


<h3 id = "conclusion">Conclusion:</h3>

In conclusion, Python's fundamentals for web development have been explored, covering the setup of a development environment, basics of Python syntax, data types, operators, control flow, functions, and modules. These foundational concepts lay the groundwork for further exploration into web development using Python. By adhering to best practices and maintaining a clean coding environment, developers can build scalable and maintainable web applications. Keep exploring and building upon these fundamentals to gain proficiency in Python for web development.