TNS
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
NEW! Try Stackie AI
Python

Basic Python Syntax: A Beginner’s Guide To Writing Python Code

Learn all the basic Python syntaxes you need to start coding. This guide covers comments, variables, functions, loops, and more — explained simply for beginners.
Apr 29th, 2025 12:00pm by
Featued image for: Basic Python Syntax: A Beginner’s Guide To Writing Python Code

Every programming language has a unique syntax. Some languages borrow syntax from others, while others create something wholly different. No matter the language you intend to use, you have to understand its syntax; otherwise, you’ll struggle to get anything done.

Syntax is a set of rules that define how code is written in a particular language. Some of the key elements of a language’s syntax include:

  • Keywords are reserved words in the programming language, such as “if,” “else,” and “for.”
  • Variables are used to store data values and have names, types, and scopes.
  • Control Flow Statements determine the sequence of execution in a program.
  • Indentation determines code blocks.
  • Comments make it possible to document your code inline.

Basic Python Syntax

Let’s take a look at basic Python syntax, which is comprised of the same items above with the addition of:

  • Functions
  • Data types
  • Classes and Objects
  • Lists, Tuples, and Dictionaries

Here’s a basic Python script that shows most of the elements that make up the basic syntax:

# Variable Declaration and Assignment

x = 5  # Integer variable assignment with ‘=’ symbol. The value of x is set to 5.

y = “Hello!” # String variable assignment – Strings are defined using the quotes “” around text content!

# Conditional Statements

if y == “Hello”:  

print(“Greeting found!”)

else:

print(“No greeting message”)   

# Loops & Repetition

fruits = [“apple”, “banana”, “cherry”] # Create a list of fruits, using square brackets!

for fruit in fruits:  # Loop through the ‘fruits’ list. Each time it enters the loop, it will execute this line

print(fruit)

def greet_user(name):

“””This function greets a user by name.””” # A comment describing what the function does. It can be helpful to understand how it works!

print(f”Hello, {name}!”)  # Using f-strings for string formatting (allows easy replacement of placeholders with variables)

greet_user(“Alice”)   # Call ‘greet’ and pass in a name as an argument

A breakdown of the code looks like this:

  • Variable Declaration and Assignment:
    • x = 5 creates a variable named “x” and assigns the integer value 5 to it.
    • y = “Hello!” creates another variable named “y” and assigns the string “Hello!”.
  • Conditional Statements (if-else): The code checks if the value of “y” is equal to a certain text — that would be true or false, causing different actions!
    • if y == “Hello”: If “y” has the exact words “hello”, it will print a message
  • Loops (for loop): The for loop iterates through each item in the list. In this case:
    • It assigns values to “fruit” from the list (fruits).
    • Each print(fruit) statement displays a different fruit on its own line.

Writing and Executing Your First Python Program

Now that you’ve seen how the code is laid out, let’s write our first Python program. As is usually the case, we’ll create a Hello, World! application and demonstrate how it works in both interactive and script mode.

Hello, World! Using Interactive Mode

Interactive Mode is exactly what it sounds like: it’s a way to use Python interactively. Instead of creating a file with your code, you run statements through an interpreter via the terminal window.

To access Python’s Interactive Mode, open your terminal window and type:

python3

Your prompt should change to:

>>>

At that prompt, type the following:

print(“Hello, New Stack!”)

The output should be:

Hello, New Stack!

That was simple, right?

To exit interactive mode, type the following:

exit()

Hit Enter and you’ll be back at your usual prompt.

Let’s do the same thing with script mode.

Hello, World! Using Script Mode

With Script Mode, you create a file that houses your code. For example, let’s create the file helloworld.py with the command:

nano helloworld.py

If you’re using a different operating system than Linux, you’ll need to alter the above command to use your default text editor.

Notice the file ends in .py, which indicates the file is a Python script. You don’t have to use the .py extension, but it’s best to do so.

In that file, type the same line you entered during Interactive Mode like so:

print(“Hello, New Stack!”)

Save and close the file with the Ctrl-X keyboard shortcut.

Congratulations, you’ve just written your first Python program.

Running Your Python Script

You’ve already seen how to run the Interactive Mode, but now let’s find out how to run that first program you created, helloworld.py. We do this by using the python3 command like so:

python3 helloworld.py

As expected, the output will be:

Hello, New Stack!

Python Syntax Fundamentals

Indentation and Whitespace

The key principles of Python indentation and whitespace include:

