Advanced
Searching inSummaries
How to search
  • Words find lesson titles, text and code. Filter by type (guides, courses, programs, books) or stay in this book.
  • book:rhcsa and ch:8 narrow the search; #code finds a word only in commands of the lessons.
  • "two words" finds the exact phrase.
  • Plain words find names, texts and examples.
  • ↑ ↓ to move · Enter to open · Esc to close · / to search
Try:

Course 7Name in the course: Python for Data Science & AI: Hands-On Development

Python for Data Science, AI & Development

Course 7 of 16 in the IBM DevOps and Software Engineering certificate. This is a beginner course. You need no coding experience before you start.

Note

My result — Course completion: 100%; Grade: 100% (pass = 50%); Certificate: not offered on Cognitive Class for this edition.

Course page: Coursera · Cognitive Class

  • 12 Lessons
  • 2 Commands
  • 1 Labs

$ run as a normal user# run as root (or with sudo)

7.1

What the course covers

Python basics: types, variables, and strings.

  • Core data structures: lists, tuples, dictionaries, sets.
  • Programming logic: conditions, loops, functions, errors, classes.
  • Working with data using files, pandas, and numpy.
  • Getting data from APIs and the web.
  • A final exam on all five modules.
ModuleMain focus
Module 1 · about 3 hoursPython Basics: Jupyter, types, expressions, variables, strings
Module 2 · about 3 hoursPython Data Structures: lists, tuples, dictionaries, sets
Module 3 · about 6 hoursPython Programming Fundamentals: conditions, loops, functions, exceptions, classes
Module 4 · about 6 hoursWorking with Data in Python: files, pandas, numpy
Module 5 · about 7 hoursAPIs and Data Collection: simple APIs, REST APIs, web scraping, final exam

7.2

Module 1: Python Basics

Python Basics: Jupyter, types, expressions, variables, strings.

  • Python is a general-purpose language. Its code is easy to read, and indentation matters.
  • A Jupyter Notebook mixes code cells, text cells, and output in one page. Run a cell with Shift+Enter.
  • Types: int (whole), float (decimal), str (text), bool, None. Check with type(x); change with int("5") or str(5).
  • Expressions produce a value; variables store one: x = 5.
  • Arithmetic: + - * /, // (floor divide), % (remainder), ** (power). Comparison gives True or False.
  • Strings: index from 0, slice with [start:stop], use .upper(), .lower(), .replace(), .split(). Strings are immutable, so build a new string instead of changing one.
  • Python reads like English. That is why teams pick it for quick work.
  • The spaces at the start of a line define a block. Python uses them, not braces.
  • A notebook holds code, notes, and output in one place. Shift+Enter runs a cell.
  • Numbers come as int (no dot) and float (with a dot). Text is str. Truth is bool. None means nothing.
  • type() names a type. int() and str() convert one to another.
  • x = 5 puts the value 5 under the name x.
  • // drops the decimal. % gives what is left over. ** raises to a power.
  • Text counts from 0. [1:4] takes 1, 2, 3. Methods: .upper(), .lower(), .replace(), .split().
  • Text cannot be edited in place. Build a new string instead.

7.3

Module 2: Python Data Structures

Python Data Structures: lists, tuples, dictionaries, sets.

  • List: ordered and changeable. l = [1, 2, 3]; methods .append(), .insert(), .remove(), .sort(). Tuple: ordered but immutable (t = (1, 2, 3)), good for fixed data.
  • Dictionary: key and value pairs. d = {"name": "Ada"}; read d["name"], change d["age"] = 3. Methods: .keys(), .values(), .items(), .get().
  • Set: unordered with no duplicates. s = {1, 2, 3}; good for repeats and membership checks.
  • len(x) gives the number of items; in checks membership (2 in l is True). Slicing works on lists too.
  • A list keeps order and can grow: [1, 2, 3]. Use .append() or .sort().
  • A tuple also keeps order but is locked: (1, 2, 3). Good for data that must stay fixed.
  • A dictionary looks up a value by key: {"name": "Ada"}. .get() is a safe lookup.
  • A set holds unique items and drops repeats. It has no order. in answers yes or no.

