Fundamentals 6 min read

Python Basics: Variables, Data Types, Control Flow, Loops, and Functions

This article introduces core Python programming concepts, covering variable creation, common data types, conditional statements, loop structures, and function definitions with examples of default, keyword, and variable arguments, providing a concise foundation for writing simple Python scripts.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Basics: Variables, Data Types, Control Flow, Loops, and Functions

1. Variables

In Python, variables are created by assignment without declaring a type; the language is dynamically typed, allowing type changes at runtime.

# Create variables

x = 5  # integer
y = "Hello"  # string
z = 3.14  # float

# Print variables print(x, y, z) # Output: 5 Hello 3.14 2. Data Types

Python supports many built‑in data types, including numbers (int, float, complex), strings, lists, tuples, dictionaries, and sets.

# Number types

a = 10  # int
b = 3.14  # float
c = 1 + 2j  # complex

# String name = "Alice" # List fruits = ["apple", "banana", "cherry"] # Tuple coordinates = (10.0, 20.0) # Dictionary person = {"name": "Bob", "age": 30} # Set colors = {"red", "green", "blue"} 3. Conditional Statements

Use if, elif, and else to implement branching logic.

x = 10
if x > 0:
    print("x is positive")
elif x == 0:
    print("x is zero")
else:
    print("x is negative")

4. Loops

Python provides for and while loops for iteration.

# for loop over a list

for fruit in fruits:
    print(fruit)

# using range()

for i in range(5):  # 0 to 4
    print(i)

# while loop

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

5. Functions

Functions are reusable code blocks defined with the def keyword; they can accept parameters, return values, and have default, keyword, and variable arguments.

Define a function

def greet(name):
    """Print a greeting"""
    print(f"Hello, {name}!")

greet("Alice")  # call function

Return value

def add(a, b):
    """Return the sum of two numbers"""
    return a + b

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

Default parameters

def greet(name="World"):
    print(f"Hello, {name}!")

greet()          # uses default

greet("Alice")  # provides argument

Keyword arguments

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type}, and its name is {pet_name}.")

describe_pet(animal_type="hamster", pet_name="Harry")

Variable arguments

def make_pizza(*toppings):
    print("Making pizza with toppings:")
    for topping in toppings:
        print(f"- {topping}")

make_pizza("pepperoni", "mushrooms", "extra cheese")

def build_profile(first, last, **user_info):
    profile = {'first_name': first, 'last_name': last}
    profile.update(user_info)
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

Summary

The content above covers the fundamental syntax elements of Python programming. By understanding and mastering these concepts, you can start writing simple Python programs and gradually build more complex applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonData TypesfunctionsVariablesprogramming basics
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.