Python Basics

I. Comment

In Python, comments start with a #. To add a multiline comment you could insert a # for each line.

Comment can:

  • Provide context
  • Help other people reading the code understand it faster
  • Ignore a line of code and test your program without it
# This is a comment

II. Indentation

Python uses indentation to indicate a block of code. Python will give you an error if you skip the indentation.

number = 10

if number > 2:
  print("Number is greater than two!")

III. Variables

A variable stores a value in Python program. We define a variable using an equals sign.

Variables can be reassigned as many times as you want, in order to change their value.

>>> x = 5
>>> print(x)
5
>>> x = "Hello"
>>> print(x)
Hello

Note: If you try to reference a variable you haven’t assigned, the program will show error.

Rules for variable name

  • Must start with a letter (usually lowercase)
  • After first letter, can use letters/ numbers/ underscores
  • So spaces or special characters
  • Case sensitive (my_var is different from MY_VAR)

IV. Print

print() function displays data on the screen when the program executes. The message to be printed should be surrounded by quotes.

If no arguments are provided, the print() function will output a blank line.

print("Hello World")

V. input()

To get input from the user in Python, we use input function.

The function prompts the user for input, and returns what they enter as a string.

>>> input("Enter your name: ")
Enter your name: Jane
'Jane'

VI. Errors

Python point to the location of error with a ^ character.

  • SyntaxError: something wrong with the way your program is written
  • NameError: detects a variable that is unknown

VII. Import Python Modules

Modules (sometimes called packages or libraries) help group together related sets of tools in Python.

  • Import a Module: import pandas
  • Import a module with an alias: import pandas as pd