Python syntax


Martin McBride, 2018-04-05
In section Python language



In this article we will look at the main differences in Python syntax compared to other languages. In this section, by other languages we mainly mean C like languages (C/C++, Java etc), as these are the most commonly used languages.

Comments

Python uses the # character to mark the rest of the line as a comment (similar to // in other languages). It doesn't use support block comments (there is no equivalent to /* ... */).

Statements

  • Python does not require a semicolon at the end of a statement
  • Every statement must be on a separate line
x = a + b
print(x)

Variables

  • Variables are untyped - any variable can hold any type of data
  • Variables do not need to be declared, you create a variable by assigning a value to it
x = 3         # x holds an integer
y = 7.8       # y holds a float
x = 'abc'     # Now x holds a string

Code blocks

  • Like other languages, Python uses nested blocks for if statements, loops and function bodies
  • A block is introduced by a colon
  • All statements in a block must be indented by the same amount
  • The end of a block is indicated by the indentation returning to its previous level
if a > b:      # Colon starts block
      a = b      # This line is part of the if block
      b = 0      # This line is also part of the if block
print(a)       # This line is not part of the if block

If statements

  • Python uses if and else like many other languages
  • You can use elif for extra clauses
  • It is not necessary to put brackets around conditions, and most programmers don't
  • Python has no switch statement - use if statements with elif clauses instead
if a == 1
    # Case 1
elif a == 2
    # Case 2
else
    # Other cases

Conditions

  • Python uses comparison operators such as > or != similar to many other languages
  • Compound conditions use keywords and, or, not (rather than &&, ||, !)
  • A numerical value of 0 tests as false, any other value is true. Similarly a list or string tests as false if empty, true if not empty

While loops

  • Similar to other languages, but with Python block syntax
  • There is no do ... while construct
a = 5
while a > 0:
      print(a)
      a -= 1

For loops

  • for loops always loop over a sequence, such as a list or the characters of a string
  • The range function creates a sequence of numbers, similar to a tradition C style for loop
for i in range(5):   # equivalent to for(i = 0; i < 5; i++)
      print(i)

Defining functions

  • Functions are defined using def keyword
  • Parameters can be given default values
  • There are many more options, see declaring functions
def add(a, b, c=0):       # c is optional, defaults to 0
      return a + b + c

Calling functions

  • Similar to other languages
  • Parameters with default values can be omitted
  • You can use parameter names, either for clarity or to reorder them
  • There are many more options, see calling functions
 add(1, 2)             # c defaults to 0
 add(2, 4, 6)          # c is now 6
 add (a=2, b=4, c=6)   # Naming the parameters

If you found this article useful, you might be interested in the book Functional Programming in Python, or other books, by the same author.

<<Prev

Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020