Python Syntax

Python's simplicity makes it an excellent choice for both beginners and experienced developers. This concise guide aims to help beginners understand Python syntax and how to work with its basic features.

Introduction

Python is an intuitive and user-friendly programming language. A simple example to check voting eligibility showcases Python's straightforward syntax:

# Simple Python Program to see if a user is eligible to vote or not.

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

print("Enter your age:")
age = int(input())

if age >= 18:
    print(name, 'is eligible to vote.')
else:
    print(name, 'is not eligible to vote.')

This program takes the user's name and age as input, evaluates the condition for voting eligibility, and displays the result.

Command-Line and Python Scripts

Python is versatile and can be used interactively in the command line or to run pre-written scripts. To try Python directly in the command line, you can simply type:

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

For running Python scripts, save your code in a file (e.g., `myfile.py`) and execute it in the terminal using the following commands:

python myfile.py

or:

python3 myfile.py

Python in Emacs Org Mode

Using Python within Emacs's Org mode is simple and interactive. You can execute Python code blocks directly in an Org document. For example:

#+begin_src python :results output code

print("Hello, World!")

#+end_src

Python in Jupyter Notebook

Jupyter Notebook provides an interactive web-based environment for running Python code, making it ideal for data analysis and visualization. You can try Jupyter Notebooks directly on their official website.

Line Structure in Python

Python processes code line by line, but it also allows multi-line statements using a backslash (`\`). For instance:

print("Hello
World")

The above will cause an error. However, the following will execute correctly:

print("Hello \
World")

Indentation and Code Blocks

Python enforces indentation for defining blocks of code, making the code more readable. For example:

if 3 < 1:
    print("I will not be printed out")
    print("I will not be printed out either")
print("I will be printed out")
I will be printed out

Multiple Statements in One Line

If readability is not compromised, you can place multiple statements on a single line using a semicolon (`;`):

print("Hello ..."); print("... World")
Hello ...
... World

Similarly:

a = 7; print(a)
7

Quotations in Python

Python supports both single and double quotes for strings. You can mix and match them as needed:

print('We are at lecture 1')
print("We are at lecture 2")
print("We are at 'lecture 2'")
We are at lecture 1
We are at lecture 2
We are at 'lecture 2'

Escape Characters

Special characters can be included in strings using escape sequences. For instance, to print That's Bob's book, you can use:

print("That\'s Bob\'s book")
That's Bob's book

Here are some commonly used escape characters:

Escape Character Prints As
`\'` Single Quote
`\"` Double Quote
`\t` Tab
`\n` Line Break
`\\` Backslash

Another example combining multiple escape characters:

print("Hello there!\n\t\\How are you?\\\nI\'m doing fine.")
Hello there!
	\How are you?\
I'm doing fine.

String Formatters

Python allows dynamic string formatting. Using the `%` operator, you can embed variables within a string:

x = 50; y = 2022
print('It rained %s days last year, 2 days more compared to %s.' % (x, y))
It rained 50 days last year, 2 days more compared to 2022.

Alternatively, Python's f-strings provide a cleaner syntax:

x = 50; y = 2021
print(f'It rained {x} days last year, 3 days less compared to {y}.')
It rained 50 days last year, 3 days less compared to 2021.

Math Operators

Python supports a wide range of math operators for calculations:

Operator Operation
`**` Exponent
`%` Modulus/Remainder
`//` Integer Division
`/` Division
`*` Multiplication
`-` Subtraction
`+` Addition

For example:

print(20 % 8)  # Outputs 4 (remainder of 20 divided by 8)
print(3 ** 2)  # Outputs 9 (3 squared)

Exercise

  1. What should these two expressions evaluate to?

    'spam' + 'spamspam'
    'spam' * 3
  2. What causes the error in this expression? How can it be corrected?

    'I have eaten ' + 99 + ' burritos.'