Learn Python in 75 Minutes

Speedy Python Tutorial

Welcome to a rapid Python tutorial! In this session, I'll teach you Python at a brisk pace. Note that this isn't intended for complete beginners. If you're seeking beginner-level content, explore my channel where I offer many beginner tutorials. I'll provide various resources below. If there's any omission or error, kindly point it out in the comments. Now, let's dive in!

1. Setup & Installation

  • Begin by downloading and installing the latest version of Python from the official website (link in the description). Ensure it's version 3.6 or above for compatibility.

  • Don't forget to select "Add Python to PATH" during installation; it'll simplify processes later.

  • While Python does come with its built-in IDE, I recommend using Visual Studio Code (VS Code) as your text editor. Download it from the link provided.

  • For those opting for VS Code, remember to install the Python extension from the VS Code marketplace.

2. What Python is Used For

  • Python is a versatile, general-purpose language known for its simplicity and rapid development speed.

  • Its primary applications include web development, machine learning, artificial intelligence, and data science tasks.

  • A quick glance at my channel's playlists can offer an overview of what can be achieved with Python.

Sponsor Note: Big thanks to SimplyLearn for sponsoring this video and offering a discount on their Data Scientist Master's Program, co-developed with IBM. This program offers a blend of six courses, teaching over 30 in-demand skills, and using tools like R, Sass, Python, Tableau, Hadoop, and Spark. On completion, certifications from both IBM and SimplyLearn are provided. Check the description for more details.

3. Data Types

  • Python primarily has four core data types:

    • Integers (int): Whole numbers without decimal points, e.g., 2, -9.

    • Floats: Numbers with decimal points, e.g., 2.7, 9.7.

    • Strings: Sequences of characters or numbers enclosed in single ('') or double ("") quotes, e.g., 'hello', "4.6".

    • Booleans: True or False values.

4. Output & Printing

  • The print() function is crucial for displaying outputs in Python.

  • To print a text, it must be enclosed in quotes (making it a string), e.g., print("hello world").

  • You can print multiple items by separating them with commas, which will add a space between them.

  • By default, every print statement prints on a new line, but you can change this behavior using the end argument.

5. Variables

Coming up next, we'll explore the importance of variables in Python programming.

Stay tuned and let's continue our quick journey through Python!


Python Tutorial: Basics and Beyond

1. Understanding Variables

Variables in Python are quite simple to create. Consider them as containers that store data. Here's a basic structure:

Naming Conventions:

  • Avoid special characters.

  • Must not start with a number.

  • Use underscores for multi-word variables (snake_case). For instance: hello_world.

2. Taking User Input

Receiving input from users is made easy with the input function. It prompts users for a value:

Note: The input function returns values as strings. If you need numerical input, you'd have to convert the string.

3. Arithmetic Operators

Python supports a variety of operators for mathematical operations:

  • Basic Arithmetic: +, -, *, and /

  • Exponents: **

  • Floor Division: // (returns the quotient without the remainder)

  • Modulus: % (returns the remainder)

Important Points:

  • Ensure that operands (values on either side of the operator) are of compatible types.

  • Division always returns a float, even if the result is a whole number.

  • Order of operations follows the BEDMAS/BODMAS convention: Brackets, Exponents, Division and Multiplication, Addition, and Subtraction.

Example:

4. Input and Arithmetic Operations

If you wish to perform arithmetic operations on user input, ensure you convert the input string to the appropriate number type:


String Methods in Python

Python strings come packed with numerous built-in methods that allow for efficient manipulation and probing of these data types. Let's dive in to explore these methods.

Understanding String Data Type

First, let's discuss what a string data type is. We can initialize a string by assigning a text value to a variable:

o))

This will output <class 'str'>, indicating that the variable hello is an instance of the string class.

Basic String Methods

It's essential to ensure case-sensitivity when counting substrings. For instance, counting 'L' would return 0 as 'L' and 'l' are distinct characters.

Combining String Methods

Python allows chaining of string methods. For instance, if we need to count the number of 'l's in a string after converting it to lowercase:

2

String Multiplication and Addition

In Python, strings can be multiplied with integers or added to other strings:

String addition is also referred to as concatenation:

Conditional Operators

Conditional operators help compare two values and produce a Boolean result (True or False).

Basic Operators:

  • ==: Equal to

  • !=: Not equal to

  • <=: Less than or equal to

  • >=: Greater than or equal to

  • <: Less than

  • >: Greater than

Examples:

Interestingly, strings can also be compared using these operators. Each character in Python has an associated ASCII value, and comparisons are made based on these values.

Chained Conditionals

Python allows multiple conditions to be linked together to form complex logical statements using the and, or, and not operators:

  • and: Both conditions must be true.

  • or: At least one condition must be true.

  • not: Inverts the truthiness of the condition.

In conclusion, Python offers a rich set of tools for working with strings and conditions, making it versatile for various programming scenarios.


Conditional Statements and Data Collections


1. Conditional Statements: If, Elif, and Else

