Python - Basic Syntax

Welcome, aspiring programmers! Today, we're diving into the exciting world of Python syntax. As your friendly neighborhood computer science teacher, I'm here to guide you through the basics of Python programming. Don't worry if you've never written a line of code before – we'll start from scratch and build our knowledge step by step. So, grab your favorite beverage, get comfortable, and let's embark on this coding adventure together!

Python - Basic Syntax

Python Syntax: The Building Blocks of Code

Python syntax is like the grammar of the Python language. Just as we need to follow certain rules when writing sentences in English, we need to follow specific rules when writing Python code. The good news? Python's syntax is designed to be clear and readable, making it an excellent language for beginners.

First Python Program

Let's start with the classic "Hello, World!" program. It's a tradition in programming to begin with this simple example:

print("Hello, World!")

When you run this code, you'll see:

Hello, World!

Pretty simple, right? The print() function is used to output text to the screen. We'll be using it a lot in our examples.

Python Identifiers

Identifiers are names given to various program elements like variables, functions, classes, etc. Think of them as labels for different parts of your code. Here are some rules for creating identifiers:

  1. They can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  2. They must start with a letter or underscore, not a digit.
  3. They are case-sensitive (name, Name, and NAME are all different).
  4. They cannot be a reserved word (we'll cover these next).

Examples of valid identifiers:

my_variable = 10
userName123 = "John"
_private_var = True

Python Reserved Words

Reserved words (also called keywords) are words that have special meanings in Python. You can't use these as identifiers. Here's a table of Python's reserved words:

Reserved Words
False class finally is
None continue for lambda
True def from nonlocal
and del global not
as elif if or
assert else import pass
break except in raise
return try while with
yield

Python Lines and Indentation

Unlike many other programming languages, Python uses indentation to define code blocks. This makes the code more readable and clean. Let's look at an example:

if True:
    print("This is indented")
    print("This is also indented")
print("This is not indented")

The indented lines are part of the if block. The non-indented line is outside the block. Consistency in indentation is crucial in Python!

Python Multi-Line Statements

Sometimes, a statement might be too long for a single line. You can split it using the backslash ():

total = 1 + \
        2 + \
        3
print(total)  # Output: 6

You can also use parentheses, square brackets, or curly braces to split lines without the backslash:

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

Quotations in Python

Python allows both single quotes ('') and double quotes ("") for strings. They work the same way:

print('Hello')  # Output: Hello
print("World")  # Output: World

For multi-line strings, you can use triple quotes (''' or """):

multi_line = '''This is a
multi-line
string'''
print(multi_line)

Comments in Python

Comments are notes in your code that Python ignores. They're useful for explaining your code or temporarily disabling parts of it. Single-line comments start with #:

# This is a comment
print("Hello")  # This is also a comment

For multi-line comments, you can use triple quotes:

"""
This is a
multi-line comment
"""

Using Blank Lines in Python Programs

Blank lines can improve readability. Python ignores blank lines, so use them to separate logical sections of your code:

# First section
x = 5
y = 10

# Second section
result = x + y
print(result)

Waiting for the User

To make your program wait for user input, use the input() function:

name = input("Enter your name: ")
print("Hello,", name)

This program will wait for the user to enter their name before continuing.

Multiple Statements on a Single Line

You can put multiple statements on one line using semicolons:

a = 1; b = 2; c = 3
print(a, b, c)  # Output: 1 2 3

However, this is generally discouraged as it can make your code less readable.

Multiple Statement Groups as Suites

A group of statements that go together (like in a function or loop) is called a suite. Here's an example using a function:

def greet(name):
    """This function greets the person passed in as a parameter"""
    print("Hello,", name)
    print("How are you today?")

greet("Alice")

The indented block under the def line is the suite of the function.

Command Line Arguments in Python

You can pass arguments to your Python script from the command line. Here's a simple example:

import sys

print("Arguments:", sys.argv)

If you run this script with python script.py arg1 arg2, it will output:

Arguments: ['script.py', 'arg1', 'arg2']

And there you have it! We've covered the basic syntax of Python. Remember, practice makes perfect, so don't be afraid to experiment with these concepts. coding is like learning a new language – the more you use it, the more natural it becomes. Happy coding, and see you in the next lesson!

Credits: Image by storyset