• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Python | Working with Variables
  1. Variables
  2. Comment
  3. Numbers
  4. Strings
  5. Dates and Times

  1. Variables
    Variables names:
    • Can contain only letters ([a-zA-Z]), numbers ([0-9]), and/or underscores (_).
    • Must start with a letter or underscore.
    • Can't start with a number.
    • Are case-sensitive.
    • Can't use Python reserved keywords (or built-in function names).

    As best practices, you should use descriptive and lowercase for variable names (e.g., value) and use all uppercase for constants (e.g., VALUE). You should use underscores to join multi-word variable names (e.g., max_value, MAX_VALUE).

    Define a variable:
    x = "Hello"
    print(x) # Output: Hello
    
    y = 1
    print(y) # Output: 1
    
    z = False
    print(z) # Output: False
    Multiple assignment: Assign multiple variables with different values in one instruction:
    x, y , z = 'hello', 'python', 3
    print(type(x)) # Output: <class 'str'>
    print(type(y)) # Output: <class 'str'>
    print(type(z)) # Output: <class 'int'>
    Multiple assignment: Assign same value to multiple variables:
    x = y = z = 1
    Swapping variables:
    x, y = 1, 2
    x, y = y, x # x will have the value 2 and y will have the value 1
  2. Comments
    To comment a line or part of a line, use the hash character (#).
    # this is a single-line comment
    x = 1 # this is an inline comment
    For multi-line comments, use triple quotes (''', """):
    """
    this is
    a multi-line
    comment using triple double quotes
    
    """
    
    '''
    this is
    another multi-line
    comment using triple single quotes
    '''
  3. Numbers
    Integers: -1, 0, 1, 2, 1_000_000, ...
    Floats, 1.0, 2.0, 1.2e-3, ...
    Operators: Addition (+), Subtraction (-), Multiplication (*), Division (/), Modulo (%), Exponentiation (**)

    Example - Modulo operator (Remainder operator):
    i = 5 % 2
    print(i) # Output: 1
    Using underscores for readability:
    i = 1_000_000
    print(i) # Output: 1000000
    Complex numbers:
    i = 1 + 2j
    print(i) # Output: (1+2j)
  4. Strings
    • Valid Strings:
      a = "This is a valid string" # double quotes
      c = 'This is a valid string' # single quotes
      b = "This is a 'valid' string" # mixed quotes
      d = 'This is a "valid" string' # escaped quotes
    • Multi-line Strings:
      a = """This is
      a valid
      multi-line string"""
    • Changing string case:

      The title() function changes each word of a string in title case (begins with a capital letter):
      print('hello python'.title()) # Output: Hello Python
      The upper() function changes a string to all uppercase:
      print('hello python'.upper()) # Output: HELLO PYTHON
      The lower() function changes a string to all lowercase:
      print('HELLO PYTHON'.lower()) # Output: hello python
    • Formatted Strings (f-strings):

      To use a variable, expression, or a function inside a string, place the letter f before opening quotation mark.
      Inside the string put any variable or function you want to use and surround it with braces.
      x='hello'
      y='python'
      z=f'message: {x} {y.title()}: {2.53 * 2.98:.1f}'
      w=f"message: {x} {y.title()}: {2.53 * 2.98:.1f}"
      print(z) # Output: message: hello Python: 7.5
      print(w) # Output: message: hello Python: 7.5
      You can also use the format() method:
      print("hello {}: {}".format("python", 7.5)) # Output: hello python: 7.5
    • Adding whitespace to strings with tabs (\t) or newlines (\n):

      print("hello\n\n\t\tpython")
      Output:
      hello
      
                      python
    • Removing whitespace:

      x = ' hello python '
      Use strip() function to remove whitespace from the beginning (left) and the end (right) of a string:
      print(f'"{x.strip()}"') # Output: "hello python"
      Use lstrip() function to remove whitespace from the beginning (left) of a string:
      print(f'"{x.lstrip()}"') # Output: "hello python "
      Use rstrip() function to remove whitespace from the end (right) of a string:
      print(f'"{x.rstrip()}"') # Output: " hello python"
    • Removing prefixes and suffixes:

      x = "hello.py"
      print(f'"{x.removeprefix("hello")}"') # Output: ".py"
      print(f'"{x.removesuffix(".py")}"') # Output: "hello"
    • String splitting:

      • Split by whitespace:
        words = 'hello python 3'.split()
        print(f'Number of words: {len(words)} | {words}') # Output: Number of words: 3 | ['hello', 'python', '3']
        for word in words:
          print(f'word: {word} | length: {len(word)}')
        Output:
        Number of words: 3 | ['hello', 'python', '3']
        word: hello | length: 5
        word: python | length: 6
        word: 3 | length: 1
      • Split by specific delimeter:
        words = 'hello,python,3'.split(',')
        print(f'Number of words: {len(words)} | {words}') # Output: Number of words: 3 | ['hello', 'python', '3']
        for word in words:
          print(f'word: {word} | length: {len(word)}')
        Output:
        Number of words: 3 | ['hello', 'python', '3']
        word: hello | length: 5
        word: python | length: 6
        word: 3 | length: 1
      • Split lines:
        lines = 'hello\npython\n3'.splitlines()
        print(f'Number of lines: {len(lines)} | {lines}') # Output: Number of lines: 3 | ['hello', 'python', '3']
        for line in lines:
          print(f'line: {line}')
        Output:
        Number of lines: 3 | ['hello', 'python', '3']
        line: hello
        line: python
        line: 3
    • Type conversion:

      x = int('1')
      print(type(x)) # <class 'int'>
      print(x) # Output: 1
      
      y = float('1.2')
      print(type(y)) # <class 'float'>
      print(float('1.2')) # Output: 1.2
      Handling conversion errors:
      try:
        print(int('a'))
      except ValueError: # ValueError: invalid literal for int() with base 10: 'a'
        print("invalid number format")
      Convert numbers to string:
      x = str(1.2)
      print(type(x)) # <class 'str'>
      print(x) # Output: 1.2
    • Other methods:

      # join
      print(' '.join(['hello', 'python', '3'])) # Output: hello python 3
      
      # in (membership)
      print('python' in 'hello python 3') # Output: True
      
      # startswith
      print('hello python 3'.startswith('hello')) # Output: True
      
      # endswith
      print('hello python 3'.endswith('3')) # Output: True
      
      # python
      print('hello python 3'.find('python')) # Output: 6 (index position)
      
      # count
      print('hello python 3'.count('o')) # Output: 2
      
      # replace
      print('hello python 3'.replace('3', '3.12.3')) # Output: hello python 3.12.3
  5. Dates and Times
    Date and time format codes:
    • %Y: Year, in four-digit format (2023, ...)
    • %y: Year, in two-digit format (23, ...)
    • %m: Month number (01 - 12)
    • %B: Month name (March)
    • %b: Month name abbreviated (Mar)
    • %d: Day of the month (01 - 31)
    • %A: Weekday name (Friday)
    • %a: Weekday name abbreviated (Fri)
    • %H: Hour, in 24-hour format (00 - 23)
    • %I: Hour, in 12-hour format (00 - 12)
    • %M: Minutes (00 - 59)
    • %S: Seconds (00 - 59)
    • %f: Microseconds (090579)
    • %p: AM|PM
    • %z: UTC offset (+0000)
    • %Z: Timezone name (EST)

    Parsing a date string using a specific format:
    from datetime import datetime, date, timedelta, timezone
    • Current date and time:
      print(f'{datetime.now()}') # Output: 2023-03-29 06:19:17.217238
      print(f'{date.today()}') # Output: 2023-03-29
      print(f'{datetime.now().time()}') # Output: 06:19:17.217294

    • Specific date/time:
      print(f'{date(2023, 3, 29)}') # Output: 2023-03-29
      print(f'{datetime(2023, 3, 29, 6, 19, 17)}') # Output: 2023-03-29 06:19:17

    • Parsing date strings:
      print(datetime.strptime('05/08/2023 01-16-26 PM', '%d/%m/%Y %I-%M-%S %p')) # Output: 2023-08-05 13:16:26

    • Dormating dates (timezone):
      print(datetime.now(timezone.utc).strftime('%d/%m/%Y %I-%M-%S %p %z %Z')) # Output: 29/05/2023 03-38-45 PM +0000 UTC
      print(datetime.now(timezone(timedelta(hours=-5))).strftime('%d/%m/%Y %I-%M-%S %p %z %Z')) # Output: 29/05/2023 10-38-45 AM -0500 UTC-05:00
      print(f"{datetime.now().year} - {datetime.now().month} - {datetime.now().day} - {datetime.now().hour} - {datetime.now().minute}") # Output: 2023 - 5 - 29 - 11 - 46

    • Date arithmetic:
      print(date.today()) # Output: 2023-05-29
      print(date.today() - timedelta(days=1)) # Output: 2023-05-28
      print(date.today() - timedelta(weeks=1)) # Output: 2023-05-22
      print(date(2023, 3, 29) - date(2000, 3, 29)) # Output: 8400 days, 0:00:00
      print(date(2023, 3, 29) < date(2000, 3, 29)) # Output: False
      print(min([date(2023, 3, 29), date(2000, 3, 29)])) # Output: 2000-03-29
      print(max([date(2023, 3, 29), date(2000, 3, 29)])) # Output: 2023-03-29
© 2025  mtitek