Python Syntax Basics

Overview

This lesson introduces you to the basics of Python syntax. You’ll learn about Python’s simplicity and readability, and by the end, you’ll understand the fundamental aspects of writing Python code, including variables, data types, comments, and basic operations.

Introduction

Python is designed to be easy to read and write, with a clean and straightforward syntax. It emphasizes readability, which reduces the cost of program maintenance and development. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.

Variables and Data Types

  • Variables: In Python, variables are containers for storing data values. Python has no command for declaring a variable; you create one the moment you first assign a value to it. Example: x = 5.
  • Data Types: Python has various data types including int (integer), float (floating point number), str (string), bool (Boolean), list, tuple, set, and dict (dictionary).

Comments

  • Comments: Comments start with a #, and Python will ignore them. They are used to explain Python code to make it more readable. Example: # This is a comment.

Basic Operations

  • Arithmetic Operators: Python can perform arithmetic operations like addition +, subtraction -, multiplication *, division /, modulus %, exponentiation **, and floor division //.
  • Assignment Operators: Used to assign values to variables, e.g., =, +=, -=, etc.
  • Comparison Operators: Used to compare two values, e.g., ==, !=, >, <, >=, <=.
  • Logical Operators: Used to combine conditional statements, e.g., and, or, not.

Indentation

  • Indentation: Python uses indentation to indicate a block of code. The amount of indentation is up to you, but it must be consistent throughout that block. Typically, four whitespaces are used for indentation.

Simple Program Example

Here’s a simple program that prints “Hello, World!” to the screen:

print("Hello, World!")

And here’s an example using variables and basic operations:

x = 5
y = 10
print(x + y)  # This will print 15