Skip to main content

Python Basics

Python Basics

This section introduces the basic building blocks of Python. By the end of this section, you will understand Python syntax, variables, data types, conditionals, loops, and functions. Let’s get started with the fundamentals of Python programming.

3.1 Python Syntax

Python uses indentation to define code blocks, unlike other languages that rely on braces or keywords. Here’s an example:

# Python syntax
if True:
    print("This is Python!")  # Correct indentation

The print() function is used to display output in Python. Python code is case-sensitive, meaning that variables myVar and myvar would be treated as two different variables.

3.2 Variables and Data Types

Variables in Python are used to store data. You don’t need to explicitly declare the variable type; Python infers the type based on the assigned value.

3.2.1 Variable Assignment

# Assigning variables
x = 10  # Integer
y = 3.14  # Float
name = "Alice"  # String
is_active = True  # Boolean

3.2.2 Data Types

Common data types in Python include:

  • int: Integer values (e.g., 10)
  • float: Decimal values (e.g., 3.14)
  • str: Strings (e.g., "Hello")
  • bool: Boolean values (e.g., True, False)

3.2.3 Checking Data Types

You can check the type of a variable using the type() function:

# Checking the type of a variable
print(type(x))  # 
print(type(y))  # 
print(type(name))  # 

3.3 Conditional Statements

Conditional statements allow you to control the flow of your program based on certain conditions. Python supports if, elif, and else statements.

# Example of conditional statements
x = 10

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

Python evaluates conditions as either True or False, and executes the corresponding block of code based on the result.

3.4 Loops

Python supports two types of loops: for loops and while loops.

3.4.1 For Loop

The for loop iterates over a sequence (e.g., list, tuple, string) and executes the code block for each item in the sequence.

# Example of a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

3.4.2 While Loop

The while loop keeps executing as long as the condition remains True.

# Example of a while loop
count = 0
while count < 5:
    print(count)
    count += 1

3.5 Functions

Functions are reusable blocks of code that perform a specific task. They allow you to encapsulate functionality, making your code more modular and maintainable.

3.5.1 Defining a Function

To define a function in Python, use the def keyword followed by the function name and parentheses:

# Defining a function
def greet(name):
    print(f"Hello, {name}!")

# Calling the function
greet("Alice")

3.5.2 Return Values

Functions can return values using the return statement:

# Function with a return value
def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

Comments

Popular posts from this blog

Arrays, Lists, and LinkedLists in Java

Arrays, Lists, and LinkedLists in Java Understanding the differences between arrays, lists, and linked lists is fundamental in Java programming. Each data structure has its unique characteristics and use cases. This guide will delve into how these structures work, their advantages and disadvantages, and provide examples of how to use them in Java. 1. Arrays in Java An array is a fixed-size data structure that stores elements of the same type in contiguous memory locations. Arrays are one of the simplest and most commonly used data structures in Java. 1.1 Declaring and Initializing Arrays You can declare and initialize an array as follows: public class ArrayExample { public static void main(String[] args) { // Declaration and initialization int[] numbers = new int[5]; // Array of integers with size 5 numbers[0] = 10; numbers[1] = 20...

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration

Guide to Creating and Executing C Executables with Shared Libraries and Java Integration 1. Compiling a C Program to an Executable Step 1: Write a C Program #include <stdio.h> int main() { printf("Hello, World!\\n"); return 0; } Step 2: Compile the C Program gcc -o example example.c 2. Executing the C Program in the Console Step 3: Run the Executable ./example 3. Including Shared .so Libraries Step 4: Create a Shared Library #include <stdio.h> void my_function() { printf("Shared Library Function Called!\\n"); } gcc -shared -o libmylib.so -fPIC mylib.c Step 5: Update the C Program to Use the Shared Library #include <stdio.h> void my_function(); int main() { my_function(); printf("Hello, World!\\n...

Mastering Java Maps

In Java, maps are a versatile and powerful data structure that allow for the efficient storage and retrieval of key-value pairs. This document will cover various aspects of using maps in Java, from basic operations to advanced use cases. Overview of Maps Maps are part of the Java Collections Framework and provide a way to store data in key-value pairs. The keys are unique, and each key maps to exactly one value. Maps are crucial for tasks where quick lookups, insertions, and deletions are needed. Types of Maps Java provides several implementations of the Map interface, each with different characteristics: HashMap: Stores key-value pairs in a hash table. It does not guarantee any order of its elements. It allows one null key and multiple null values. LinkedHashMap: Extends HashMap and maintains a doubly-linked...