01 - Python Fundamentals
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability.
It was created by Guido van Rossum and released in 1991.
Python is widely used for a variety of applications, including web development, data analysis, artificial intelligence, machine learning, scripting, automation, and DevOps.
In the context of DevOps, Python is a powerful tool for:
Automating repetitive tasks.
Managing configuration files and infrastructure.
Writing scripts for CI/CD pipelines.
Interacting with cloud providers using SDKs.
Monitoring and logging systems.
Print Function
The
print()
is a built-in function in Python which is used to display information to the console or standard output.The backslash \ tells python that the next character has a special meaning (eg. \n)
In
print()
, keyword arguments such assep
andend
can be used to format the output.
print(*objects, sep=' ', end='\n', flush=False)
Parameters
*objects
: One or more objects (string, number, etc.) to be printed. Multiple objects are separated by thesep
keyword.sep
: Specifies the separator between multiple objects. Default is a space (' '
).end
: Specifies what to print at the end. Default is a newline ('\n'
).flush
: IfTrue
, the output is flushed immediately. Default isFalse
.
Example
print("Welcome to DevOps!", end=" ")
print("Python", "is", "fun!", sep="-", end="❤️\n")
# Output: Welcome to DevOps! Python-is-fun! ❤️
Literals
Literals in Python are fixed values assigned to variables or constants. They represent data directly in the code without requiring computation.
Python supports several types of literals, including numeric, string, and boolean.
Numeric Literals
Numeric literals represent numbers. They can be:
Integer: Whole numbers.
Floating-point: Decimal numbers.
Complex: Numbers with a real and imaginary part.
a = 10 # Integer
b = 3.14 # Floating-point
c = 1 + 2j # Complex
0o123 # Octal
0x123 # Hexadecimal
String Literals
String literals represent text data or sequence of characters.
They are enclosed in single (
'
), double ("
), triple single ('''
), or triple double ("""
) quotes."Hello!" # Double quotes 'Hello!' # Single quotes '''This is a multi-line string''' # Tripple quotes 'Hi "hi"' # Use quotes within strings 'Hi \'hi\'' # Escape quotes
Boolean Literals
Boolean literals represent
True
orFalse
.False # False True # True 0 # Numeric False 1 # Numeric True
Special Literal
Python has a special literal:
None
. It represents the absence of a value or a null value.data = None
Operators
Operators in Python are special symbols or keywords that perform operations on variables or values.
Python has eight types of operators.
Arithmetic Operators
Used for mathematical calculations.
Operator | Description | Example |
+ | Addition | 5 + 3 → 8 |
- | Subtraction | 5 - 3 → 2 |
* | Multiplication | 5 * 3 → 15 |
/ | Division | 5 / 3 → 1.67 |
% | Modulus (remainder) | 5 % 3 → 2 |
** | Exponentiation | 5 ** 3 → 125 |
// | Floor Division | 5 // 3 → 1 |
Comparison Operators
Used to compare values. Returns True
or False
.
Operator | Description | Example |
== | Equal to | 5 == 3 → False |
!= | Not equal to | 5 != 3 → True |
> | Greater than | 5 > 3 → True |
< | Less than | 5 < 3 → False |
>= | Greater than or equal to | 5 >= 3 → True |
<= | Less than or equal to | 5 <= 3 → False |
Logical Operators
Used to perform logical operations.
Operator | Description | Example |
and | Logical AND | True and False → False |
or | Logical OR | True or False → True |
not | Logical NOT | not True → False |
Bitwise Operators
Operate on binary values.
Operator | Description | Example | ||
& | AND | 5 & 3 → 1 | ||
` | ` | OR | `5 | 3→ 7` |
^ | XOR | 5 ^ 3 → 6 | ||
~ | NOT (invert bits) | ~5 → -6 | ||
<< | Left Shift | 5 << 1 → 10 | ||
>> | Right Shift | 5 >> 1 → 2 |
Assignment Operators
Used to assign values to variables.
Operator | Description | Example |
= | Assign | x = 5 |
+= | Add and assign | x += 3 → x = x + 3 |
-= | Subtract and assign | x -= 3 → x = x - 3 |
*= | Multiply and assign | x *= 3 → x = x * 3 |
/= | Divide and assign | x /= 3 → x = x / 3 |
**= | Exponentiate and assign | x **= 3 |
Membership Operators
Check for membership in a sequence (e.g., list, tuple).
Operator | Description | Example |
in | Present in | 'a' in 'apple' → True |
not in | Not present in | 'b' in 'apple' → False |
Identity Operators
Check if two variables reference the same object.
Operator | Description | Example |
is | Identical objects | x is y |
is not | Not identical | x is not y |
Special Operators
Ternary Operator: Conditional assignment.
result = "Yes" if 5 > 3 else "No" # Output: "Yes"
Priority of Operators
+ - (unary operator) # highest priority
**
* / // %
+ - (binary operator) # lowest priority
Variables in Python
Variables in Python are used to store data values.
A variable is a name that refers to a memory location where data is stored.
In Python, variables are dynamically typed, meaning you don't need to declare their type explicitly - it is inferred from the assigned value and also the variables can redeclared.
Rules for Naming Variables
Must start with a letter (A-Z, a-z) or an underscore (
_
).Cannot start with a digit.
Can contain letters, digits, and underscores (e.g.,
my_var1
).Cannot use reserved keywords (e.g.,
class
,if
,for
).Avoid using special characters like
@
,$
,%
.Python is case-sensitive (
x
andX
are different).
Types of Variables
Variables in Python can hold data of different types:
Numeric: Integer (
int
), Float (float
), Complex (complex
).String: Text (
str
).Boolean:
True
orFalse
(bool
).List: Ordered, mutable collection (
list
).Tuple: Ordered, immutable collection (
tuple
).Dictionary: Key-value pair collection (
dict
).Set: Unordered collection of unique elements (
set
).NoneType: Represents absence of a value (
None
).
Comments in Python
- Comments in Python are ignored by the Python interpreter, making them useful for documentation without affecting the execution of the program.
Single-Line Comments
Single-line comments start with a hash (
#
) symbol. Everything after the#
on that line is treated as a comment.# This is a single-line comment x = 10 # Assigning 10 to variable x
Multi-Line Comments
- Python doesn’t have a specific syntax for multi-line comments like other languages (e.g.,
/* ... */
in C). However, you can achieve multi-line comments in two ways:
Using Multiple Single-Line Comments:
# This is a multi-line comment # written over multiple lines a = 5
Using Docstrings: Docstrings (triple quotes:
'''
or"""
) can act as multi-line comments when they are not used as a docstring for a function or class. (not a standard approach for comments)""" This is a multi-line comment. It spans multiple lines. """ y = 20
Input Function
The
input()
function in Python is used to take user input from the console during program execution.It allows users to provide data dynamically when the program runs.
The input provided by the user is always returned as a string.
Syntax
input(prompt)
name = input("Enter your name: ")
print("Hello, " + name + "!")
Type Casting
Since
input()
always returns a string, you often need to convert the input to the desired type using type conversion / type casting functions likeint()
,float()
, orbool()
.age = int(input("Enter your age: ")) print(f"You are {age} years old.")
Handling Multiple Inputs
You can use the
split()
method to take multiple inputs in one line.x, y = input("Enter two numbers separated by a space: ").split() x = int(x) y = int(y) print(f"The sum is: {x + y}")
String Operations
You can use
+
in order to concatenate two stringsYou can use * in order to repeat a string a several amount of times.
With the
str()
function, you can type-cast a number into a string.print("Hello" + " " + "there!") # "Hello there!" print("ha" * 10) # "hahahahahahahahahaha" print(str(22)) # 22 (string)