Variables

You can name a variable anything as long as it obeys the following rules:

  1. It can be only one word.
>>> # this wont work
>>> my variable = 'Hello'

>>> # good
>>> var = 'Hello'
  1. It can use only letters (A-z), numbers(0-9), and the underscore (_) character.
>>> # this wont work
>>> %$@variable = 'Hello'

>>> # good
>>> my_var = 'Hello'

>>> # good
>>> my_var_2 = 'Hello'
  1. It can’t begin with a number.
>>> # this wont work
>>> 23_var = 'hello'
  1. Do not use keywords or built-in function as the variable name
>>> # this wont work
>>> if = 'hello'
>>> # this is bad
>>> print = 'world'

Data Types

Data Type Examples
Bool True, False
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Complex numbers 2+1j, 3-5j
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
Use the built-in function type() to verify the datatype of the value assigned to a variable.

Math Operators

From Highest to Lowest precedence:

Operators Operation Example
** Exponent 2 ** 3 = 8
% Modulus/Remainder 22 % 8 = 6
// Floor(Integer) division 22 // 8 = 2
/ Float(True) Division 22 / 8 = 2.75
* Multiplication 3 * 3 = 9
- Subtraction 5 - 2 = 3
+ Addition 2 + 2 = 4
>>, << shifting 16 >> 2
&,^, | bitwise-logical operator 1^0
>,>=,== Comparison operator 2!=3
not, and, or Logical operator (4 < 5) and (5 < 6)
=,+=,*= assignment symbol a +=1

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
You can use parenthesis to properly specify the order of operations in complex expressions.

Examples of expressions:

>>> 2 + 3 * 6
# 20

>>> (2 + 3) * 6
# 30

>>> 2 ** 8
#256

>>> 10 / 2
#5.0

>>> -11 / 2
#-5.5

>>> 23 // 7
# 3

>>> -5.0 // 2
# -3.0

>>> 23 % 7
# 2

>>> (5 - 1) * ((7 + 1) / (3 - 1))
# 16.0

Augmented Assignment Operators

Operator Equivalent
var += 1 var = var + 1
var -= 1 var = var - 1
var *= 1 var = var * 1
var /= 1 var = var / 1
var %= 1 var = var % 1
var **= 2 var = var**2

Examples:

>>> greeting = 'Hello'
>>> greeting += ' world!'
>>> greeting
# 'Hello world!'

>>> number = 1
>>> number += 1
>>> number
# 2

Multiple assignment

my_string = 'characters' my_Boolean = True # True/False my_integer = 5 my_floating_point = 26.2 my_complex = 2+1j # Note that 1 can not be omitted # The above code is equivalent to my_string, my_Boolean, my_integer, my_floating_point, my_complex = 'characters', True, 5, 26.2, 2+1j

String concatenation and Replication

String concatenation:

>>> 'Alice' + 'Bob'
# 'AliceBob'

String Replication:

>>> 'Alice' * 5
# 'AliceAliceAliceAliceAlice'

Comments

Inline comment:

# This is a comment

Multiline comment:

# This is a
# multiline comment

Code with a comment:

a = 1  # initialization

Function docstring or multiline comments can also be used:

"""
This is a function docstring
You can also use it as multiline string
"""

The print() Function

The print() function writes the value of the argument(s) it is given. It handles multiple arguments, floating point-quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely:

>>> print('Hello world!')
# Hello world!

>>> a = 1
>>> print('Hello world!', a)
# Hello world! 1

>>> print('Hello,\
 World') # It is possible for statements to span more than one line using `\`
# Hello, World

The escape sequence

>>> print("Welcome\nto\nthe course") #Welcome #to #the course

The end keyword

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

print("Welcome", end='-')
print("to the course")
...
# Welcome-to the course

The sep keyword

The keyword sep specify how to separate the objects, if there is more than one, the default value is a white space:

print('cats', 'dogs', 'mice', sep=',')
# cats,dogs,mice

The input() Function

This function takes the input from the user and converts it into a string:

>>> print('What is your name?')   # ask for their name
>>> my_name = input()
>>> print('Hi' + my_name)
# What is your name?
# Martha
# Hi, Martha

input() can also set a default message without using print():

>>> my_name = input('What is your name? ')  # default message
>>> print('Hi' + my_name)
# What is your name? Martha
# Hi, Martha

The len() Function

Evaluates to the integer value of the number of characters in a string, list, dictionary, etc.:

>>> len('hello')
# 5

The bool(), int(), float(), complex() and str() Functions

These functions allow you to change the type of variable. For example, you can transform from an integer or float to a string:

>>> str(29)
# '29'

>>> str(-3.14)
# '-3.14'

Or from a string to an integer or float:

>>> int('11')
# 11

>>> float('3.14')
# 3.14

Keywords

  • algorithm (演算法): It contains well-defined, unambiguous steps and must produce a result in a finite time.
  • pseudocode (虛擬碼): A simple way to describe the steps of an algorithm in plain language that looks like code.
  • programming (程式設計): The process of writing instructions (code) that a computer follows to perform tasks.
  • programming language (程式語言): A set of rules and syntax used to write code that computers can understand.
  • interpreted language (直譯式語言): A programming language where the code is executed directly, line-by-line, without first being compiled.
  • interpreter (直譯器): A tool that reads and executes code one line at a time.
  • statement (敘述): A single line of code that tells the computer to perform an action.
  • function (函數): A reusable block of code that performs a specific task when you call it.
  • arguments (參數): The values or information you pass into a function to help it work.
  • constants (常數): Values that, once set, should not change while the program is running.
  • method (方法): A function that belongs to an object, used to perform actions with that object.
  • comment (註解): Notes in the code meant for humans to read; these are ignored by the computer.
  • expression (運算式): A combination of values, variables, and operators that computes a new value.
  • floor division (向下取整除法): A division operation using // that returns the largest whole number less than or equal to the result.
  • variable (變數): A name that holds a value which can change as the program runs.
  • assignment statement (賦值敘述): A line of code that assigns a value to a variable using the = sign.
  • keywords (關鍵字): Reserved words in Python that have special meanings and cannot be used as names for your variables or functions.
  • type (資料型別): The category of data stored in a variable, such as numbers (int, float) or text (str).
  • debugging (除錯): The process of finding and fixing errors in your code.
  • syntax error (語法錯誤): An error caused by code that doesn't follow the proper rules or grammar of Python.
  • semantic error (語意錯誤): An error where the code runs without crashing, but doesn't do what you intended because of a logical mistake.
  • runtime error (執行階段錯誤): An error that occurs while the program is running, often stopping the program unexpectedly.