Python Syntax

python-logo
This page summarises the syntax of the Python language. When using Python always remember two key rules:

  • Rule #1: Python is white-space dependent; code blocks are indented using spaces.
  • Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.
Input / OutputSelection (IF Statements)Iteration (Loops)ListsSubroutinesFile HandlingInput Validation

Annotations


Variables & Assignment Operator

Input

Output

Casting

String Manipulation

Random Library

Arithmetic Operators

Rounding a Number

IF Statements / Selection


Warning: Use the 4 spaces rule!!! (Indentation)

Comparison Operators


The main comparison operators are:

Comparison Operator Meaning Example
== is equal to 4==4
!= is different from 4!=7
< is lower than 3<5
> is greater than 9>2
<= is lower or equal to 3<=5
5<=5
>= is greater or equal to 9>=2
5>=5

Comparison operators are used to check if a condition is true or false.

Boolean operators such as AND, OR and NOT can also be used to check multiple conditions at the same time.

e.g.

Loops / Iteration


Warning: Use the 4 spaces rule!!! (Indentation)

Lists

Procedures


Warning: Use the 4 spaces rule!!! (Indentation)

Functions


Warning: Use the 4 spaces rule!!! (Indentation)

File Handling – (Over)Writing a text file

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

File Handling – Appending data to a text file

File Handling – Reading a text file line by line

File Handling – Reading a CSV file line by line


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a divider symbol such as a comma “,”, a semi-colon “;” or a pipe “|”.

In this case when reading a line of the text file you can use the split() method to then access each field one by one.

File Handling – Reading a text file using a list

Input Validation: Presence Check

Input Validation: Type Check – Integer?

Input Validation: Range Check

Input Validation: Lookup Check

Input Validation: Character Check

Input Validation: Length Check


Try Again! Using a While Loop:

You can investigate more advance approaches to implement validation subroutines on this blog post.

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 10

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!