DEV Community

Cover image for Python Syntax: The Lazy Guide for Beginners
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Python Syntax: The Lazy Guide for Beginners

Python, known for its simplicity and readability, is an excellent programming language for beginners to embark on their coding journey.

Understanding Python syntax is essential for writing effective code and solving real-world problems. In this article, we will take you through a step-by-step guide that covers the fundamentals of Python syntax in a beginner-friendly manner.

So grab your favourite beverage, sit back, and dive into Python!

Python Basics

To get started, you need to install Python on your computer. Visit the official Python website, download the appropriate version, and follow the installation instructions.

Once installed, you can write and run Python code using a text editor or an Integrated Development Environment (IDE). Alternatively, you can explore Python's interactive mode, which allows you to experiment and execute code directly.

Installing Python

  • Go to the official Python website.
  • Click on the "Downloads" tab.
  • Choose the appropriate version of Python for your operating system. For most users, the recommended version is the latest stable release.
  • Download the installer for your operating system (e.g., Windows, macOS, or Linux).
  • Run the installer and follow the installation wizard instructions.
  • On Windows, check the box that says "Add Python to PATH" during the installation. This allows you to run Python from the command prompt easily.
      • You may need to use the terminal to run Python after installation on macOS and Linux.


Writing and Running Python Code
  • Open a text editor or an Integrated Development Environment (IDE). Some popular choices are Visual Studio Code, PyCharm, and IDLE (which come with the Python installation).
  • Create a new file and save it with a .py extension. For example, you can name it my_script.py.
  • In the file, you can start writing your Python code. Let's start with a simple "Hello, World!" example:

print("Hello, World!")

  • Save the file.

Running Python Code

  • Open a terminal or command prompt.
  • Navigate to the directory where you saved your Python file using the cd command. For example, if your file is on the desktop, you can use cd Desktop to navigate to the desktop directory.
  • Once you're in the correct directory, run the Python file using the Python command followed by the file name. For example:  

python my_script.py

  • You should see the output Hello, World! Printed in the terminal, indicating that your Python code was executed successfully.

Exploring Python's Interactive Mode

Python also provides an interactive mode, allowing you to experiment with Python code directly in the terminal or command prompt without needing a file.

  • Open a terminal or command prompt.
  • Type python and press Enter to start the Python interpreter.
    $ python
    
    Python 3.9.6 (default, Jun 29 2021, 05:14:37)
    
    [Clang 12.0.5 (clang-1205.0.22.9)] on darwin
    
    Type "help", "copyright", "credits" or "license" for more information.
    
    >>>
  • You can now start typing Python code directly into the prompt and press Enter to execute it. For example, you can try entering print("Hello, World!") and see the output immediately.

>>> print("Hello, World!")

Hello, World!

  • To exit the interactive mode, type exit() or press Ctrl + Z (Windows) or Ctrl + D (macOS/Linux).

Congratulations! You have installed Python, written your first Python code, and learned about Python's interactive mode. You can continue exploring Python by learning more about its syntax, data types, control flow statements, functions, and libraries. Happy coding

Variables and Data Types

In Python, variables are used to store and manipulate data. You'll learn to declare variables and follow naming conventions to write clean and understandable code.

Python supports various data types, including integers, floats, strings, and booleans. We'll cover each data type in detail and show you how to convert data from one type to another when needed.

Variables

Variables are used to store and manipulate data in Python. You can think of variables as containers that hold values. You can assign a value to a variable using the assignment operator (=). Here's an example:

# Variable assignment

x = 5

In the example above, we assigned 5 to the variable x. Now, we can use the variable x in our code.

Data Types

Python has several built-in data types. Each data type represents a different value and provides different operations that can be performed. Here are some commonly used data types in Python:

Integers

Integers represent whole numbers without any fractional part. They can be positive or negative. For example:

# Integer

age = 25

Floats

Floats represent real numbers with a fractional part. They are used to represent numbers with decimal places. For example:

# Float

temperature = 98.6

Strings

