0% found this document useful (0 votes)
10 views18 pages

Python Programming Basics Guide

The document provides an overview of programming concepts using Python, including definitions of code, software, and programs, as well as an introduction to Python syntax, variables, expressions, and control structures. It covers essential topics such as functions, loops, data structures (lists, dictionaries, tuples), and file handling, along with examples and explanations of how to use these features effectively. Additionally, it touches on regular expressions and web services like XML and JSON for data interchange.

Uploaded by

Clive Mixer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views18 pages

Python Programming Basics Guide

The document provides an overview of programming concepts using Python, including definitions of code, software, and programs, as well as an introduction to Python syntax, variables, expressions, and control structures. It covers essential topics such as functions, loops, data structures (lists, dictionaries, tuples), and file handling, along with examples and explanations of how to use these features effectively. Additionally, it touches on regular expressions and web services like XML and JSON for data interchange.

Uploaded by

Clive Mixer
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PY4E

Why Program

What is Code? Software? A Program?

A sequence of stored instructions


A little piece of our intelligence in the computer

A piece of creative art


When a good job is done on User Experience

Python Language

An individual who can speak Python is known as a Pythonista

Guido van Rossum developed it

You can run a line of code directly in the interpreter

Vocabulary/Words - Variables and Reserved words

Sentence structure or Lines - valid syntax patterns

Story Structure - constructing a program for a purpose

Script - Python program in a file .py

Program Steps or Flow

Reserved words

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

Variables, Expressions and Statements

Constants

Fixed values such as numbers, letters, and strings.

None is a constant assigned to variable to indicate the value is empty.

Variable

PY4E 1
A named place in memory where a programmer can store data and later
retrieve the data using variable name

Variable Name Rules

can start with letter or underscore _

must consist of letters, number and underscores

Case Sensitive

Mnemonic variable names help remember the intent of use as they are
descriptive. Mnemonic means memory aid.

Python reserved keywords (not to be used for variable names)

False await else import pass


None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

Expressions

Operators

Comparison Operators

Boolean ask questions & answers

Numeric Operators

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

** Power

% Remainder

Order of Operation

Parenthesis

Power

Multiplication

PY4E 2
Addition

Left to Right

Type

type() function can tell what type a variable is.

Integer division converts the result to be float

int() and float() functions can be used to convert strings

User input() function

nam= input(’who are you :’ )

input() function always returns string

ng

Comments
# is used at the begining of the sentence

Conditional Execution

if statement is used for 1-way decision

if x ==5:
print(’Equals 5’)
#another action here ..

if else statement is used for 2-way decisions

if x > 5:
print(”Great”)
else :
print(”Not Greater”)

elif statement is used for multi-way decisions

if condition1:
#do this
elif condition2:
#do this
elif condition3:
#do this

Comparison operators

PY4E 3
Python Meaning

< Less Than

<= Less than of Equal to

!= Not Equal

>= Greater or Equal to

== Equal to

> Greater than

Catching Exceptions with try and except

inp = input('Enter Fahrenheit Temperature:')


try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')

# Code: [Link]

Functions

A function is some stored code that we use.

A function takes some input and produces an output.

Built-in functions

input(), print(), type(),max(), etc…

Function we define

def keyword defines the function

A function definition specifies the name of a new function and the


sequence of
statements that execute when the function is called.

def thing():
print(’Hello’)

invoke/call functions as part of the expressions.

def print_lyrics():
print("I'm a lumberjack, and I'm okay.")

PY4E 4
print('I sleep all night and I work all day.')

def repeat_lyrics():
print_lyrics()
print_lyrics()

repeat_lyrics()

# Code: [Link]

An argument is a value we pass into the function as input when we call the
function e.g. float(rate)

A Parameter is a variable which we use in the function definition.

return keyword is used for returning a value of the function execution or to exit
a loop.

Loops and Iterations

Loops have iteration variables that change each time through a loop.

The break statement ends the current loop and jumps to the statement
immediately following the loop.

The continue statement ends the current iteration and jumps to the top of the
loop and starts the next iteration.

While Loop

