Python basics

Scott
8 min readMar 31, 2020

--

Python is dynamically typed so you don’t need to define the types of variables and constants.

Here is the authoritative style guide.

Python recognizes strings by quotes. ASCI characters have to be in quotes.

Print takes n number of arguments. Quotes (aka inverted comma in India) are used for printing string literals.

print(n, n, n)

Every keyword is case sensitive.

System key words are in small cases.

Users can create capitalized variables or lowercased.

To take inputs from users:

input("message")

For example:

input("enter your age") 

Inputs only take user inputs as string. So you have to cast it as numbers if needed. Only takes one argument. If you want to take multiple arguments you have to use a loop because python pauses the execution as it waits for the user input.

The above will show to the user:

enter your age |

I added a blinking cursor for effect.

As a default the input is stored in a memory location.

Single line comments

# single line comment

Multiple line comments

"""
Multiple
Line comment
"""

OR

'''
Multiple line comment
'''

Constants don’t exist in python. Only variables are used.

You can’t declare a variable only initialization. You must give it a value every you write it.

name = value

variables must be alpha numeric (a1 = 10)or alpha (a =10), spaces are not allowed, use underscore instead (_).

Semi colons are optional but preferably ommited, except when you are multiple initializations on a single line.

Data types

Simple types

int
str (collection of letters)
float (decimal)
bool (True or False, interchangeable with 1 and 0)

Note: True and False are capitalized.

Others

list (mutable)
tuple (immutable)
dictionary
set

You do not need to specify the type, python uses dynamic type inference. You can do this.

Note: list in Python is an Array.

a = 10
# a is an int
a = "Scott"
#a is a string

You can check the type by using this function.

type(variable_name)

you can cast to another type like so.

a = '30'
a = int(a)
type(a) # will be int

Execution

control d to abort.

Check your python version by typing Python in the terminal .

Run your python script by first cd ing into it, then

YourName@FirstLast-MacBook-Air Desktop % python yourScript.py

You write if else statements like so

if operand == "x" or operand == "multiplication":
print(first * second)
elif operand == "+" or operand == "addition" or operand == "add":
print(first + second)

You can also do this:

name = "Harry"
if "a" in name:
print("has a")
>>>has a

Note:

  • We do not use {} in python. We instead use a colon in the if or elif lines.
  • We do not use else if , we do not use elseif, we use elif as if to say “elifant.”

Cool string functions

len(name) # gives the character count
name.lower() # returns the name lowercased.
name.upper() # returns the name uppercased.
"Harry".count("r") # returns 2
name.title() # returns lowercased except for the first letter.
myString.replace(" ", "_")
myString.replace(" ", "_", titmeCount)
myString.find("is") # finds first occurance
myString.find("is", 1) # finds second occurrence's index
myString.center(totalLength, "Fills w/this")

Types of operators

Arithmetic

+, 
-,
/ (does not round down),
*,
%,
// (dividing and round down),
math.ceil(7.1) -> 8,
+=, # does not support ++
-=, # does not support --

+= behaves normally except it allows you to omit square brackets when concatenating lists.

Logical

and, or, in (returns true if value is present in list)

conditional

<=, >=, <, >, !=

Control flow

if:, elif:, else:

Benefits of Python

  • automation
  • Good for scripting and GUI and games.
  • Simpler to use than C and Java
  • works on all major OS
  • More error checking than C
  • More support for large programs than scripts.
  • High Level
  • Interpreted, which makes it more readily adaptable to other programs. (With strongly typed programs you have to make adapters to communicate with other programs).
  • compact and readible
  • the high-level data types allow you to express complex operations in a single statement;
  • statement grouping is done by indentation instead of beginning and ending brackets;
  • no variable or argument declarations are necessary.
  • modular
  • extensible — you can easily add to the python interpreter using C, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application.
  • Named after Monty Python, the English comedy group.

Names, Memory locations and values

scott = "kind"

The name of the constant is scott, it holds a reference to an object that has 3 parts: the memory address is not shown to the developer here, but it is something like 0x9cf10c, the value is "kind", and the type: String.

scott -> Object
- Identity: 0x9cf10c
- type: String
- value: "kind"

Memory address:

id(val) # memory address of value
# you can compare two values memory addresses like so:
if val1 is val2:
print("val1 has the same memory address as val2")

Immutability

Immutability has a different meaning depending on what language you are using. It can either mean that the name points to the same memory address with the same value until it is deallocated, so it can never be reassigned (like in Swift), or, like in Python, if you reassign a constant, then the name gets a new object with a new memory address and a new value.

In Swift the constant’s name never changes memory addresses until its deallocated. In Python the memory addresses retain the same value so names point to new memory addresses when they are deallocated. In Swift immutability describes the constant’s name. In Python immutability describes the memory addresses responsibilities.

You can do this with immutable objects in Python:

scott = "nice" # creates an object with value "nice"
scott = "mean" # creates a new object with new identity and value

types:

Integer, float, string, tuple, bool, frozen set

Here is an interesting example demonstrating the unseparatable link between a memory address and an “immutable” value in Python.