7.4

Module 3: Python Programming Fundamentals

Python Programming Fundamentals: conditions, loops, functions, exceptions, classes.

  • Conditions: if, elif, else, with indented blocks. Python checks them in order.
  • Loops: for goes over a sequence; while runs while a condition is true. range(5) gives 0,1,2,3,4; break leaves early and continue skips one.
  • Functions: def name(args): then return value. A function with no return gives None.
  • Exceptions: try, except, else, finally. Example: try: x = int("abc") then except ValueError: print("bad number").
  • Classes are templates for objects. class Dog: with def __init__(self, name): sets up a new object; self is the object itself.
  • if / elif / else checks top to bottom. The first true branch wins.
  • for walks a collection. while repeats until a test turns false. range(3) is 0, 1, 2.
  • break exits a loop. continue jumps to the next round.
  • def names a function. return hands a value back. With no return, the answer is None.
  • Errors are caught with try / except. finally runs either way.
  • A class is a blueprint. __init__ runs at birth. self points at the object.

Commands in this lesson

7.5

Module 4: Working with Data in Python

Working with Data in Python: files, pandas, numpy.

  • Files: with open("data.txt", "r") as f: reads text. "w" writes and replaces, "a" adds to the end, and with closes the file for you.
  • pandas works with tables: a DataFrame has rows and columns; a Series is one column.
  • pd.read_csv("file.csv") loads a CSV; df.head() shows the first rows. Common pandas work: df["col"], df[df["age"] > 30] (filter), df.dropna(), df.describe().
  • numpy works with arrays: np.array([1,2,3]), a.shape, and fast math on all items like a * 2.
  • with open(...) reads a file and closes it when the block ends.
  • "w" clears the file. "a" adds to the end.
  • A DataFrame is a table. A Series is one column of that table.
  • read_csv loads a file. head() peeks at the first rows.
  • df[df["age"] > 30] keeps matching rows. dropna() drops blanks.
  • describe() summarises the numbers. numpy arrays do maths on every item at once.

7.6

Module 5: APIs and Data Collection

APIs and Data Collection: simple APIs, REST APIs, web scraping, final exam.

  • An API is a way for programs to talk to each other. A simple API wraps one job; a REST API uses HTTP.
  • REST methods: GET (read), POST (create), PUT (replace), DELETE (remove).
  • A request goes to an endpoint (a URL) and returns a response, often in JSON: {"name": "Ada"}.
  • In Python, requests sends calls: r = requests.get(url), then r.status_code and r.json(). Codes: 200 OK, 404 not found, 500 server error.
  • Web scraping reads data from web pages: requests fetches the HTML and BeautifulSoup parses it.
  • An API is a contract between two programs.
  • A simple API does one task. A REST API follows HTTP rules.
  • GET reads. POST adds. PUT replaces. DELETE removes.
  • A call goes to an endpoint. The reply is often JSON text.
  • requests.get() makes the call. status_code is the result number. .json() turns text into data.
  • 200 is fine. 404 is missing. 500 is a server fault.
  • Scraping means fetching a page and pulling data from the HTML.

7.7

Course topics and key ideas

Python is a popular language. Many people use it for data and software.

  • You can start from zero. The course says you need no earlier coding experience.
  • The course is hands-on. You practice as you learn.
  • Data structures hold and organize your data.
  • APIs let your code talk to other services.
  • Web scraping takes data from web pages.
  • These skills are useful for data science, data analytics and software development.

Topics of the course

  • How to run Python code
  • Variables and simple data types
  • Text with strings
  • Data structures: lists and dictionaries (the catalog names data structures)
  • Logic with if and else
  • Loops to repeat work
  • Functions to reuse code
  • Classes and objects
  • Files and data libraries such as NumPy and pandas
  • REST APIs (the catalog names APIs)
  • Web scraping (the catalog names this)