Strings represent sequences of characters. They are enclosed in either single quotes (') or double quotes ("). For example:

# String

name = "John Doe"

Booleans

Booleans represent the truth values True and False. They are used in logical operations and control flow statements. For example:

# Boolean

is_raining = True

Converting Data Types

Python provides built-in functions to convert data from one type to another. Here are some commonly used conversion functions:

  1. int() - converts a value to an integer.
  2. float() - converts a value to a float.
  3. str() - converts a value to a string.
  4. bool() - converts a value to a boolean.

Here are some examples:

# Converting to integer

x = int(3.5)  # x will be 3


# Converting to float

y = float("2.5")  # y will be 2.5


# Converting to string

z = str(42)  # z will be "42"


# Converting to boolean

w = bool(0)  # w will be False

It's important to note that not all conversions are possible or meaningful. For example, converting a string that doesn't represent a valid number to an integer will raise an error.

Naming Conventions

Following naming conventions to write clean and understandable code is important when choosing variable names. Here are some guidelines:

  • Variable names can contain letters, digits, and underscores.
  • They cannot start with a digit.
  • Python is case-sensitive, so age, Age, and AGE are considered different variables.
  • Choose meaningful and descriptive variable names to improve code readability.
    # Good variable names
    
    name = "John"
    
    age = 25
    
    is_student = True
    
    
    # Avoid using single-letter variable names or ambiguous names
    
    n = "John"  # Not descriptive
    
    a = 25  # Not clear what it represents

Understanding and using different data types in Python is fundamental for working with data and building applications. It allows you to store and manipulate different kinds of information efficiently.

Lists

Lists are used to store multiple values in a single variable. They are ordered and mutable, meaning you can modify, add, or remove elements. Lists are defined with square brackets ([]) and can contain elements of different data types. For example:

# List
fruits = ["apple", "banana", "orange"]

Tuples

Tuples are similar to lists but immutable, meaning their elements cannot be modified once assigned. Tuples are defined with parentheses (()) and can contain elements of different data types. For example:

# Tuple
coordinates = (10, 20)

Dictionaries

Dictionaries are used to store key-value pairs. Each value has a unique key, allowing for fast data retrieval. Dictionaries are defined with curly braces ({}) and consist of key-value pairs separated by colons (:). For example:

# Dictionary
person = {"name": "John", "age": 25, "is_student": True}

Accessing and Modifying Values

You can access and modify values in variables by using the variable name followed by the value's index or key. Here are some examples:

# Accessing values

print(fruits[0])          # Output: apple

print(coordinates[1])     # Output: 20

print(person["name"])     # Output: John


# Modifying values

fruits[1] = "grape"

coordinates = (30, 40)

person["age"] = 30

Type Checking

You can check the type of a variable using the type() function. Here's an example:

age = 25
print(type(age))        # Output: <class 'int'>

Type checking can be useful to ensure that a variable has the expected type before performing certain operations.

Type Conversion Methods

In addition to the built-in conversion functions mentioned earlier, some data types have their methods for type conversion. For example:

# String to integer

num_str = "42"

num_int = int(num_str)


# Integer to string

num_int = 42

num_str = str(num_int)


# List to string

my_list = ["apple", "banana", "orange"]

list_str = ", ".join(my_list)

These methods provide specific functionality and can be handy when dealing with specific data types.

By understanding and utilizing these different data types, you can effectively store and manipulate data in Python. Practice using variables and data types in your code to gain familiarity and improve your programming skills.

Operators and Expressions

Python provides a rich set of operators to perform mathematical calculations, compare values, combine conditions, and assign values to variables.

You'll explore arithmetic operators for basic calculations, comparison operators to evaluate conditions, logical operators to combine conditions, and assignment operators to assign values.

Understanding operator precedence and associativity is crucial to ensure the correct order of operations in complex expressions.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations on numerical values. Here are the commonly used arithmetic operators in Python:

# Addition

x = 5 + 3    # x will be 8


# Subtraction

y = 10 - 2   # y will be 8


# Multiplication

z = 4 * 2    # z will be 8


# Division

a = 16 / 2   # a will be 8.0 (float division)


# Floor Division

b = 17 // 2  # b will be 8 (integer division)


# Exponentiation

c = 2 ** 3   # c will be 8


# Modulo (Remainder)

d = 17 % 9   # d will be 8

Comparison Operators

Comparison operators are used to compare values and evaluate conditions. They return either True or False based on the comparison. Here are the commonly used comparison operators in Python:

# Equal to
x = 5 == 5     # x will be True

# Not equal to
y = 10 != 5    # y will be True

# Greater than
z = 8 > 3      # z will be True

# Less than
a = 4 < 9      # a will be True


# Greater than or equal to
b = 7 >= 7     # b will be True


# Less than or equal to
c = 6 <= 10    # c will be True

Logical Operators

Logical operators are used to combine conditions and perform logical operations. They return either True or False based on the logical evaluation. Here are the commonly used logical operators in Python:

# AND
x = (5 > 3) and (4 < 6)    # x will be True
# OR
y = (10 < 5) or (3 == 3)   # y will be True
# NOT
z = not (8 >= 9)           # z will be True

Assignment Operators

Assignment operators are used to assign values to variables. They combine the assignment operation (=) with another operation. Here are some examples:

# Addition assignment
x = 5
x += 3     # x will be 8
# Subtraction assignment

y = 10

y -= 2     # y will be 8


# Multiplication assignment

z = 4

z *= 2     # z will be 8


# Division assignment
a = 16
a /= 2     # a will be 8.0

# Modulo assignment
b = 17
b %= 9     # b will be 8

Operator Precedence and Associativity

Operator precedence determines the order in which operators are evaluated in an expression. It's important to understand the precedence rules to ensure the correct order of operations. Parentheses can be used to change the order of evaluation.

Here's a general precedence order (from highest to lowest):

  1. Parentheses: ( )
  2. Exponentiation: **
  3. Multiplication, Division, Floor Division, Modulo: *, /, //, %
  4. Addition and Subtraction: +, -
  5. Comparison Operators: ==, !=, >, <, >=, <=
  6. Logical Operators: and, or, not

Operator associativity determines the order in which operators with the same precedence are evaluated. Most operators in Python have left-to-right associativity, which means they are evaluated from left to right.

However, exponentiation (**) is an exception, as it has right-to-left associativity.

Here's an example that demonstrates operator precedence and associativity:

result = 2 + 3 * 4 ** 2 / 6 - 1
print(result)  # Output: 9.0

The example above evaluates the expression based on the operator precedence and associativity rules. The order of evaluation is as follows:

  1. Exponentiation: 4 ** 2 evaluates to 16.
  2. Multiplication: 3 * 16 evaluates to 48.
  3. Division: 48 / 6 evaluates to 8.0.
  4. Addition: 2 + 8.0 evaluates to 10.0.
  5. Subtraction: 10.0 - 1 evaluates to 9.0.

By understanding operator precedence and associativity, you can ensure that complex expressions are evaluated correctly.

Expressions

Expressions are combinations of values, variables, operators, and function calls that are evaluated to produce a result.

Expressions can be as simple as a single variable or value or more complex with multiple operators and operands.

Here are some examples of expressions:

x = 5 + 3    # Simple arithmetic expression
y = (2 * x + 5) / (x - 2)   # Complex arithmetic expression with parentheses
is_valid = x > 0 and y < 10   # Logical expression using comparison and logical operators

Expressions play a crucial role in performing calculations, making decisions, and controlling the flow of your program.

Understanding and utilizing operators and expressions in Python allows you to perform mathematical calculations, compare values, combine conditions, and assign values efficiently.

Practising and experimenting with different operators and expressions will enhance your programming skills.

In the next part of this article, we will dig deeper into more complex Python syntax and learn how to develop complete Python programs.

If you discover this, publish thrilling, discover extra thrilling posts like this on Learnhub Blog; we write a lot of tech-related topics from Cloud computing to Frontend Dev, Cybersecurity, AI and Blockchain. Take a look at How to Build Offline Web Applications. 

Resources

Top comments (0)