Getting Started with Python

Course Notes

Eslam Shoaala
5 min readMar 28, 2018
Photo by David Clode on Unsplash

DISCLAIMER: These are my review notes from an online course named ‘Python: Getting Started’ by ‘Bo Milanovich’ on PluralSight. Here is a link to the course. And YES, it’s worth taking it if you have the time.

What is python?

Python is an interpretted, object-oriented, high level programming language with such a high productivity level.

Basic Syntax:

print statement
print("Hello World!")

Types in python:

Python does not require type declaration for variables unlike Java

Integers and floats:

  • ints can be +ve or -ve but can’t have decimal points
  • floats can be decimals
  • python 3 introduces complex number as a type
  • use the following methods to convert from int to float or the opposite
int(32.5) # 32
float(5) # 5.0

Strings:

  • by default they are unicode in python 3
  • strings can be decalred using single quotes, double quotes or trible quotes (used more for class documentation)
  • common string methods:
'hello'.capitalize() == 'Hello'
'hello'.replace('e','a') == 'hallo'
'hello'.isalpha() == True # means that all characters are letters
'123'.isdigit() == True # means that all characters are digits
  • to splits a string into a list
"some,csv,values".split(",") == ["some", "csv", "values"]
  • String format function
name = "Eslam"
machine = "Lenovo"
"Nice to meet you {0}. I am {1}".format(name, machine)
  • Starting in python 3.6, you can do the following:
f"Nice to meet you {name}. I am {machine}"

Boolean and None:

var1 = True
var2 = False
aliens_found = None #None is simillar to null in different languages

If statements:

number = 6
if number == 6:
print("Number is 6")
else:
print("Number is NOT 6")
  • we use the keyword is to see if two variables are pointing to the same object in memory

Truthy and Falsy values:

python checks if a variable has a truthy value, a truthy value in integers is anything which is not zero or a string that contains any text.
This is useful in case of lists, where you do not need to check for list size as in other programming languages put you would rather do the following

if student_list:
execute some code if list exists
if not
!=
is not

Multiple if statements:

and, or
if x and y:
if x or y:

Ternary if statements:

a=1
b=2
"bigger" if a > b else "smaller"

Lists:

  • to create an empty list just use the square brakcets
student_names = []
  • a list that has some elements
student_names = ["Eslam", "Maged", "Ahmed"]
  • to access an item in the list
student_names[0]
student_names[-1] == "Ahmed"
  • Add new items to a list
student_list.append("Hoba") # add to the end
  • to check if an element is in the list
"Hoba" in student_names == True
  • Number of elements in a list
len(student_names) == 4

-having multiple types in a list is not a problem. A list can contain different types from different lists

  • to delete an element from a list
del student_names[2] # "Ahmed is not longer in the list"
  • elements will shift to the left after the delete operation

List slicing:

  • if we want to ignore the first element in the list and get the rest of the list
student_names[1:] == ['Maged', 'Ahmed'] 
student_names[1:-1] == ['Maged'] # we have ignored the first item and the last item in the list

For Loop:

for student in student_names:
print(student)

range:

x = 0
for x in range(10): # code executes from 0 till 10
range(5,10) # 5,6,7,8,9
range(4,10,2) # 4,6,8

Break and continue:

  • break is used to get out of the loop in case you got what you want
  • continue is used to skip an iteration without breaking the loop

Dictionary:

  • In python dictionary we have keys and values
student = {
"name": "Eslam",
"id": "25",
"feedback": None
}

To retrieve data from dictionary:

student["name"] == "Eslam"
student["last_name"] == KeyError
  • in case you want to query a key and you are not sure that it exists there then you should add a fallback
student.get["last_name", "unknown"] == "unknown" #True
  • to get all keys in a dictionary
student.keys() => returns a list of all keys
student.values() => returns a list of all values

Exceptions:

  • events that occur during the execution of your program that causes problems while executing.
try:
last_name = student["last_name"]
numbered_last_name = last_name + 3
except KeyError:
print("Error finding last name")
except TypeError as error:
print("cant add two values")
print(error) #used to show the error in the logs

Other data types:

complex
long #only in python2
bytes and bytearray
tuple = (3,5,1,"Mark")
set and frozenset
set([3,2,1,5]) == (1,2,3,5)

Function:

def function_name(input_params):
function_body
return return_value
  • multiple arguments for a function we use *args
def var_args(name, *args):
print(name)
print(args) #refet to args inside function body we do not use the astrics
var_args("Eslam", "love pythong", None, 77, True)
  • It would be better to have names to the arguments instead of having to loop through all the given arguments to extract the needed variable/value; that’s where we use kwargs…
def var_args(name, **kwargs):
print(name)
print(kwargs["description"], kwargs["feedback"])
var_args("Eslam", description="love pythong", feedback=None, subscriber=True)

Input:

  • to take input from the user we use the input method
student_name = input("Enter student name")

Nested Function:

  • sometimes you need to add a function to do a job inside another function thats where we use neste functions and call it from the outer function. The nested function has access to the variables defined in the outer function. This is called a closure
def get_student():
students = ["eslam", "maged"]
def get_Students_titlecase():
for student in students:
students_titlecase.append(student.title())
return student_titlecase
students_titlecase_names = get_students_titlecase()
print(students_titlecase_names)

Working with files:

try:
f = open("stuents.txt", "r")
for student in f.readlines():
add_student(student)
f.close()
except Exception:
print("could not read file")

Access modes in python:

"w" - writing: overwrites the entire file
"r" - reading a text file
"a" = appending to a new or existing file
"rb" - reading a binary file
"wb" - writing to a binary file

Classes:

  • class is a logical group of functions and data. functions in a class are called methods
  • classes allow you to write more readable and more maintable code.
  • class is a blueprint/building block and the instances of the class are the actualy blocks
class Student:
pass
  • to initiate a new instance of a class
student = Student()

Class example with a function

students = []
class Student:
def add_student(self, name, student_id=332):
student = {"name": name, "student_id": student_id}
students.append(student)
student = Student()
student.add_student("Mark")
  • The constructor method is a special method in python classes that gets executed everytime you create a new isntance of that class
  • Constructor method in python has the syntax of init
def __init__(self, name, student_id):
pass
  • To print an instance of a class we use the method override _ str _
def __str__(self):
return "student" #prints student when trying to print the object otherwise we would get a memory reference

Inheritance:

class HighSchoolStudent(Student):
# we can override methods and variables in the parent class

Calling a parent method in the inherited class:

def get_name_capitalized(self):
original_value = super().get_name_capitalized()
  • In python you can inherit from multiple classes
  • In python there is a convention to put an underscore before the method name to state that the method should not be overridden or even used directly. There are no interfaces in python
  • pyInstaller to generate executable files from the python program you wrote

--

--

Eslam Shoaala

Software Engineer 👨‍💻 | Full-time learner 📚