- Defining a Variable - how to define a variable of a specific datatype
- Defining a Constant - how to define an immutable variable
- Complex Literals - native support for literal complex datatypes (non-primitive types)
Variables and Constants
Change TopicPython Language
TypeScript Variables
Variables
x = 100
Variables
let x: number = 100;
Constants
Python does not have true constants, but conventionally, uppercase names indicate constants.
PI: float = 3.1415 # Convention for constants (not enforced) count: int = 10 # Mutable variable count += 1 # Allowed
- Variables are dynamically typed unless explicitly hinted.
Constants
const PI: number = 3.1415; // Immutable constant
Literals
Python has a few native literals.
my_int = 10 my_binary = 0b1010 my_octal = 0o12 my_hex = 0xA my_float = 10.5 my_sci_not = 2.0e3 my_complex = 3 + 4j my_bool = True my_None = None
For strings, multi-line and raw strings are supported:
my_str = 'hello' my_str_double = "hello" my_multi_line = """hello there""" my_raw = r"New\nLine" -- ignores escape sequences my_formatted = f"Hello {name}"
The complex type literals are as follows:
my_list = [1, 2, 3] my_tuple = (1,2,3) -- note that Tuple types are separate to arrays in python my_single_tuple = (42,) -- special syntax single-element tuple my_dict = {"key": "value", "age": 30} my_set = {1, 2, 3} my_empty_set = set() -- avoid confusion with empty dict my_bytes = b"hello"` my_byte_array = bytearray(b"hello")
Literals
The following primitive literals are covered by Typescript:
let myInt: number = 10; let myBinary: number = 0b1010; let myOctal: number = 0o12; let myHex: number = 0xa; let myFloat: number = 10.5; let mySciNot: number = 2.0e3; let myBool: boolean = true; let myNull: null = null; let myUndefined: undefined = undefined;
String literals:
let myStr: string = "hello"; let myStrDouble: string = "hello"; let myMultiLine: string = `hello there`; // Template literals allow multi-line strings let myRaw: string = String.raw`New\nLine`; // Ignores escape sequences let myFormatted: string = `Hello ${name}`; // String interpolation
Complex literals
let myArray: number[] = [1, 2, 3]; // Standard array let myTuple: [number, number, number] = [1, 2, 3]; // Fixed-size tuple let mySingleTuple: [number] = [42]; // Tuple with one element let myObject: { key: string; age: number } = { key: "value", age: 30 }; // Object type let mySet: Set<number> = new Set([1, 2, 3]); // Set type let myEmptySet: Set<number> = new Set(); // Empty set let myBuffer: ArrayBuffer = new ArrayBuffer(8); // Equivalent to `bytes` let myTypedArray: Uint8Array = new Uint8Array([104, 101, 108, 108, 111]); // Equivalent to `bytearray`