Why it matters

  • Python is a first language for many data and software jobs
  • Data work needs code skills
  • APIs and scraping bring real data into your projects
  • Good basics make the next courses easier

7.8

Key terms

The words of this course in one table. Learn them before the quiz or exam.

TermMeaning
404Not found.
APIA way for two programs to trade data.
ArgumentA value you give to a function when you call it.
ClassA plan for making objects. An object has data and actions.
ConditionalCode that runs only when a test is true. Example: if / else.
Data frameA table of data. pandas uses it. See glossary.md.
DataFrameA table. Series = one column.
DictionaryKey to value.
EndpointThe address of one API job.
ExceptionAn error object.
FloatA number with a decimal point. Example: 3.14.
FunctionA named piece of work.
IDEA program to write and run code.
IndentationThe spaces that open a block.
intWhole number. float = number with a decimal point.
IntegerA whole number. Example: 7.
JSONA text shape for data.
len()How many items.
LibraryCode that other people wrote. You add it to your project.
ListOrdered and able to grow.
LoopCode that repeats a step many times.
NoneThe empty value.
numpy arrayA box for numbers.
range(n)0 up to n-1.
REST APIA web API that uses HTTP and common URL and method rules.
returnThe value a function sends back.
ScrapingTaking data from web pages.
SetUnique items only.
status_codeThe three-digit reply.
strText. bool = True or False.
tryThe risky block.
TupleOrdered and locked.
VariableA name that holds a value.
Web scrapingA program reads web pages and takes the data it needs.

Commands in this lesson

7.9

Check yourself

Answer each question first, then open it to check the answer.

1What is a variable in Python? a) A type of loop · b) A name that stores a value · c) A file on disk · d) A code cell in Jupyter

b) A name that stores a value. A variable is a name that holds a value.

2Which type stores text? a) int · b) float · c) str · d) bool

c) str. str means string, which is text.

3What is the main difference between a list and a tuple? a) A list is ordered, a tuple is not · b) A tuple cannot be changed after it is created · c) A list can hold only numbers · d) A tuple can hold only one item

b) A tuple cannot be changed after it is created. Tuples are immutable; lists can be changed.

4Which line creates a dictionary with the key name? a) d = ["name", "Ada"] · b) d = ("name", "Ada") · c) d = {"name": "Ada"} · d) d = {"name", "Ada"}

c) d = {"name": "Ada"}. Curly braces with key: value make a dictionary.

5What happens when you add the same value twice to a set? a) The value is stored twice · b) The set keeps only one copy · c) Python raises an error · d) The set becomes a list

b) The set keeps only one copy. Sets hold unique values only.

6In an if / elif / else chain, which block runs? a) All three blocks · b) The first block whose condition is true · c) The last block only · d) A random block

b) The first block whose condition is true. Python runs the first true branch and skips the rest.

7What does range(3) produce? a) 1, 2, 3 · b) 0, 1, 2 · c) 0, 1, 2, 3 · d) 3 only

b) 0, 1, 2. range(3) starts at 0 and stops before 3.

8Which keyword starts a function definition in Python? a) func · b) define · c) def · d) function

c) def. def defines a function.

9What is the purpose of try / except? a) To repeat a block of code · b) To handle an error without crashing the program · c) To import a library · d) To print the type of a value

b) To handle an error without crashing the program. except catches the error so the program continues.

10Which library is best for tables with labelled rows and columns? a) numpy · b) pandas · c) requests · d) json

b) pandas. pandas DataFrames are labelled tables.

11What does r.json() do when r is an API response? a) Sends the request again · b) Turns the JSON text into Python data · c) Saves the response to a file · d) Deletes the response

b) Turns the JSON text into Python data. .json() parses the response body into Python objects.

12Which HTTP method usually reads data from an API? a) GET · b) POST · c) DELETE · d) PUT

