Python syntax overview

By Martin McBride, 2018-04-05


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

Join the GraphicMaths/PythonInformer Newsletter

Sign up using this form to receive an email when new content is added to the graphpicmaths or pythoninformer websites:

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

Popular tags

2d arrays abstract data type and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes close closure cmyk colour combinations comparison operator context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing integer iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library range recipes rectangle recursion regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slicing sound spirograph sprite square str stream string stroke structural pattern symmetric encryption template tex text tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest