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 as sep and end can be used to format the output.

print(*objects, sep=' ', end='\n', flush=False)

Parameters

  1. *objects: One or more objects (string, number, etc.) to be printed. Multiple objects are separated by the sep keyword.

  2. sep: Specifies the separator between multiple objects. Default is a space (' ').

  3. end: Specifies what to print at the end. Default is a newline ('\n').

  4. flush: If True, the output is flushed immediately. Default is False.

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 or False.

      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.

OperatorDescriptionExample
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 31.67
%Modulus (remainder)5 % 32
**Exponentiation5 ** 3125
//Floor Division5 // 31

Comparison Operators

Used to compare values. Returns True or False.

OperatorDescriptionExample
==Equal to5 == 3False
!=Not equal to5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater than or equal to5 >= 3True
<=Less than or equal to5 <= 3False

Logical Operators

Used to perform logical operations.

OperatorDescriptionExample
andLogical ANDTrue and FalseFalse
orLogical ORTrue or FalseTrue
notLogical NOTnot TrueFalse

Bitwise Operators

Operate on binary values.

OperatorDescriptionExample
&AND5 & 31
``OR`537`
^XOR5 ^ 36
~NOT (invert bits)~5-6
<<Left Shift5 << 110
>>Right Shift5 >> 12

Assignment Operators

Used to assign values to variables.

OperatorDescriptionExample
=Assignx = 5
+=Add and assignx += 3x = x + 3
-=Subtract and assignx -= 3x = x - 3
*=Multiply and assignx *= 3x = x * 3
/=Divide and assignx /= 3x = x / 3
**=Exponentiate and assignx **= 3

Membership Operators

Check for membership in a sequence (e.g., list, tuple).

OperatorDescriptionExample
inPresent in'a' in 'apple'True
not inNot present in'b' in 'apple'False

Identity Operators

Check if two variables reference the same object.

OperatorDescriptionExample
isIdentical objectsx is y
is notNot identicalx 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

  1. Must start with a letter (A-Z, a-z) or an underscore (_).

  2. Cannot start with a digit.

  3. Can contain letters, digits, and underscores (e.g., my_var1).

  4. Cannot use reserved keywords (e.g., class, if, for).

  5. Avoid using special characters like @, $, %.

  6. Python is case-sensitive (x and X 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 or False (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:
  1. Using Multiple Single-Line Comments:

     # This is a multi-line comment
     # written over multiple lines
     a = 5
    
  2. 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 like int(), float(), or bool().

      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 strings

  • You 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)