Skip to content

Python



Basics

  • Code is just a series of instructions for a computer to follow one after another. Programs can have a lot of instructions.
  • Code runs in order, starting at the top of the program.
  • print() function to print on console.
  • Each print() instruction prints on a new line.
  • "Syntax" is jargon for "valid code that the computer can understand".
  • Syntax: The rules for how expressions and statements should be structured in a language.
  • An expression produces a value. You can use it wherever a value is needed.
  • Examples:
    • Python: 2 + 3, "hi".upper(), len([1,2,3]), x if x>0 else 0
    • JavaScript: a * b, user?.name, [1,2].map(f)
  • A statement performs an action. It doesn’t itself produce a value you can use.
    • Examples:
    • Python: if, for, while, def, class, return, import, pass
    • JavaScript: if (...) {}, for (...) {}, function f(){}, return;, let x = 1;
  • Notes:
    • Many languages allow “expression statements,” where a standalone expression is used as a statement (e.g., a function call print("hi")).
    • In Python, assignment like x = 3 is a statement, not an expression. In JavaScript, x = 3 is an expression that can be used inside others.
    • Expressions can be nested; statements control structure and scope.
  • Variables are how we store data as our program runs.
  • Comments don't do... anything. They are ignored by the Python interpreter. That said, they're good for what the name implies: adding comments to your code in plain English.
  • A single # makes the rest of the line a comment
  • You can use triple quotes to start and end multi-line comments as well
  • Variable names can not have spaces, they're continuous strings of characters.
  • The creator of the Python language himself, Guido van Rossum, implores us to use snake_case for variable names. What is snake case? It's just a style for writing variable names.
  • Snake Case: All words are lowercase and separated by underscores --> num_new_users --> Python, Ruby, Rust
  • Camel Case: Capitalize the first letter of each word except the first one --> numNewUsers --> JavaScript, Java
  • Pascal Case: Capitalize the first letter of each word --> NumNewUsers --> C#, C++

Functions