Table of Contents
Introduction
Welcome back to the second part of our comprehensive guide to Python programming for beginners. In Part 1, we discussed the process of installing Anaconda and Python packages to create a Python execution environment. If you haven’t had the chance to read it yet, we highly suggest taking a look at it here. In this article, we will focus on the very basic syntax of Python, which is crucial for understanding the language. So let’s get started!
How to Run Jupyter Notebook on a Windows
Before we dive into exploring Jupyter Notebook and running your first code, let’s walk through the necessary steps to open Jupyter Notebook. If you haven’t installed it yet, please refer to my previous article [link to the previous article] for detailed instructions on installation. Once you have it installed, follow the steps below to get started.
Note: For installing Jupyter Notebook without Anaconda, please consult the following link for step-by-step instructions link
As mentioned earlier, Jupyter Notebook is an excellent tool for learning Python, especially for beginners. However, if you haven’t installed Anaconda and prefer to use a different integrated development environment (IDE), you have the freedom to choose the IDE that suits your preferences. Feel free to explore and select the IDE that best fits your needs.
Now that you have Anaconda installed, you can launch Jupyter Notebook:
To access Jupyter Notebook, simply enter “Jupyter” in the search box on your Windows. Locate and click on the Jupyter Notebook app, as demonstrated in the image below.
This action will initiate the launch of Jupyter Notebook, opening it in your default web browser for immediate usage.
In the Jupyter Notebook interface, you can navigate through your file system, create new notebooks, and open existing ones.
To initiate the creation of a fresh notebook, navigate to the “New” button and opt for “Python 3” from the provided dropdown menu. By selecting this option, a brand new notebook will be generated, enabling you to seamlessly compose and execute Python code within its interface.
Using Jupyter Notebook
Jupyter Notebook provides a web-based interface where you can write and run code cells, add text and visualizations, and document your analysis. Discover the essential features and expert tips that will kickstart your journey:
To add a new cell, click the “+” button on the toolbar or use the keyboard shortcut B (for inserting a new cell below) or A (for inserting a new cell above).
Heading cells in Jupyter Notebook play a crucial role in organizing and structuring your code and documentation. These specialized cells allow you to create headings and subheadings, providing a hierarchical structure to your notebook. By utilizing heading cells, you can effectively divide your notebook into logical sections, making it easier to navigate and understand the flow of your code. Whether you’re outlining different sections of your analysis, documenting steps, or providing explanations, heading cells enhance the readability and organization of your Jupyter Notebook, facilitating a seamless and cohesive user experience.
Markdown cells allow you to add text, headers, and formatted content to your notebook. To change a cell to Markdown mode, select it and click on the dropdown menu in the toolbar to change the cell type.
Each notebook consists of multiple cells. You can execute a cell by clicking the “Run” button or pressing Shift+Enter. The output, if any, will be displayed below the cell.
Jupyter Notebook supports code completion, syntax highlighting, and other helpful features to enhance your coding experience. Use the Tab key for code completion and Shift+Tab for accessing documentation or function signatures.
Remember to save your notebook periodically using the “Save” button or by pressing Ctrl+S.
Explore the world of Jupyter Notebook, experiment with code, and enjoy the flexibility and interactivity it offers for your programming projects!
Note: You can access the Jupyter file containing all the example code in the download section of this blog post. It serves as a valuable resource to accompany and enhance your learning experience.
Python Syntax: The Basics
Let’s start by exploring the fundamentals of Python programming, including its syntax and the importance of proper indentations.
Python boasts a straightforward and easily understandable syntax, which positions it as an ideal programming language for individuals who are new to coding. Understanding the basic syntax is essential as it forms the building blocks of any Python program. Let’s explore some fundamental aspects:
1.1 Variables and Data Types
Basics of Variables and Data Type
In Python, you can assign values to variables using the equals (=) operator. Variables can hold various types of data, such as numbers, strings, and boolean values.
# Assigning values to variables
name = "John"
age = 25
is_student = True
PythonPython supports several data types, including:
- Integers: Whole numbers without decimal points (e.g., 5, -10, 0).
- Floats: Numbers with decimal points (e.g., 3.14, -0.5, 2.0).
- Strings: Ordered sequences of characters enclosed in quotes (e.g., “Hello”, ‘Python’, “42”).
- Booleans: Represents either True or False.
1.2 Comments
Including comments in your code is vital as they serve the purpose of documenting your code and providing additional explanations. In Python, you can add comments using the hash (#) symbol. These comments are ignored by the Python interpreter and are solely for human readers.
# This is a comment
Python1.3 Printing Output
The ‘print()‘ function in Python allows you to display output to the console. It is a useful tool for debugging and displaying information during program execution.
print("#### This is my first line of code")
Python1.4 Indentation
Python uses indentation to define blocks of code. Proper indentation is crucial for the correct execution of your program. It is recommended to use four spaces or one Tab for each indentation level.
x = 23
if x > 0:
print("Positive number")
else:
print("Negative number")
Python1.5 Conditional Statements
Conditional statements, such as ‘if‘, ‘else‘, and ‘elif‘, enable you to execute different blocks of code based on specific conditions.
age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("As of now, you do not meet the eligibility criteria to exercise your voting rights.")
Python1.6 Loops
Loops in Python enable the execution of a code block repeatedly. There are two types of loops available: the ‘for’ loop and the ‘while‘ loop.
The ‘for’ loop is suitable for scenarios where the number of iterations is known in advance, allowing you to iterate over a sequence or range of values. On the other hand, the ‘while‘ loop is utilized when the number of iterations is uncertain and depends on a specific condition that determines when the loop should stop executing. With these looping constructs, Python offers versatile tools to handle repetitive tasks efficiently and dynamically.
# Example of a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Python# Example of a while loop
count = 0
while count < 5:
print("Count:", count)
count += 1
PythonNote: While I have covered advanced topics in this section, please feel free to proceed at your own pace. If you find it overwhelming, take it step by step. Rest assured, we will revisit these advanced concepts when we get into Data Structures and Object oriented programming in python, ensuring a comprehensive understanding in due time.
Diving deeper into each of these subjects:
Variables and Data Type
Exploration of intermediate concepts in Variables and Data Types
Variables:
Within the realm of python programming, variables serve as essential entities responsible for storing and facilitating the manipulation of data, allowing for seamless data management and transformation. In the Python programming language, the assignment operator (=) allows you to assign values to variables effortlessly.
variable_name = value
PythonHere, variable_name
represents the name you choose for your variable, and value
is the data or information you want to assign to that variable.
For example:
age = 25
name = "John"
is_student = True
PythonIn this code, we assign the value “John” to the variable name, the value 25 to the variable age, and the value True to the variable is_student.
Python is a dynamically typed language, which means that you do not need to explicitly declare the type of a variable. In Python, the data type of a variable is automatically determined based on the assigned value, allowing for dynamic typing and flexibility in programming.
You can also assign the result of an expression or a calculation to a variable.
For instance:
radius = 5
pi = 3.14
area = pi * (radius ** 2)
PythonIn this example, we assign the result of the expression pi * (radius ** 2) to the variable area. The expression calculates the ‘area’ of a circle with a given radius.
It’s important to note that variables in Python are case-sensitive. This means that ‘name‘, ‘Name‘, and ‘NAME‘ would be treated as three different variables.
Furthermore, variables can be reassigned with new values as needed:
name = "John"
name = "Alice"
PythonIn this case, the variable ‘name
‘ is initially assigned the value "John"
, but then it is reassigned the value "Alice"
. The latest assignment overwrites the previous value.
In Python, you do not need to explicitly reserve memory for variables. Python handles memory management automatically through a process known as automatic memory allocation and garbage collection.
When you assign a value to a variable in Python, the interpreter automatically allocates memory to store that value. The memory allocation is dynamic and adjusts as needed based on the type and size of the assigned value.
Python utilizes a reference counting mechanism to keep track of the number of references to an object in memory. When the reference count of an object reaches zero, meaning there are no more references to it, Python’s garbage collector frees up the memory occupied by that object.
This automatic memory management in Python provides convenience to developers, as they do not need to worry about explicitly allocating or de-allocating memory for variables. Python takes care of memory management behind the scenes, allowing programmers to focus on writing their code.
It’s worth noting that although Python handles memory management, understanding memory usage and optimizing code for efficient memory utilization can still be beneficial, especially for handling large datasets or optimizing performance in memory-intensive applications.
Data Types:
Python programming supports various data types to represent different kinds of information. Some commonly used data types in Python 3 include:
- Integers:
- Integers, is an essential data type in Python, represent whole numbers without any decimal components.
For instance:
age = 25
Python- Floats:
- Floats represent numbers with decimal points.
For example:
pi = 3.14
Python- Strings:
- Strings, a fundamental data type in Python, are sequences of characters encompassed within either single or double quotation marks. They are used to represent text.
For instance:
name = "John"
Python- Booleans:
- Booleans can have either of two values: True or False. They are commonly used in conditions and logical operations.
For example:
is_student = True
PythonIn Python, there are several built-in data structures that allow you to store and organize collections of data. Now, let’s delve into each of these concepts extensively:
Lists:
Lists, as versatile data structures in Python, are meticulously organized collections of elements enclosed within square brackets ([]), providing seamless accessibility and manipulation capabilities. They can contain elements of different data types and are mutable, meaning you can modify the items they hold. For example:
fruits = ["apple", "banana", "cherry"]
PythonYou can access elements in a list by their index, starting from 0. Lists support various operations such as appending, inserting, removing, and slicing.
Tuples:
Tuples, akin to lists in Python, exhibit the quality of immutability, signifying that their elements remain unalterable once initially established, enabling secure and reliable data storage. They are defined using parentheses (()) or can be created without any enclosing brackets. Tuples are commonly used when you want to ensure data integrity or create a collection that should not be changed. For example:
coordinates = (10, 20)
PythonTuples support similar operations as lists, such as indexing and slicing, but do not allow modification of individual elements.
Dictionaries:
Dictionaries are key-value pairs enclosed in curly braces ({}). They provide an efficient way to store and retrieve data based on unique keys. Keys can be of any immutable type, such as strings or numbers, while the associated values can be of any data type. For example:
student = {"name": "John", "age": 20, "grade": "A"}
PythonYou can access values in a dictionary by their corresponding keys. Dictionaries support operations like adding new key-value pairs, modifying existing values, and deleting entries.
Sets:
Sets, dynamic data structures in Python, epitomize the concept of unordered collections, housing exclusively distinct elements within their confines, all enclosed gracefully within curly braces ({}), facilitating efficient membership testing and eliminating duplicates. They are useful when you want to store a collection of items without any duplicates and perform set operations such as union, intersection, and difference. For example:
numbers = {1, 2, 3, 4, 5}
PythonSets support various operations like adding elements, removing elements, and performing set operations.
These data structuresโlists, tuples, dictionaries, and setsโprovide different capabilities and are suitable for specific use cases. Understanding their characteristics and choosing the appropriate data structure for your needs can greatly enhance your ability to work with collections of data in Python.
Remember, lists and dictionaries are mutable, allowing you to modify their elements, while tuples are immutable, providing data integrity. Sets ensure uniqueness and provide set operations. Each of these data structures offers its own advantages and can be leveraged based on the requirements of your program.
Note: While I have covered advanced topics in this section, please feel free to proceed at your own pace. If you find it overwhelming, take it step by step. Rest assured, we will revisit these advanced concepts when we delve into Object-oriented programming in python and Data Structures, ensuring a comprehensive understanding in due time.
Advance Topic explanation of Variables and Data Type
In addition to the basics and intermediate, there are advanced topics worth exploring in variables and data types in Python. Let’s get into these concepts to expand our understanding:
Variable Scope
Variable scope refers to the portion of the program where a variable is accessible. Python has two primary variable scopes: global and local. Variables that are defined outside the boundaries of any specific function possess a global scope, granting them unrestricted accessibility from any part of the program, thereby fostering seamless data flow and utilization. On the other hand, variables defined inside a function have a local scope and are only accessible within that function.
Consider the following example:
x = 10 # Global variable
def my_function():
y = 20 # Local variable
print(x) # Accessing global variable
print(y) # Accessing local variable
my_function()
PythonIn this case, ‘x’ is a global variable accessible within the function ‘my_function()’. The local variable ‘y‘ is only accessible within the function. Understanding variable scope helps ensure proper usage and avoid naming conflicts.
In the context of class objects, variable scope refers to the accessibility of variables within different parts of a class. Consider the following example:
class Car:
global_brand = "Ford" # Class variable
def __init__(self, model):
self.model = model # Instance variable
def display_car(self):
print("Brand:", Car.global_brand) # Accessing class variable
print("Model:", self.model) # Accessing instance variable
car1 = Car("Mustang")
car1.display_car()
PythonIn this example, ‘global_brand ‘ is a class variable accessible by all instances of the ‘Car‘ class. The ‘model‘ variable is an instance variable, unique to each instance of the class.
Variable Lifetime
The lifetime of a variable is the duration during which it exists in the memory. Global variables have a lifetime equal to the execution time of the program. Local variables, however, have a shorter lifetime and are created when the function is called and destroyed when the function execution ends.
Let’s look at an example:
def my_function():
name = "John"
print(name)
my_function()
# print(name) # This line will result in an error
PythonIn this example, the variable ‘name ‘ has a local scope within the ‘my_function()‘ function. It exists and can be accessed only during the execution of the function. After the function finishes executing, the variable name is destroyed, and trying to print it outside the function would result in an error.
In class objects, the lifetime of variables is tied to the lifetime of the object itself. When an instance of a class is created, the instance variables are initialized and exist as long as the instance is alive. Here’s an example:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display_info(self):
print("Product:", self.name)
print("Price:", self.price)
product = Product("Phone", 999.99)
product.display_info()
PythonIn this example, the ‘name ‘and ‘price ‘variables are instance variables that exist as long as the ‘product ‘object exists. Once the object is no longer referenced, the instance variables are destroyed by the garbage collector.
Type Conversion
Type conversion, also known as type casting, allows you to convert a variable from one data type to another. Python provides built-in functions like int(), float(), str(), and bool() to perform type conversion. This flexibility in type conversion enables you to handle different data types and perform operations accordingly.
Consider this example:
x = 10
y = "20"
sum = x + int(y) # Converting y to an integer
print(sum) # Output: 30
PythonIn this example, the string value “20” is converted to an integer using the ‘int()‘ function. Type conversion allows you to handle different data types and perform operations accordingly.
Type conversion can be applied to class objects by defining appropriate methods. Here’s an example:
class Distance:
def __init__(self, meters):
self.meters = meters
def to_feet(self):
return self.meters * 3.281
distance = Distance(10)
feet = distance.to_feet()
print(feet)
PythonIn this example, the Distance class has a method to_feet() that converts distance from meters to feet. By invoking this method on an instance of the class, we can perform the type conversion.
Type Inference
Python, a dynamically typed programming language, presents the advantage of not requiring explicit declaration of variable data types. By intelligently deducing the data type from the assigned value, Python bestows programmers with unparalleled flexibility and effortless usage, streamlining the development process..
Here’s an example showcasing type inference:
x = 10 # Integer
y = 3.14 # Float
z = "Hello" # String
print(type(x)) # Output:Integer
print(type(y)) # Output:Float
print(type(z)) # Output:String
PythonPython infers the data types of variables x, y, and z based on the values assigned to them.
Type inference in class objects works similarly to other variables. The data type of instance variables is inferred based on the assigned values. Here’s an example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
student = Student("John", 20)
student.display_info()
PythonIn this example, the ‘name ‘ variable is an instance variable of ‘string‘ type, and the ‘age‘ variable is an instance variable of ‘integer‘ type. Their data types are inferred based on the assigned values.
Immutable and Mutable Types
Some data types in Python, like strings and tuples, are immutable, meaning their values cannot be changed after creation. On the other hand, lists and dictionaries are mutable, allowing you to modify their elements. Understanding the distinction between mutable and immutable types is crucial for managing data effectively.
Let’s explore an example:
fruit = "apple" # Immutable string
numbers = [1, 2, 3] # Mutable list
fruit = "banana" # Reassigning a new value to the immutable variable
numbers.append(4) # Modifying the mutable list
print(fruit) # Output: banana
print(numbers) # Output: [1, 2, 3, 4]
PythonIn this example, the string variable ‘fruit‘ is immutable, so when we assign a new value, it creates a new string object. However, the list variable ‘numbers‘ is mutable, allowing us to modify it by appending a new element.
Class objects can utilize both immutable and mutable data types such as ‘lists‘, ‘tuples‘, ‘dictionaries‘, and ‘sets‘. For example:
class ShoppingCart:
def __init__(self):
self.items = [] # Mutable list
self.details = {} # Mutable dictionary
self.options = ("Option 1", "Option 2") # Immutable tuple
self.products = set(["Product 1", "Product 2"]) # Mutable set
def add_item(self, item):
self.items.append(item)
def add_detail(self, key, value):
self.details[key] = value
cart = ShoppingCart()
cart.add_item("Item 1")
cart.add_detail("key", "value")
print(cart.items) # Output: ["Item 1"]
print(cart.details) # Output: {"key": "value"}
print(cart.options) # Output: ("Option 1", "Option 2")
print(cart.products) # Output: {"Product 1", "Product 2"}
PythonIn this example, ‘items‘ and ‘details‘ are mutable ‘list‘ and ‘dictionary‘ instances, respectively. ‘options‘ is an immutable ‘tuple‘, and ‘products‘ is a mutable ‘set‘.
Variable Unpacking
Variable unpacking in Python emerges as a convenient and efficient attribute, empowering developers to effortlessly assign multiple values from a sequence to distinct variables within a concise line of code, streamlining the assignment process and enhancing code readability and efficiency. This technique is particularly useful when working with functions that return multiple values or when iterating over collections.
Let’s see an example of variable unpacking:
coordinates = (10, 20)
x, y = coordinates # Unpacking the tuple into individual variables
print(x) # Output: 10
print(y) # Output: 20
PythonIn this example, the values from the ‘coordinates‘ tuple are unpacked into the variables ‘x‘ and ‘y‘ in a single line, simplifying the assignment process.
Variable unpacking can be used with class objects, including lists, tuples, dictionaries, and sets. Here’s an example:
class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
employee_data = ["John Doe", 30, 5000]
employee = Employee(*employee_data)
print(employee.name, employee.age, employee.salary)
PythonIn this example, the values from the ‘employee_data‘ list are unpacked and assigned to the respective instance variables of the Employee object.
Variable Swapping
Python provides a concise way to swap the values of two variables without using a temporary variable. This can be achieved by assigning the values simultaneously in a single line.
For example:
a = 10
b = 20
a, b = b, a # Swapping the values of a and b
print(a) # Output: 20
print(b) # Output: 10
PythonIn this example, the values of a and b are swapped without using a temporary variable. This concise syntax simplifies the process of swapping values between variables.
Variable swapping can also be applied to class objects, including lists, tuples, dictionaries, and sets. Here’s an example:
class Shape:
def __init__(self, sides):
self.sides = sides
def swap_sides(self):
self.sides[0], self.sides[1] = self.sides[1], self.sides[0]
shape = Shape([4, 6, 8])
shape.swap_sides()
print(shape.sides) # Output: [6, 4, 8]
PythonIn this example, the ‘swap_sides()‘ method swaps the values of the first and second elements in the sides list of the Shape object.
By exploring these advanced topics in variables and data types with respect to class objects, including lists, tuples, dictionaries, and sets, you gain a deeper understanding of their practical usage. These concepts allow for flexible and efficient handling of data within class-based programs, enabling you to build robust and versatile applications.
To be Continued:
In our upcoming blog post, we will delve deeper into additional topics, expanding our understanding and exploring new avenues of knowledge. Stay tuned for more insightful content and exciting discoveries in the world of python programming.
Downloads
To make the most of your learning journey, we encourage you to download the provided Jupyter notebook .ipynb (ziped) file. By saving it in your repository and opening it locally, you gain the flexibility to explore, experiment, and engage with the content firsthand. Unleash your creativity and deepen your understanding as you dive into the interactive world of Jupyter notebooks.
Conclusion
In this second part of our Python programming guide for beginners, we covered the very basic syntax of the language. Understanding variables, data types, comments, printing output, indentation, conditional statements, and loops is crucial for building a solid foundation in Python.
In conclusion, the advanced topics covered in variables and data types, along with their application in class objects, provide valuable insights into the versatility and flexibility of Python programming. Understanding concepts such as variable scope, lifetime, type conversion, type inference, immutable and mutable types, variable unpacking, and variable swapping empowers developers to effectively manage and manipulate data within their programs.
By exploring real-time examples, we’ve witnessed how these concepts come to life in practical scenarios. Whether it’s accessing variables within different scopes, ensuring the lifetime of variables aligns with the lifespan of objects, converting types to perform desired operations, inferring types for efficient coding, leveraging immutable and mutable types for different data manipulation needs, unpacking values for streamlined assignments, or swapping variable values for reordering and reconfiguring data, these advanced topics enhance the power and flexibility of Python programming.
Applying these concepts to class objects, including lists, tuples, dictionaries, and sets, further extends their applicability. Variables within class objects allow for efficient data management, encapsulation, and manipulation, while utilizing various data structures enables developers to organize and process data in different ways, catering to specific requirements of their applications.
Mastering these advanced topics empowers programmers to write code that is more readable, maintainable, and adaptable. By harnessing the capabilities offered by variables and data types in Python, developers can create powerful and efficient programs that handle complex data structures, support dynamic operations, and meet diverse programming needs.
In essence, the exploration of these advanced topics highlights the breadth and depth of Python’s capabilities, solidifying its position as a versatile and popular programming language. By understanding and effectively utilizing variables and data types, programmers can unlock the full potential of Python, enabling the development of sophisticated applications and solutions.
By practicing these fundamental concepts, you are on your way to mastering Python and unlocking its vast potential. In the next part of our series, we will explore more advanced topics, building upon the knowledge gained so far.
Remember, learning programming is a journey, and patience and practice are key. Keep exploring, experimenting, and building exciting projects. Happy coding!
Note: This article is part of a series. If you haven’t already, make sure to check out Part 1 of our Python programming guide for beginners, where we discussed the installation process of Anaconda and Python packages to create a Python execution environment.