Python Programming
Python is an interpreted, high-level, dynamic language.
Variables and Data Types
Python supports various data types including integers, floats, strings, and booleans.
Boolean
Numericals
String
Strings can be sliced.
Operator precedence
Operator | Description |
---|---|
** | Exponentiation |
~ , + , - | Complement, unary plus, and minus |
* , / , % , // | Multiply; divide, modulo, floor division |
+ , - | Addition and subtraction |
>> , << | Right and left bitwise shift |
& | Bitwise AND |
^ , | | Bitwise XOR and OR |
<= , < , > , >= | Comparison operators |
== , != | Equality operators |
= , %= , /= , //= , -= , += , *= , **= | Assignment operators |
is , is not | Identity operators |
in , not in | Membership operators |
not , or , and | Logical operators |
Control Structures
Python uses indentation to define blocks of code.
Selection
elif
and else
sections are optional.
match-case
syntax can be used for pattern matching.
Repetition
Executing a block of code multiple times.
In for
loop, the looping variable is automatically incremented.
Subprogram (functions)
A reusable block of code that is used to perform a single action. Defined using
the def
keyword, followed by its name and ()
.
Lists
Lists are ordered collections of items. The items can be of any type. Items are indexed sequentially starting from 0.
Tuples
Similar to lists but immutable (cannot be changed after creation). ()
are used
instead of []
.
Commonly used for returning multiple values from functions or when you want to ensure data cannot be modified.
Dictionary
Stores key-value pairs.
There are a handful of built-in functions in Python.
Error Handling
Python uses try-except blocks for error handling.
Common exceptions:
ValueError
: Invalid valueTypeError
: Invalid operation on typesFileNotFoundError
: File doesn’t existIndexError
: List index out of rangeKeyError
: Dictionary key not found
Exceptions can be raised when required.