Discover the essentials of Python programming in this comprehensive guide, designed to help you master the basics. Learn about variables, data types, string formatting, data structures, functions, conditionals, loops, modules, and classes in Python, and unlock the power of this versatile and powerful language. Whether you're a beginner or looking to brush up on your skills, this article will provide you with a solid foundation for Python development. I've previously discussed installing and setting up Visual Studio Code for Python development, so I won't explain that in this article. Python Variable In Python, a variable is a named placeholder that can store a value. Variables are created using the assignment operator ( ). For example: = my_variable = 10 Here, is a variable that holds the value . my_variable 10 Python has several data types that can be assigned to variables. Some common data types in Python include: Numeric data types: Integer ( ) - represents whole numbers, such as or . int 42 -7 Float ( ) - represents decimal numbers, such as or . float 3.14 -0.5 Complex ( ) - represents numbers with both a real and imaginary component, such as . complex 1 + 2j Boolean data type: Boolean ( ) - represents a value of either or . bool True False Sequence data types: String ( ) - represents a sequence of characters, such as . str "Hello, World!" List ( ) - represents an ordered collection of items, such as . list [1, 2, 3] Tuple ( ) - similar to a list, but immutable (cannot be changed), such as . tuple (1, 2, 3) Mapping data type: Dictionary ( ) - represents a collection of key-value pairs, such as . dict {"name": "John", "age": 30} Set data type: Set ( ) - represents an unordered collection of unique items, such as . set {1, 2, 3} Python is a dynamically typed language, which means that the data type of a variable is inferred at runtime based on the value it holds. For example, if you assign an integer value to a variable, the variable will have an data type. If you later assign a string value to the same variable, the variable will now have a data type. int str String Formatting In Python, string formatting is the process of creating a string by inserting values into a string template. There are several ways to do string formatting in Python, including: Concatenation: You can concatenate strings and variables using the operator. For example: + name = "John" age = 30 message = "My name is " + name + " and I am " + str(age) + " years old." Here, the function is used to convert the integer to a string so that it can be concatenated with the other strings. str() age operator: You can use the operator to substitute values into a string template. For example: % % name = "John" age = 30 message = "My name is %s and I am %d years old." % (name, age) Here, is a placeholder for a string value, and is a placeholder for a decimal (integer) value. The values to be substituted are provided in a tuple . %s %d (name, age) : You can use the method to insert values into a string template. For example: str.format() str.format() name = "John" age = 30 message = "My name is {} and I am {} years old.".format(name, age) Here, the placeholders are used to indicate where the values should be inserted. The values to be substituted are provided in the method. {} format() f-strings (formatted string literals): This is the most recent and widely used way to format strings in Python. You can use an f-string to substitute values into a string template using curly braces . For example: {} name = "John" age = 30 message = f"My name is {name} and I am {age} years old." Here, the variables and are enclosed in curly braces within the string literal, and the values will be interpolated into the string. name age In addition to string formatting, Python also provides several built-in string methods that can be used to manipulate strings. Some commonly used string methods in Python include: : Converts all characters in a string to uppercase. str.upper() : Converts all characters in a string to lowercase. str.lower() : Removes whitespace (spaces, tabs, and newlines) from the beginning and end of a string. str.strip() : Splits a string into a list of substrings based on a specified separator. str.split() : Joins a list of strings into a single string, using a specified separator. str.join() : Replaces all occurrences of a specified substring in a string with another substring. str.replace() : Returns if a string starts with a specified substring, otherwise . str.startswith() True False : Returns if a string ends with a specified substring, otherwise . str.endswith() True False These are just a few of the many string methods available in Python. You can find more information on string methods in the Python documentation. Data Structures List In Python, a list is a collection of items, which can be of any data type, that are ordered and mutable (changeable). Lists are created by enclosing a comma-separated sequence of items within square brackets . [] For example: my_list = [1, 2, 3, "apple", "banana", "cherry"] Here, is a list that contains three integers and three strings. my_list You can access individual items in a list by their index, which starts at 0 for the first item in the list. For example: print(my_list[0]) # prints 1 print(my_list[3]) # prints "apple" You can also use negative indexing to access items from the end of the list. For example: print(my_list[-1]) # prints "cherry" print(my_list[-3]) # prints "apple" Lists in Python support several built-in methods for adding, removing, and manipulating items. Some commonly used list methods include: : Adds an item to the end of the list. list.append(item) : Inserts an item at a specified position in the list. list.insert(index, item) : Removes the first occurrence of an item from the list. list.remove(item) : Removes and returns the item at a specified position in the list. list.pop(index) : Sorts the items in the list in ascending order. list.sort() : Reverses the order of the items in the list. list.reverse() : Returns the number of items in the list. len(list) You can also use slicing to extract a subsequence of a list. Slicing uses the colon operator to specify a start index (inclusive) and end index (exclusive) for the subsequence. For example: : my_list = [1, 2, 3, 4, 5] sub_list = my_list[1:4] # returns [2, 3, 4] Lists in Python are versatile and widely used in many applications. They can be used to store collections of data, implement algorithms, and represent complex structures. Tuple In Python, a tuple is an ordered, immutable (unchangeable) collection of elements. Tuples are similar to lists, but they cannot be modified once created. Tuples are created by enclosing a comma-separated sequence of values within parentheses . () For example: my_tuple = (1, 2, 3, "apple", "banana", "cherry") Here, is a tuple that contains three integers and three strings. my_tuple You can access individual elements in a tuple by their index, just like in a list. For example: print(my_tuple[0]) # prints 1 print(my_tuple[3]) # prints "apple" However, because tuples are immutable, you cannot modify their elements once they have been created. For example, the following code will raise a : TypeError my_tuple[0] = 4 # raises TypeError: 'tuple' object does not support item assignment Tuples in Python support several built-in methods for manipulating and querying elements. Some commonly used tuple methods include: : Returns the number of times a specified value appears in the tuple. tuple.count(value) : Returns the index of the first occurrence of a specified value in the tuple. tuple.index(value) : Returns the number of elements in the tuple. len(tuple) Because tuples are immutable, they are often used to represent fixed collections of data that should not be modified, such as the coordinates of a point in 2D space or the RGB values of a color. Tuples are also commonly used to return multiple values from a function, where the values cannot be modified separately. For example: def get_name_and_age(): name = "John" age = 30 return name, age result = get_name_and_age() print(result) # prints ("John", 30) Here, the function returns a tuple containing two values: the name and age of a person. The tuple is unpacked into the variables , which contains the two values as separate variables. get_name_and_age() result Set In Python, a set is an unordered collection of unique elements. Sets are created by enclosing a comma-separated sequence of values within curly braces or by using the constructor function. {} set() For example: my_set = {1, 2, 3, 4, 4, 5} Here, is a set that contains five unique integers. my_set Sets in Python support several built-in methods for adding, removing, and manipulating elements. Some commonly used set methods include: : Adds an element to the set. set.add(element) : Removes an element from the set. Raises a if the element is not in the set. set.remove(element) KeyError : Removes an element from the set if it is present. Does not raise an error if the element is not in the set. set.discard(element) : Removes and returns an arbitrary element from the set. set.pop() : Removes all elements from the set. set.clear() : Returns a new set that contains all elements from both sets. set.union(other_set) : Returns a new set that contains only the elements that are common to both sets. set.intersection(other_set) : Returns a new set that contains only the elements that are in the first set but not in the second set. set.difference(other_set) : Returns a new set that contains only the elements that are in either the first or the second set, but not both. set.symmetric_difference(other_set) : Returns the number of elements in the set. len(set) Sets in Python are often used to perform mathematical set operations such as union, intersection, and difference. They are also useful for removing duplicates from a list or other sequence. For example: my_list = [1, 2, 3, 4, 4, 5] my_set = set(my_list) print(my_set) # prints {1, 2, 3, 4, 5} Here, the constructor is used to create a set from the list, which contains duplicate elements. The resulting set contains only the unique elements from . set() my_list my_set my_list Dictionary In Python, a dictionary is an unordered collection of key-value pairs. Dictionaries are created by enclosing a comma-separated sequence of key-value pairs within curly braces or by using the constructor function. {} dict() For example: my_dict = {"apple": 2, "banana": 3, "cherry": 5} Here, is a dictionary that maps the keys "apple", "banana", and "cherry" to the values 2, 3, and 5, respectively. my_dict You can access individual values in a dictionary by their key, like this: print(my_dict["apple"]) # prints 2 You can also add new key-value pairs to a dictionary, like this: my_dict["orange"] = 4 You can modify the value associated with a key in a dictionary, like this: my_dict["banana"] = 6 And you can remove a key-value pair from a dictionary, like this: del my_dict["cherry"] Dictionaries in Python support several built-in methods for manipulating and querying keys and values. Some commonly used dictionary methods include: : Returns a view of the keys in the dictionary. dict.keys() : Returns a view of the values in the dictionary. dict.values() : Returns a view of the key-value pairs in the dictionary. dict.items() : Returns the value associated with a key in the dictionary, or a default value if the key is not present. dict.get(key, default=None) : Removes and returns the value associated with a key in the dictionary, or a default value if the key is not present. dict.pop(key, default=None) : Adds all key-value pairs from to the dictionary, overwriting values for keys that already exist in the dictionary. dict.update(other_dict) other_dict : Returns the number of key-value pairs in the dictionary. len(dict) Dictionaries in Python are often used to represent collections of related data where each element is identified by a unique key. They are also useful for counting the occurrences of elements in a sequence, and for performing lookups based on keys rather than indices. Function In Python, a function is a block of reusable code that performs a specific task. Functions are defined using the keyword, followed by the function name, parentheses , and a colon . The body of the function is indented below the function definition. def () : For example: def greet(name): print("Hello, " + name + "!") Here, is a function that takes a parameter and prints a greeting message. greet name You can call a function by using its name followed by parentheses, like this: greet("Alice") # prints "Hello, Alice!" Functions can have multiple parameters, and you can provide default values for some or all of the parameters. For example: def calculate_sum(a, b=0): return a + b Here, is a function that takes two parameters, and , with a default value of 0 for . The function returns the sum of and . calculate_sum a b b a b You can call a function with default parameter values by omitting the corresponding arguments, like this: print(calculate_sum(5)) # prints 5 print(calculate_sum(5, 10)) # prints 15 Functions can also return values using the keyword. For example: return def calculate_product(a, b): return a * b Here, is a function that takes two parameters, and , and returns their product. calculate_product a b You can call a function that returns a value and use its return value in an expression, like this: result = calculate_product(3, 4) print(result) # prints 12 Functions in Python can be used to break down complex problems into smaller, more manageable parts, and to organize code for better readability and maintainability. They are a fundamental building block of Python programming and are used extensively in Python applications. Conditionals Conditionals in Python allow you to execute different blocks of code depending on whether certain conditions are true or false. The most commonly used conditional statement in Python is the statement. if Here is an example of an statement in Python: if x = 5 if x > 0: print("x is positive") In this example, the statement checks whether the value of is greater than zero. If the condition is true, the statement is executed, and "x is positive" is printed to the console. if x print You can also use an statement to execute a different block of code when the condition is false. else For example: x = -3 if x > 0: print("x is positive") else: print("x is non-positive") In this example, since is negative, the condition is false, and the block is executed instead. "x is non-positive" is printed to the console. x if else You can also use an (short for "else if") statement to test additional conditions after the initial statement. For example: elif if x = 0 if x > 0: print("x is positive") elif x < 0: print("x is negative") else: print("x is zero") In this example, since is zero, the first condition is false, and the condition is tested instead. Since is not negative either, the block is executed instead. "x is zero" is printed to the console. x if elif x else Conditionals in Python can also use logical operators such as , , and to combine multiple conditions. For example: and or not x = 10 if x > 0 and x < 100: print("x is a positive two-digit number") In this example, the condition checks whether is both greater than zero and less than 100. If the condition is true, the statement is executed. if x print Conditionals in Python are a powerful tool for controlling program flow and making decisions based on different situations. They are used extensively in Python programs to implement logic and make decisions based on user input, data values, and other factors. Loops In Python, loops allow you to execute a block of code multiple times. There are two types of loops in Python: loops and loops. for while A loop is used to iterate over a sequence of values, such as a list or a string. for Here is an example of a loop in Python: for fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) In this example, the loop iterates over the list of fruits and prints each one to the console. for A loop is used to execute a block of code repeatedly as long as a certain condition is true. while Here is an example of a loop in Python: while i = 0 while i < 5: print(i) i += 1 In this example, the loop prints the value of to the console and increments it by 1 each time, until is no longer less than 5. while i i You can also use the and statements to control the flow of a loop. The statement allows you to exit a loop prematurely, while the statement allows you to skip over certain iterations of a loop. For example: break continue break continue for i in range(10): if i == 5: break elif i % 2 == 0: continue print(i) In this example, the loop prints the values of from 0 to 9, but it uses the statement to exit the loop prematurely when is equal to 5. It also uses the statement to skip over even values of . for i break i continue i Loops in Python are a powerful tool for iterating over sequences of values, executing code repeatedly, and controlling program flow. They are used extensively in Python programs to implement logic and perform tasks such as data processing, file I/O, and user interaction. Module In Python, a module is a file containing Python code that can be imported into other Python scripts or modules. Modules provide a way to organize code into reusable units and avoid name collisions between different parts of a program. To use a module in Python, you simply import it using the statement. Here is an example of how to import the module, which provides mathematical functions such as trigonometric and logarithmic functions: import math import math print(math.sqrt(25)) # prints 5.0 print(math.sin(math.pi / 2)) # prints 1.0 In this example, we import the module and use its and functions to calculate the square root of 25 and the sine of pi/2, respectively. math sqrt sin You can also import specific functions or variables from a module using the keyword. For example: from from math import sqrt, pi print(sqrt(25)) # prints 5.0 print(pi) # prints 3.141592653589793 In this example, we import only the and functions from the module, which allows us to use them directly without having to prefix them with . sqrt pi math math. Python also comes with a large standard library of modules that provide a wide range of functionality, such as file I/O, network communication, and GUI programming. In addition, there are many third-party modules available from the Python Package Index (PyPI) that can be installed using the package manager. pip Modules in Python are a powerful tool for organizing and reusing code, and they provide a convenient way to extend the functionality of the language. By importing modules, you can leverage existing code and focus on solving your specific programming problems. Classes and Objects In Python, a class is a blueprint or template for creating objects, which are instances of the class. A class defines a set of attributes and methods that describe the behavior of objects created from that class. Here is an example of a simple class in Python: class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") In this example, we define a class with two attributes ( and ) and one method ( ). The method is a special method that is called when an object of the class is created. It initializes the and attributes with the values passed as arguments. Person name age say_hello __init__ name age To create an object from the class, we can use the following syntax: Person person1 = Person("Alice", 25) person2 = Person("Bob", 30) In this example, we create two objects ( and ) from the class with different values for the and attributes. person1 person2 Person name age We can call the method on each object to display a greeting: say_hello person1.say_hello() # prints "Hello, my name is Alice and I am 25 years old." person2.say_hello() # prints "Hello, my name is Bob and I am 30 years old." In this example, we call the method on each object to display a personalized greeting. say_hello Classes and objects are a fundamental concept in object-oriented programming (OOP) and are used extensively in Python programs to organize code and implement complex systems. By defining classes, you can create reusable code that can be easily modified and extended, and by creating objects, you can model real-world entities and manipulate them in your program. Conclusion In conclusion, Python is a versatile and powerful programming language with a wide range of features and applications. By mastering the basics, such as variables, data types, string formatting, data structures, functions, conditionals, loops, modules, and classes, you can unlock the full potential of Python and become a proficient developer. Whether you are a beginner or looking to enhance your skills, understanding these fundamental concepts will provide a strong foundation for your Python development journey. In this series, you'll be learning Python in-depth starting from variables to Object Oriented Programming. At the end of this series, you'll be a proficient Python programmer, who'll know how to write optimized code.