a) GET. GET reads data; the others change data.

13What does x = 8 do? a) Prints 8 · b) Stores 8 under the name x · c) Adds 8 to x · d) Deletes x

b) Stores 8 under the name x. The name x now points at the value 8.

14Which value is text? a) 42 · b) 4.2 · c) "42" · d) True

c) "42". Quotes around a value make it a string.

15What does type(3.0) show? a) int · b) float · c) str · d) bool

b) float. A number with a dot is a float.

16Which sign gives the remainder of a division? a) // · b) % · c) ** · d) /

b) %. % returns what is left after the division.

17Why does s[0] = "A" fail on a string? a) Text cannot be changed in place · b) Text has no index 0 · c) The letter is wrong · d) Strings need []

a) Text cannot be changed in place. Strings are immutable, so build a new one.

18Which structure can grow after it is made? a) A tuple · b) A list · c) A constant · d) A file

b) A list. A list can take new items. A tuple cannot.

19Best choice for two fixed values that must not change: a) A list · b) A tuple · c) A dict · d) A set

b) A tuple. A tuple locks its values after it is made.

20Which structure maps a name to a value? a) List · b) Tuple · c) Dictionary · d) Set

c) Dictionary. A dictionary stores key and value pairs.

21You have ten names and want no repeats. Which structure? a) Set · b) Tuple · c) String · d) List

a) Set. A set removes duplicates by design.

22What does len([4, 5, 6]) give? a) 2 · b) 3 · c) 4 · d) 6

b) 3. It counts the three items.

23What does range(4) produce? a) 1, 2, 3, 4 · b) 0, 1, 2, 3 · c) 0, 1, 2, 3, 4 · d) 4

b) 0, 1, 2, 3. It starts at 0 and stops before 4.

24if / elif / else: how many branches run? a) One · b) Two · c) All · d) None

a) One. Only the first true branch runs.

25What does continue do? a) Ends the loop · b) Skips the rest of this round · c) Ends the program · d) Starts again from zero

b) Skips the rest of this round. It skips the rest of the current round.

26A function ends with no return. What comes back? a) 0 · b) None · c) False · d) ""

b) None. No return means the function gives None.

27Which clause catches a bad number conversion? a) except ValueError · b) finally · c) else · d) pass

a) except ValueError. ValueError is the error from a bad conversion.

28What is self in a method? a) The class name · b) The current object · c) The module · d) The test

b) The current object. self is the object the method works on.

29You must erase a file and write new text. Which mode? a) "r" · b) "a" · c) "w" · d) "rb"

c) "w". "w" truncates the file before writing.

30Which pandas object is a single column? a) DataFrame · b) Series · c) list · d) dict

b) Series. A Series is one column with labels.

31Which line keeps rows with price over 10? a) df[df["price"] > 10] · b) df["price" > 10] · c) df > 10 · d) df.price(10)

a) df[df["price"] > 10]. The inner test makes a true/false mask.

32A reply has status 500. What happened? a) The server failed · b) The page is missing · c) The login failed · d) The data is fine

a) The server failed. Codes from 500 up point at the server side.

33What is a list?

A list is an ordered group of items.

34What does an API do?

An API lets one program ask another program for data or a service.

35Why do we use functions?

A function keeps code in one place. We can use it many times.

7.10

Study and exam tips

Practise in Jupyter. Run small cells and read the error messages.

  • Learn every type (int, float, str, bool, None) and when to use a list, tuple, dict, or set.
  • For data remember pd.read_csv, df.head(), np.array; for APIs, requests.get, status_code, .json().
  • Run code in Jupyter. Short cells show what each line really does.
  • Know the four containers, and match the library to the job: pandas for tables, numpy for arrays, requests for APIs.
  • For API questions, look at the method, the code, and the parsed body.
  • When two answers seem right, choose the exact type or tool named in the course.

Practice

All commands in this chapter