# strings associated with addresses are always the same and this means that 
moveablePointer1 = 'Scott'
moveablePointer2 = moveablePointer1
print(moveablePointer1, id(moveablePointer1), moveablePointer2, id(moveablePointer2))
# Scott 112248030192 Scott 112248030192
moveablePointer1 = 'Nick'print(moveablePointer1, id(moveablePointer1), moveablePointer2, id(moveablePointer2))
# Nick 112248029872 Scott 112248030192
moveablePointer2 = 'Nick'print(moveablePointer1, id(moveablePointer1), moveablePointer2, id(moveablePointer2))
# Nick 112248029872 Nick 112248029872
print('Nick', id('Nick'))
# Nick 112248029872

Notice that no matter what instance of 'Nick' we look at, the memory address of the String literal is always 112248029872.

When the type is immutable the namepointer is moveable.

In Contrast with Swift (and this is true for a few other languages).

let str = "Nick"withUnsafePointer(to: str) {
print("\(str) address: \($0)")
}
withUnsafePointer(to: "Nick") {
print("address: \($0)")
}
// output: Nick address: 0x00007ffeef9a3ac0
// output: address: 0x00007ffeef9a3ac8

The memory addresses are similar because they were created one after the other, but notice the last digit is different, 0 is not 8.

Something weird happens with Python class variables though.

class Circle: 

# class variable
pi = 3.1419

circle1 = Circle()
circle2 = Circle()
circle2.pi = 10
print(Circle.pi, circle1.pi, circle2.pi)
# 3.1419 3.1419 10
Circle.pi = 40
print(Circle.pi, circle1.pi, circle2.pi)
# 40 40 10

Now, notice that circle1.pi changed when the Circle.pi changed. Sketchy. So sometimes variables point not to the literal value, but to another name.

Alternatively, Python pointers don’t always point indirectly to the memory address. They point directly do it.

first = 30
second = first
first = 20
print("first: ", first, "second: ", second)
# first: 20 second: 30

Mutability

When you reassign a new value to a mutable object, it keeps the same memory address, and the name still points to the same object, but it gets a new value.

types:

list, dict, set

Garbage Collection

What happens when an immutable object when its name redirects to a new object? You likely can’t access that old object anymore. When the reference count of an object reaches zero, then Python (the program) calls a garbage collection function that deallocates the object.

Loops

While loops

count = 0
while count < 10:
print("Hello")
count += 1 # you can't use count++ in Python

For loops

for index in range(len(username) - 1, -1, -1): 
print("hi")
print(username[index]) # prints letters backwards
for i in range(0, name._len_()):
print("hi")
  • Range function
range([start,] stop [, step]) -> range object

Functions

def function_name(param1, param2):

You don’t need to assign return values, you can let them be discardeable results.

Weird parts:

  • each of the integers from -5 to 256 reference the same objects. Every 5 value references the 5 object.
  • The assignment operator can split-assign lists, for example:
item1, item2 = [3, 9]
print(item1, item2)
# (3, 9)
  • Python doesn’t have Null, instead it has None

Dictionary

a = {"Area": [10,20,30], "Price": [200, 300, 400]}
# keys are immutable, values are mutable.

If you have multiple data points for a key then you should pass a list

a = {"Name": ["Scott", "Satya"], "rollno": [10, 20]}
# value lengths should be the same for machine learning and data science.

Set

mySet = {1, 1, 3, 4, "Sachin"}
print(mySet)
# {1, 3, 4, "Sachin"}

Removes duplicates.

List

List in Python is an Array for other languages. List is a more relatable naming convention for regular English.

myList = []

An unusual method:

myList.extend(
From here

Had we used append instead, we would have gotten the following instead:

language = ['French', 'English', 'German', ['Spanish', 'Portuguese']]

We also have “remove” which removes the first occurrence of an element regardless of the position and crashes if the element is not present.

*Do not do this!

myList.remove("French")

So you always have to run this before calling remove

if "French" in myList:
myList.remove("French")

You can initialize a list with a range. NumberOfElements minimum is converted to 0.

list = list(range(0, 7))
# List = [0, 1, 2, 3, 4, 5, 6]
# list(range(firstElement, numberOfElements))

There is a function called index which has some interesting optional parameters, from the docs.

list.index(x[, start[, end]])

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueErrorif there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

Weird list method:

mixed[2:] = ["cats", "hat"]

This will delete all values at and after index 2 and then extend the array with “cats”, and “hat”.

Split

names = "Scott Lydon".split()
# names = ["Scott", "Lydon"]
# ORfirst, last = "Scott Lydon".split()
# first = "Scott"
# last = "Lydon"

Comparing lists:

== # compares values
is # compares memory location

Demonstration of mutability

cars1 = ["bla", "blee", "blacc"]
cars2 = cars1
cars2.append("Honda")
print(cars1)
#['bla', 'blee', 'blacc', 'Honda']

You can convert a list with listy strings into a matrix

futureMatrix = ["cats, in, the", "hat, is, a"]
print(",".join(futureMatrix))

Class Variables

class Circle: 

pi = 3.1419

circle1 = Circle()
circle2 = Circle()
circle2.pi = 10
print(Circle.pi, circle1.pi, circle2.pi)
# output: 3.1419 3.1419 10Circle.pi = 40
print(Circle.pi, circle1.pi, circle2.pi)
# output: 40 40 10

Class variables are changeable, and when changed on the class itself, have an affect on all the instances which haven’t manually changed their property value. Until you reassign the class variable on the created instance (not the class instance), it points to the class instance value, either with internal logic that returns the class variable automatically, or it points to the class var name which points to the memory address.

Class Methods:

So if you want to use dot notation with your methods, you need to pass in the first argument as self.

--

--

No responses yet