Python basics

Carlos Pineda
2 min readMay 16, 2020

--

I recently decided to learn Python to add to my stack (JS, Ruby) given the popularity of the languages across many industries. I’m writing this in hope that it can help others who are learning python with some coding background (I know JS/Ruby).

# Stringssentence = 'Hi i am a string'
type(sentence) # return <class 'str'>

Strings are pretty straight forward, just like any other language, you define them with single quotes (‘ ’) or double quotes (“ ”), unlike JS back ticks (` `) won’t work in python.

# Boolean  boolean = True # type boolean
type(boolean) # return <class 'bool'>
bool(100) # returns True
bool(0) # returns False

Booleans are also straight forward: True/False. For numbers, 0 is considered ‘falsy’ while any other number is ‘truthy’.

# Numericnum = 1 # type int
type(num) # return <class 'int'>
num = 2.1 # type float
type(num) # return <class 'float'>

Numbers can either be save as integers (whole numbers) or floats (decimals).

# Complexnum = 1j # type complex
type(num) # <class 'complex'>

There’s also a “complex” type which is a combination of numbers and letters.

# Empty Variables (None type)  var = None
type(var) # return <class 'NoneType'>

“none” type which allows you to declare empty variables without having to define them.

There are three collection type of data structures: lists, tuples, sets.

  • Lists: defined with square brackets [] these are arrays and built as as such
  • Tuple: defines with braces () similar to lists but they are immutable in nature
  • Set: defined with curly braces {} similar to lists but they only keep unique values

Note: you can combine set and list methods to obtain the unique values of a list.

# List 

this_list = [1,2,3]
type(this_list) # return <class 'list'>
# Tuple this_tuple = (1,2,3)
type(this_tuple) # return <class 'tuple'>
# Set this_set = {1,2,3}
type(this_set) # return <class 'set'>
# Creating one collection from another collection = [4,1,2,3,3]
tuple(collection) # return (4,1,2,3,3)
set(collection) # return {1,2,3,4}
# Obtain sorted unique list list(set(collection)) # return [1,2,3,4] (uniques values# slice numbers of elements (NOT INDEX)

collection[:2] # return [1,2]

Dictionaries are just like JS objects and Ruby hashes with key/value pairs. They can be created hard coded or with keys from a list.

# Dictionary   dictionary = {"name": "John", "age": 30}
type(dictionary) # return <class 'dict'>
# setup dict from array with keys for dict this_list = [4, 1, 3, 3] dict.fromkeys(this_list) # returns {4: None, 1: None, 3: None}
dict.fromkeys(this_list,0) # returns {4: 0, 1: 0, 3: 0}

--

--