Python Syntax Overview

Jul 15, 2024

Python Syntax Overview

Introduction

  • Overview of Python syntax
  • Python Shell: Represented by >>>, code runs individually
  • Program Code: No angle brackets, runs all at once

Basic Math

  • Standard operations: Addition, multiplication, division
  • Parentheses for order of operations

Strings

  • Concatenation: "hello" + "world"
  • Repeat strings: "hello" * 3 ā†’ hellohellohello
  • Define variable: spam = "hello"
  • Comments: # single line and ''' multi-line '''
  • Print: print("hello", spam)
  • Input: input("Enter your name: ")
  • Formatting: ",".format(variable)
  • Length: len("hello") ā†’ 5
  • Type Conversion: str(5), int(5.0)

Operators

  • Equality: ==, !=
  • Boolean: is, is not, and, or

Conditionals

  • if name == "Alice": print("Hi Alice")
  • if-else:
    if name == "Alice":
        print("Hi Alice")
    else:
        print("Hello stranger")
    
  • elif (else-if):
    if name == "Alice":
        print("Hi Alice")
    elif name == "Bob":
        print("Hi Bob")
    else:
        print("Hello stranger")
    

Loops

While Loops

  • Basic:
    while spam < 5:
        print(spam)
        spam += 1
    
  • Infinite:
    while True:
        if condition:
            break
    

For Loops

  • Basic: for i in range(5): print(i)
  • Range: range(start, stop, step)

Modules

  • Import: import random
  • Import All: from random import *

Functions

  • Define:
    def hello(name):
        print("Hello", name)
    
  • Return Value:
    def get_answer(number):
        return "Yes"
    

Lists

  • Create: spam = ["cat", "bat", "rat"]
  • Access: spam[0] ā†’ cat, spam[-1] ā†’ rat
  • Slices: spam[0:2] ā†’ ['cat', 'bat']
  • Copy: spam_copy = spam[:]
  • Append: spam.append("dog")
  • Sort: spam.sort()

Dictionaries

  • Create:
    spam = {"size": "fat", "color": "gray"}
    
  • Access: spam["size"] ā†’ fat
  • Methods: .keys(), .values(), .items(), get(), setdefault()

Tuples

  • Immutable lists: t = (1, 2, 3)
  • Conversion: list(t), tuple(spam)

Sets

  • Create: set(), {1, 2, 3}
  • Methods: .add(), .update(), .remove(), .discard(), .union(), .intersection(), .difference(), .symmetric_difference()

Comprehensions

  • List: [i-1 for i in a]
  • Set: {s.upper() for s in b}
  • Dictionary: {k: v for k, v in d.items()}

Strings

  • Escape characters: \n, \', \t
  • Raw strings: r"\n"
  • Multi-line: '''text'''
  • Slicing: spam[0:5], spam[:5], spam[5:]
  • Methods: .upper(), .lower(), .startswith(), .endswith(), .join(), .split(), .strip()

Error Handling

  • Try-Except:
    try:
        1/0
    except ZeroDivisionError:
        print("Error")
    
  • Finally:
    try:
        pass
    finally:
        print("Always executed")
    

Lambda Functions

  • Simple: lambda x, y: x + y
  • No name: (lambda x, y: x + y)(5, 3)

Miscellaneous

  • Ternary: print('kid') if age < 18 else print('adult')
  • *args and **kwargs: Allows variable number of arguments
  • Exception raising: raise Exception("Error message")
  • Logging:
    import logging
    logging.basicConfig()
    logging.debug('message')
    
  • Main check:
    if __name__ == "__main__":
        pass
    

Summary

  • Basics of Python syntax in various aspects
  • Mention of classes and objects in another resource

Note: Explore more on advanced topics like classes and objects for a complete understanding of Python.

Additional Resources

  • Check the pinned comment for more insights on Python.

šŸŒŸ Happy Coding! šŸŒŸ

Emoji

  • :snake: For Python (symbolizes the Python language)