Python offers a powerful way to make decisions using the if, elif, and else statements. These conditional statements allow us to execute certain blocks of code based on specific conditions.

Example:

In the example above:

  • If the user's name is "Tim", the program prints "You are great!"

  • If the name is "Joe", it prints "Bye Joe!"

  • For any other name, it prints "No".

Remember:

  • An if statement is always followed by a condition.

  • You can have multiple elif conditions.

  • The else statement, if used, should always be at the end.


2. Collections: Lists and Tuples

Python provides two primary types of ordered collections: Lists and Tuples.

2.1 Lists

Lists in Python are versatile and can contain elements of different data types.

Example:

List operations:

  • Length: len(my_list) returns the number of elements in the list.

  • Append: my_list.append("Hello") adds "Hello" to the end of the list.

  • Extend: my_list.extend([5, 6]) appends all elements from the new list.

  • Pop: my_list.pop() removes the last item. You can also specify an index, e.g., my_list.pop(0) removes the first element.

Access and modify:

  • Access elements using index, e.g., my_list[1] returns True.

  • Modify elements by assignment, e.g., my_list[0] = "Changed".

Note: Lists are mutable. If list2 = list1 and you modify list1, list2 will also be changed.

2.2 Tuples

Tuples are similar to lists but are immutable, meaning their elements cannot be modified after creation.

Example:

While you can access elements in a tuple, like my_tuple[0], you can't modify them.


3. Loops: For Loops

The 'for loop' is one of the most common loops in Python. It allows you to iterate over a collection, like lists or tuples, and execute a block of code for each element.



Python For Loops

For loops are fundamental constructs in programming, enabling us to execute a block of code multiple times. Let's delve into the specifics of Python's for loops.

The Basics

In many programming languages, for loops allow us to iterate a specific number of times. However, in Python, the mechanics are a little different and more versatile.

To illustrate, let's create a basic for loop to print numbers from 0 to 9:

Understanding the range Function

The range function is a built-in Python function that generates a sequence of numbers. Its syntax can be one of the following:

  • range(stop): Starts from 0 by default and goes up to, but does not include, the stop number.

  • range(start, stop): Starts from the start number and goes up to, but does not include, the stop number.

  • range(start, stop, step): Starts from the start number, increments by step, and goes up to, but does not include, the stop number.

In our example above, we only provided one argument to range, which means it defaults to starting from 0 and stops at 9.

Looping Through a List

In Python, for loops are not limited to numbers; we can loop through any iterable, such as a list:

This loop will print all the numbers in the numbers list.

Accessing List Indices

If you want to access the index of each element while looping, you can use the enumerate function:

This prints both the index and the value of each element in the numbers list.


Understanding While Loops and the Slice Operator


1. While Loops

Introduction:

while loops in Python are a mechanism to execute a block of code repeatedly as long as a given condition holds true.

Basic Structure:

Example:

Let's consider a simple example where we want to print numbers from 0 to 9.

Key Points:

  • i += 1 is a shorthand for i = i + 1.

  • Apart from addition, other operations like multiplication (*=), division (/=), etc., can also be used in similar shorthand formats.

Using the Break Statement:

You can also control the loop's execution with the break statement.

In the above code, the loop will terminate when i is equal to 10.


2. Slice Operator

Introduction:

Slicing is a technique in Python that allows us to extract specific portions (slices) of a collection, such as a list or string.

Basic Structure:

collection[start:stop:step]

  • start: Index to start the slice (inclusive).

  • stop: Index to stop the slice (exclusive).

  • step: Interval between items.

Examples:

  • Basic Slice:

  • Omitting Values:

If we omit any value, Python uses default values.

  • No start: Assumes the start of the collection.

  • No stop: Assumes the end of the collection.

  • No step: Assumes 1.

  • Negative Step:

Using a negative step value allows you to slice in reverse.

  • Reversing:

A handy trick to reverse a list or string:

Application on Strings and Tuples:

The slicing technique can be applied to any collection in Python, including strings and tuples.


3. Sets in Python

Sets are a unique and versatile data type in Python that allow you to store unordered collections of unique items. Stay tuned as we dive deep into the world of sets in the upcoming section!



Understanding Sets, Dictionaries, and Comprehensions


1. Sets

Introduction:

  • A set in Python is an unordered collection of unique elements. This means sets do not allow for duplicate elements. The importance of sets is in their efficiency in performing look-ups, additions, and removals.

  • Creation:

    • To create an empty set: x = set()

    • To create a set with elements: x = {4, 30, 2, 2}

      • Note: {} creates a dictionary, not a set.

  • Key Properties:

    • Sets don't track the order or frequency of elements.

    • They are very fast for checking membership, adding, and removing elements.

    • Example: A set initialized as {4, 32, 2, 2} will be represented as {32, 2, 4} since it removes duplicates and doesn't maintain order.

  • Basic Operations:

    • Add an element: s.add(5)

    • Remove an element: s.remove(5)

    • Check if an element is in the set: 4 in s (returns a boolean)