while condition :
#statements
#statements

While loops are called “indefinite loops” because they keep going until a
logical condition becomes false.

For Loop

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends:
print('Happy New Year:', friend)
print('Done!')

PY4E 5
These loops are called “definite loops” because they execute an exact
number of times.

definite loops iterate through the numbers of a set.

definite loops have explicit iteration variables that move through the
sequence or set.

Strings

A string is a sequence of characters

String literal uses quotes ‘Hello’

Reading and Converting

We prefer to read data using strings and then parse and convert the data as
we need.

This gives us more control over error situations and/or bad user input.

Looking Inside Strings

We can get a single character in string using index specified in square


bracket str[i]

The index value must be an integer and starts from zero.

len() function returns the length of the string.

looping through strings can be achieved with for loop or while loop.

Slicing Strings

colon operator

controls string as an array

s[0:4] start at position 0 up to, but not including 4.

+ operator has no space in between print(x+y) prints the 2 strings as one

in keyword

can be used check if one string is in another string

in expression is a logical expression that returns True or False and can


be used in an if statement

String Library

set of string functions

These functions are already built into every string - we invoke them by
appending the function to string variable

PY4E 6
these functions do not modify the original string, but return an altered
string based on the operation.

dir(string_var) returns all the methods executable

find() function

is used to search for substring within another string

finds the first occurrence of the substring

if not found return value is -1

Stripping whitespace

strip() removes whitespace

lstrip() and rstrip() strips left/right

replace() function

is like search and replace operation in word processor

replaces all occurrences of the search string with replacement string

Prefixes

[Link](’Please”) True

Parsing and Extracting

Files

Text file is a sequence of lines

open() function

opens a file

returns a file handle - a variable used to perform operations on the file

Similar to File→Open

syntax handle=open(filename, mode)

newline \n character

used to indicate end of line

Always include \n at the end of each line in file for python to be able to read
it

File Handle

File handle open for read can be treated as sequence of strings (lines)

Reading File

PY4E 7
fhand = open('[Link]')
count = 0
for line in fhand:
count = count + 1
print('Line Count:', count)

# Code: [Link]

Searching through a file

fhand = open('[Link]')
for line in fhand:
line = [Link]() #this removes \n at the end of line

if [Link]('From:'):
print(line)

# Code: [Link]

for statement is used to iterate through the sequence


xfile = open(’[Link]’)

for cheese in xfile:


print(cheese)

Lists

Algorithm

A set of rules or steps to solve a problem.

Data Structures

A particular way of organising data in a computer.

Store more than one item in a variable.

A List is a kind of Collection

Collection

A collection allows us to put many values in a single variable.

Carry many values in one convenient package

PY4E 8
List constants are surrounded by square brackets and elements separated by
comma

friends = [ ‘Joseph’, Glenn’ , ‘Sally’ ]

List element can be any Python object or even another list

Lists are mutable (changeable)

len() function returns the number of elements in a list

Concatenating lists using + : we can create new list by adding 2 existing lists

Lists can be sliced using :

List Methods e.g. append(), sort(),

split() function

splits the list using space by default

split(;) will split based on character ;

Dictionaries

The dictionary data structures allows us to store multiple values in an object


and look up the values by their key.

A linear collection of key-value pairs.

Python’s most powerful data collection.

Allows us to do fast database-like operations in Python

Keeps entries in order of insertion.

Python lists, dictionaries, and tuples are “abstract objects” designed to be easy
to use.

dict() function

is used to construct a dictionary e.g.

person = dict()
person[’name’] = ‘Clive’

person[’Surname’] = “M”

get()
we can use get() and provide a default value zero when the key is not yet in the
dictionary —and then just add one.

PY4E 9
Even though dictionaries are not stored in order, we can write a for loop that
goes through all the entries in a dictionary. It goes though all the keys.

Tuples

The tuple is a Python data structure that is like a simple and efficient list.

Another kind of sequence that functions much like a list, indexed from from 0.

Tuples are immutable, no sort, no append, no reverse.

Only count and index methods are available foe tuples.

