Python 102! Python Basics for Web Development

kihuni

kihuni

Posted on January 18, 2024

Python 102! Python Basics for Web Development

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:

How to Configure your development environment

Follow these steps:

  • Install Python:

Download and install the latest version of Python from the official Python website.

Select a code editor that aligns with your preferences. Popular choices include Visual Studio Code, PyCharm, and Atom.

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

Enter fullscreen mode Exit fullscreen mode
On macOS and Linux

source venv/bin/activate

Enter fullscreen mode Exit fullscreen mode

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

Printing in Python

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

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!')
Enter fullscreen mode Exit fullscreen mode

Python code that prints 'Hello, world'
Learn more about the 'print' statement here

Variable in Python

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
Enter fullscreen mode Exit fullscreen mode

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

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
Enter fullscreen mode Exit fullscreen mode

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

name = 'John Doe'

print(type(name))
Enter fullscreen mode Exit fullscreen mode

Learn more about Data types here

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

Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • Logical operators
p = True
q = False

logical_and = p and q
logical_or = p or q
logical_not = not p
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • Membership operators
list1 = [1, 2, 3, 4, 5]

is_member = 3 in list1
is_not_member = 6 not in list1
Enter fullscreen mode Exit fullscreen mode
  • Identity operators
x = 10
y = 10

is_same = x is y
is_not_same = x is not y
Enter fullscreen mode Exit fullscreen mode

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

Control Flow in Python

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

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.

Functions and Modules in Python

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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

Standard Input and Output

  • 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 + "!")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This example prints the value of the age variable.

Final project:

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

If you are stuck you can check an example here

Conclusion:

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.

💖 💪 🙅 🚩
kihuni
kihuni

Posted on January 18, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related