2. Dictionaries (Dicts)

Introduction:

  • A dictionary, often likened to hash tables or maps in other languages, is a collection of key-value pairs.

  • Creation:

    • Example: x = {"key": 4}

  • Key Properties:

    • Keys are unique.

    • The values associated with these keys can vary in data types.

    • Extremely efficient in retrieving, adding, and modifying values.

  • Basic Operations:

    • Access a value: x["key"]

    • Add a new key-value pair: x["key2"] = 5

    • Delete a key-value pair: del x["key"]

    • Check if a key exists in the dictionary: "key" in x

    • Get all values: list(x.values())

    • Get all keys: list(x.keys())

    • Iterating through keys and values: for key, value in x.items():


3. Comprehensions

Introduction:

  • Comprehensions are unique to Python and offer a concise way to create lists, dictionaries, and other collections.

  • List Comprehensions:

    • Example: [x for x in range(5)] produces [0, 1, 2, 3, 4]

    • Conditional inclusion: [i for i in range(100) if i % 5 == 0] includes only numbers divisible by 5.

  • Dictionary Comprehensions:

    • Example: {i: 0 for i in range(5)} produces a dictionary with keys from 0 to 4, all mapped to 0.

  • Set Comprehensions:

    • Example: {i for i in range(5)} produces a set {0, 1, 2, 3, 4}.

  • Tuple Comprehensions:

    • Tuples technically don't have their own comprehension, but one can achieve this with the tuple constructor: tuple(i for i in range(5)).

Introduction to Functions

Python offers an elegant way to define reusable blocks of code known as functions. Functions play an integral part in making code modular and maintainable.

Defining a Function

To define a function in Python:

  • Use the def keyword.

  • Choose a function name (same naming conventions as variables).

  • Optionally, add parameters inside parentheses.

  • End with a colon.

  • Write the function's code indented under the function definition.

Calling a Function

Once defined, you can invoke or call the function by its name:

Functions with Parameters

You can define functions to take in parameters:

To call this function, you'd provide values for x and y:

Returning Values

Functions can return values using the return keyword:

Calling this function:

Returning Multiple Values

A function can return multiple values in the form of a tuple:

To capture these returned values, you can use tuple unpacking:

Optional Parameters

Functions can have optional parameters:


Advanced Function Concepts

Functions as Objects

In Python, functions are objects, allowing for some advanced usages:

  • Defining a function inside another function.

  • Returning a function from a function.

Example:

The Unpack Operator

The unpack operator (*) is used to unpack elements from lists or tuples:

For dictionaries, use ** to unpack key-value pairs:

Outputs: 2 5

Variable-length Arguments: *args and **kwargs

For functions that might take a varying number of arguments:

  • *args collects extra positional arguments as a tuple.

  • **kwargs collects extra keyword arguments as a dictionary.

Example:

Usage:


Scope and Globals

Variables have different scopes:

  • Local Scope: Variables defined inside a function.

  • Global Scope: Variables defined outside all functions.

If you want to modify a global variable inside a function, use the global keyword:


That covers the foundational and some advanced concepts about functions in Python. As you progress, you'll encounter even more advanced features and patterns related to functions, which will further enhance your programming capabilities.



Raising Exceptions in Python

In Python, you can intentionally raise an exception using the raise keyword. For instance, consider the following code snippet:

When this code executes, you'll encounter the message "Exception: Bad!". While this is a basic way to raise an exception, there's a lot more you can do with it, such as defining custom exceptions, especially when you delve into object-oriented programming. Another example could be raising a specific error like:

Handling Exceptions

Instead of a try-catch mechanism that you might be familiar with from other languages, Python employs a try-except-finally block:

Here, attempting to divide by zero will trigger an exception. The exception will be caught in the except block, and its message will be printed. You can catch specific exceptions or use a general catch-all. Additionally, there's a finally block where you typically put cleanup operations, ensuring the code within it runs regardless of whether an exception occurred.

Lambda Functions

Lambdas are anonymous functions in Python, typically written in one line:

This lambda takes one argument, x, and returns x + 5. While lambdas can be handy, their primary power is evident when combined with functions like map and filter.

Using Map and Filter

map applies a function to all items in an input list:

filter, on the other hand, creates a list of elements for which a function returns true:

While you can use lambda functions with map and filter, it's not strictly necessary. Any function returning the appropriate value (a single value for map or a boolean for filter) will work.

F Strings in Python

Introduced in Python 3.6, F strings offer a concise way to embed expressions inside string literals:

You can include any expression inside the {} to be evaluated and inserted into the string.

Conclusion

Thank you for sticking through this quick-paced Python tutorial. While I aimed to cover the essentials swiftly, there's much more to Python, especially topics like object-oriented programming and advanced language features. If you're interested, check out my resources on object-oriented programming in Python and a series on expert-level Python features in the description below. Please like, subscribe, and let me know what other topics you'd like to see. Until next time!


Comments

Popular posts from this blog

state government roles website

SQL Tutorials 10 hours

RAG Developer