The Key Principles:

  • Indentation Defines Code Blocks: Python uses indentation to define blocks of code that should be executed together. Without proper indentation, your program will encounter syntax errors and won’t function correctly. Typically, indentation in Python is four spaces.
  • Consistency: Indentation consistency matters. If you don’t use the same number of spaces or tabs consistently throughout all your code files, it could not only lead to confusion but your script not functioning.
  • One-Level: Indent blocks that contain multiple lines of Python’s “language rules.” Such rules are made up of the following types:
    • if, elif, else statements
    • Loops (for, while)
    • Function calls (like print(a) )
  • Indentation is not merely a code formatting rule, but it’s also how Python “understands” the flow of your program.

Comments in Python

There are two types of comments in Python: single-line and multiple-line. A single-line comment might look like this:

# This is my comment

The best way to add a multiline comment in Python is with docstrings, which are encased in triple quotes like this:

“””This is my comment.

I love this comment.

It is the best comment.”””

Everything in between the triple quotes is ignored by Python.

Variables and Data Types

Operators and Expressions

There are different types of operators and expressions for Python. You have:

  • Arithmetic operators for basic math, such as addition, subtraction, multiplication, and division (result = 5 + 3)
  • Comparison operators for comparing values and checking equality/inequality (is_equal = 5==5, if x > y, if x >= y)
  • Logical operators for combining conditions and performing logical comparisons (is_true = x > 0 and y < 10).

Control Flow Statements

If-Else Conditions

An if-else statement is used to execute a block of code when a certain condition is met. It checks for truth values and executes the corresponding code blocks based on these values.

The basic syntax of an if-else statement looks like this:

if expression:

# Code block to be executed if the condition is true

elif [optional]:

# Alternative code block to be executed if the initial condition is false, but this one evaluates to True

else:

# Default code block to be executed if none of the above conditions are met

Loops

Python has two different types of control statements that are used for repetition:

  • For Loops allow you to execute a block of code repeatedly based on the iterations over a sequence.
  • While Loops continue executing as long as a certain condition is true, regardless of whether it’s related directly to each individual item or not (this also allows for conditional logic).

Here’s a simple example of a Python loop:

# example using an integer variable and range()

for i in range(5):

print(i)

fruits = [‘apple’, ‘banana’, ‘cherry’]

for fruit in fruits:

   print(fruit)

Functions in Python

A function is a block of code that can be executed multiple times from different parts of a program. Functions make up the core structure of any well-written piece of software and are defined as such:

  • Define the name of the function
  • The def keyword is used to indicate to Python that what follows is a function.
  • Parentheses are used to encapsulate the function.

Here’s a sample function definition:

def greet(name):

print(“Hello ” + name)

That function can be called from within a Python script like so:

greet(‘John’)

# Outputs: Hello John

Function Arguments and Return Values

You can also return values to their callers using the return statement like this:

def add(x,y):

return (x+y)

result = add(1,2)  # Outputs:3

print(result)

Importing and Using Modules

Python also allows you to import and use various modules. Modules are pre-written Python source files that serve different purposes. For example, you could use the built-in datetime module like this:

print(“Current date:”,datetime.datetime.now())

You could also import modules for use in your code. For example, there’s the time module. To import a module, you use the import keyword like so:

import time

You could then call that module like this:

time.sleep(5) # Wait for 5 seconds. Outputs: Output nothing (sleeps)

Error Handling in Python (try-except Blocks)

Python provides several ways to handle errors, but the most important is the try-except block, which is used to catch and handle exceptions that may occur during the execution of your code.

There are two parts to the try-except block:

  • Try Block contains the code that might raise an exception.
  • Except Block is used to handle exceptions raised in the try block.

Here’s an example of a try-except block:

try:

   num = int(input(“Enter a number: “))

   result = 5 / num

except ZeroDivisionError:

   print(“Cannot divide by zero!”)

except ValueError:

   print(“Invalid input. Please enter an integer.”)

else:

# Code to be executed if no exception is raised

print(f”Result: {result}”)

Best Practices for Writing Clean Python Code (PEP 8 Guidelines)

PEP 8 provides a set of rules for writing clean and maintainable Python code, which are:

  • Use import statements instead of from module import item.
  • Use meaningful variable names.
  • Keep functions concise.
  • Keep class methods concise and meaningful.
  • Use meaningful error messages.
  • Use triple quotes for docstring formatting.
  • Use consistent indentation (4 spaces).
  • Keep blank lines between logical sections or control structures.
  • Be cautious when formatting the code for documentation.
  • Avoid repeated lines of code.
  • Use loop constructs where possible to avoid recursion.
  • Make your code testable.

Conclusion

Python is one of the easiest programming languages to learn, which makes it a good choice for your first go at coding. If you follow the above suggestions, your experience will be far easier, especially as you get deeper involved with complex applications.

Created with Sketch.
TNS owner Insight Partners is an investor in: Control.
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.