Tuples are more efficient in terms of memory use and performance than lists.

For temporary variables, tuples are preferred over lists.

💡 Quick Tips to Beat the Tuple Hurdle:


1. Think of tuples as "read-only lists":

You can’t change them ( immutable ), but you can access them.

Use them when you need a fixed group of items (like (name, score) ).

2. Practice tuple unpacking:

python
CopyEdit
(x, y) = (4, 'hello')
print(x) # 4
print(y) # 'hello'

3. Use tuples in sorting:

python
CopyEdit
d = {'a': 10, 'b': 1, 'c': 22}
tmp = list([Link]()) # Converts dict to list of tuples
[Link]() # Sorts by key by default

4. Try sorting by value:

python
CopyEdit
sorted_by_value = sorted([Link](), key=lambda x: x[1], reverse=True)

PY4E 10
print(sorted_by_value)

These come up a lot in data analysis and AI work later, so it’s worth getting
comfortable with them.

Would you like a short practice exercise or visual explanation to help lock in
how tuples and sorting work?
4o

You said:
yes please and keep it brief

ChatGPT said:
Absolutely — here’s a brief tuple + sorting exercise to lock it in:

🧪 Mini Exercise: Sort Dictionary by Value Using Tuples


Code:

python
CopyEdit
data = {'Alice': 5, 'Bob': 9, 'Clive': 3}

# Convert to list of tuples


tmp = list([Link]()) # [('Alice', 5), ('Bob', 9), ('Clive', 3)]

# Sort by value (index 1 of tuple)


sorted_data = sorted(tmp, key=lambda x: x[1], reverse=True)

print(sorted_data)

Output:

python
CopyEdit
[('Bob', 9), ('Alice', 5), ('Clive', 3)]

🧠 Quick Breakdown:
PY4E 11
[Link]() → gets (key, value) tuples.

lambda x: x[1] → tells sorted() to use the value for sorting.

reverse=True → sorts from highest to lowest.

You’ve just used tuples, lambda, and sorting in a real-world Python pattern —
this shows up often in AI tasks too, like ranking predictions.

Regular Expressions

Allows us to search for patterns in strings and extract data from strings using
the regular expression programming language.

Provides a concise and flexible means for matching strings of text.

Written in a formal language that can be interpreted by a regular expression


processor.

before using them import re

[Link]() is similar to find()

Network Programming
[Link]
G11lO9#scrollTo=Q9pupLXTJUWJ

Web Services

XML (eXtensible Markup Language)

share structured data

Tags indicate the begining and ending of elements

Attributes - keyword/value pairs on opening tag

Serialize/De-serialize- convert data in one program into a common format


that can be stored and/or transmitted between systems in a programming
language-independent manner.

XML Schema

describing a contract as to what is acceptable XML

Expressed in terms of constraints on the structure and content of


documents

PY4E 12
<xs:complexType name="poerson">
<xs:sequence>
<xs:element name="lastname" type="xs:string"
minOccurs="1" maxOccurs="1"/> <!--# This is a constraint,
means it's required -->
<xs:element name="age" type="xs:integer"/>
<xs:element name="dateborn" type="xs:date"/>
</xs:sequence>
</xs:complexType>

Example Python Code

import [Link] as ET
data = '''<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes"/>
</person>'''

tree = [Link](data)
print('Name:', [Link]('name').text)
print('Attr:', [Link]('email').get('hide'))

JSON (JavaScript Object Notation)

Represents data as nested “lists” and “dictionaries”

Dictionary code

import json
#dictionary data type starts here with {
data = ''' {
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}

PY4E 13
}'''

info = [Link](data)
print('Name :' , info["name"])
print('Hide :' , info["email"]["hide"])

List code

import json
##[ indicates a list
input ='''[
{ "id" : "001",
"x" : "2",
"name" : "Chuck"
},
{ "id" : "009",
"x" : "7",
"name" : "Chuck"
}
]'''

info = [Link](input)
print('User count:', len(info))
for item in info:
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])

Service Oriented Approach

Most non-trivial web-apps use services

Services publish rules applications must follow to make use of the service
(API)

API

Application Programming Interface

Specifies an interface and controls the behaviour of objects specified in


that interface.

Python Objects

Object Oriented

A program is made up of many cooperating objects.

PY4E 14
A program has one or more objects working together.

Object is self-contained Code and Data.

Key aspect of the object approach is to break the problem into smaller
understandable parts.

Class - a template - Dog

Method or Message - A defined capability of a class - bark()

Field or Attribute - A bit of data in a class - length

Object or Instance - A particular instance of a class.

Sample Class

class PartyAnimal:

def __init__(self):
self.x = 0
print('I am constructed')

def party(self) :
self.x = self.x + 1
print("So far", self.x)

def __del__(self) :
print("I am destructed", self.x)

an = PartyAnimal()

[Link]()
[Link]()
[Link]()
an = 42
print('an contains', an)

Object Life-cycle

Objects are created (constructor), used and discarded(destructer)

Inheritance

reuse existing class and inherit all capabilities and add new to make new
class

PY4E 15
class PartyAnimal:

def __init__(self, nam):


self.x = 0
[Link] = nam
print([Link], 'constructed')

def party(self) :
self.x = self.x + 1
print([Link], "party count", self.x)

def __del__(self) :
print("I am destructed", self.x)
class FootballFan(PartyAnimal):
def __init__(self, nam):
super().__init__(nam)
[Link] = 0

def touchdown(self):
[Link] = [Link] + 7
[Link]()
print([Link], "points", [Link])

s = PartyAnimal("Sally")
[Link]()

j = FootballFan("Jim")
[Link]()
[Link]()

Databases

Terminology

Database - contains many tables

Relation(or table) - contains tuples and attributes

Tuple (or row) - a set of fields that generally represents an object like a
person or music track

Attribute (also column or field) - one of possibly many elements of data


corresponding to the object represented by the row

SQL

PY4E 16
Structured Query Language is used to issue commands to the database

Create table

Retrieve some data

Insert data

Delete data

DBA (Database Administrator)

Person responsible for the design, implementation, maintenance, and repair


of an organization’s database

Database Model/Schema

Structure or format of a database.

SQL Summary

INSERT INTO Users (name, email) VALUES ('Kristen', 'kf@[Link]')


DELETE FROM Users WHERE email='ted@[Link]'
UPDATE Users SET name="Charles" WHERE email='csev@[Link]'
SELECT * FROM Users
SELECT * FROM Users WHERE email='csev@[Link]
SELECT * FROM Users Order BY email'

Database Design

The art form of its own with particular skills and experience

Starts with a picture (data model)

Building Data Model

Drawing a picture of the data objects for our application and then
figuring out how to represent the objects and their relationships.

Basic rule: Don’t put the same string data in twice - use relationship
instead.

Representing Relationships in a Database (Normalization)

Do not replicate data - reference data - point at data

Use integers for keys and for references

Add a special key column to each table which we will make references
to.

Primary Key - generally an integer auto-increment field

Logical Key - What the outside world uses for lookup

PY4E 17
Foreign Key - generally an integer key pointing to a row in another
table. When a table has a column that contains a key which points
to the primary key of another table.

Key Rules/Best Practices

Never use your logical key as the primary key

Logical keys can and do change, albeit slowly.

Relationships that are based on matching string fields are less


efficient than integers

JOIN Operation

links across several tables as part of SELECT operation

You must tell JOIN how to use the keys that make the connection
between the tables using ON clause

select [Link], [Link] from Album join Artist on Album.


artist_id = [Link]

Many-to-Many Relationship

Connection(Junction) table with 2 foreign keys is used.

There is usually no separate primary key

Complexity Enables Speed

By normalizing the data and linking it with integer keys, the overall
amount of data which the relational database must scan is far lower
than the data were simply flattened out

Summary

Relational Databases allow us to scale to very large amounts of data

The key is to have one copy of any data element and use relations and joins
to link the data to multiple places

This greatly reduces the amount of data which must be scanned when
doing complex operations across large amounts of data

Database and SQL design is a bit of an art form

PY4E 18

You might also like