Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Python Beginners Tutorial - Zero To Hero for Beginners

Python Beginners Tutorial - Zero To Hero for Beginners



What is Python Programming ?

Python is a high-level, interpreted programming language that is widely used for web development, data analysis, artificial intelligence, scientific computing, and many other applications. It is designed to be easy to read and write, and it has a large and active community that contributes to its development and maintenance.

Python was first released in 1991 by Guido van Rossum and has since grown in popularity due to its simple and expressive syntax, its support for multiple programming paradigms (such as object-oriented, functional, and procedural), and its vast collection of libraries and modules.

Python code is executed line by line, and it can be used to perform a wide range of tasks, from simple scripts to more complex software applications. It supports multiple programming paradigms such as object-oriented, functional and procedural programming. Python is also widely used for scripting and automation tasks, as well as for building web applications and data analysis.

Python is an open-source programming language, which means that it can be used, modified, and distributed freely. There are many libraries, frameworks, and tools available for Python, which makes it a very versatile and powerful programming language.

In summary, Python is a general-purpose, high-level programming language that is widely used for web development, data analysis, artificial intelligence, scientific computing, and many other applications. It is designed to be easy to read and write, and it has a large and active community that contributes to its development and maintenance.

Installing Python on MacOS / Macbook

There are several ways to install Python on a MacOS system, here are a couple of options:

Using the Python Package Installer (Homebrew):

You can use the package installer Homebrew to install Python on your MacOS system. First, you need to install Homebrew by running the following command in the terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then, you can install Python using the following command:

brew install python

This will install the latest version of Python on your system.

Using the Python.org installer:

You can also download the Python installer from the official Python website (https://www.python.org/downloads/mac-osx/) and run it on your system.

Using the macOS built-in Python:

macOS comes with Python pre-installed, but it is usually an older version. You can check the version of Python that is currently installed by running the following command in the terminal:

python --version

Once you've installed Python, you can verify the installation by running the python command in the terminal. You should see the Python REPL (Read-Eval-Print-Loop) where you can type commands and see the results immediately.

It is also recommended to use virtual environment while working with multiple projects and different version of python packages. You can use pipenv or conda to create virtual environment.

Installing Python on Windows 10 / 11

The process for installing Python on Windows 11 is the same as it is for other versions of Windows. You can go to the official Python website (python.org) and download the latest version of Python for Windows. 

Once the download is complete, run the installer and follow the prompts to install Python on your computer. Once the installation is complete, you can verify that Python was installed correctly by opening the Command Prompt and typing "python" (without the quotes). If the installation was successful, you should see the version of Python that you installed displayed in the terminal.

Please note, installing Python on Windows 11 is same as other windows version and you don't need any different steps or version of python.


Python IDEs - Development Environment

An Integrated Development Environment (IDE) is a software application that provides a comprehensive environment for software development. There are many IDEs available for Python, some of the most popular ones include:

PyCharm: Developed by JetBrains, PyCharm is a professional IDE for Python and web development. It includes features such as debugging, code completion, and version control integration.
  1. IDLE: IDLE is a simple IDE that comes with the Python standard library. It is a good option for beginners who are just starting to learn Python.
  2. Visual Studio Code: Visual Studio Code is a lightweight, cross-platform code editor that has great support for Python development through the use of extensions.
  3. Eclipse with PyDev: Eclipse is a popular Java IDE that can also be used for Python development through the PyDev plugin.
  4. Spyder: Spyder is a powerful open-source IDE for scientific computing and data science.
These are some of the most popular IDEs, but there are many other options available as well. The best IDE for you will depend on your specific needs and preferences.

Python Hello World Example

  # This is a simple Hello, World! program in Python.
  # The print function is used to display text on the screen
  
  print("Hello, World!")

This program uses the built-in
print() function to display the string "Hello, World!" on the screen. This is a classic example and often used as a starting point when learning a new programming language.

You can run this program by saving it to a file with a .py extension and then running it using the Python interpreter on the command line like so: python filename.py

 # This is a basic example of a Python program that performs simple math operations.
 # Assign values to variables
 x = 5
 y = 3
 
 # Perform math operations using the variables
 sum = x + y
 difference = x - y
 product = x * y
 quotient = x / y
 
 # Print the results
 print("x + y =", sum)
 print("x - y =", difference)
 print("x * y =", product)
 print("x / y =", quotient)

This program assigns values to two variables, x and y, and then performs some basic math operations using those variables. The results of the operations are then printed to the screen using the print() function.

Commenting in Python

Comments are used to explain what the code is doing and to make the code more readable.

There are two types of comments in Python:

Single-line comments: These comments start with the # symbol and continue until the end of the line.

# This is a single-line comment

Multi-line comments: These comments are used when a comment spans multiple lines and are created by using triple quotes (either single or double).

  """
  This is a 
  multi-line comment
  """

Comments are ignored by the Python interpreter and do not affect the execution of the program. It is a good practice to include comments in your code to make it more readable and understandable for others.

Example:

  # This program calculates the average of a list of numbers
  numbers = [1, 2, 3, 4, 5]

  # calculate the sum
  sum = 0
  for number in numbers:
  sum += number

  # calculate the average
  average = sum / len(numbers)

  # print the average
  print("The average is", average)

Here, the comments are used to explain what each part of the code is doing, making it easier to understand.

Python Variables

Python variable is a named location in memory that stores a value. Variables are used to store data in a program, and the data stored in a variable can be of different types, such as numbers, strings, lists, etc.

To create a variable, you need to give it a name and assign a value to it using the assignment operator =. The variable name must start with a letter or an underscore, and the rest of the characters can be letters, digits, or underscores.

  # Example of variable assignments
  x = 5 # variable x with integer value 5

  name = "John Doe" # variable name with string value "John Doe"
  pi = 3.14 # variable pi with float value 3.14

Once a variable is created, its value can be accessed and changed throughout the program.

  # Changing the value of a variable
  x = 5

  print(x) # prints 5
  x = 10

  print(x) # prints 10

Variables do not have to be declared with a specific data type, unlike other programming languages. The type of a variable is determined by the value that is assigned to it.

  x = 5 # x is an integer
  x = "hello" # x is now a string
  x = [1, 2, 3] # x is now a list

It is a good practice to use meaningful variable names that describe the data they store, making the code more readable.

  # Good variable names
  first_name = "John"
  last_name = "Doe"
  average_temperature = 72.5

  # Bad variable names
  x = "John"
  y = "Doe"
  z = 72.5

It's also worth noting that Python has some reserved keywords that cannot be used as variable names. For example,
print, if, else, for, while, def, etc. are reserved keywords in Python and can't be used as variable names.

Python Datatypes

In Python, data is stored in different types of variables, such as integers, floating-point numbers, strings, lists, dictionaries, etc. These data types are known as Python data types.

Here are some common Python data types:

Integers: Whole numbers, such as 1, 2, and 3.

x = 5

y = -10


Floating-point numbers: Numbers with decimal points, such as 3.14 and -2.5.

x = 3.14

y = -2.5


Strings: A sequence of characters, such as "hello" and "world". They can be created using single or double quotes.

x = "hello"

y = 'world'


Lists: An ordered collection of items, such as [1, 2, 3] and ["apple", "banana", "cherry"]. Lists are mutable, meaning their elements can be changed.

x = [1, 2, 3]

y = ["apple", "banana", "cherry"]


Tuples: An ordered collection of items, such as (1, 2, 3) and ("apple", "banana", "cherry"). Tuples are immutable, meaning their elements cannot be changed once created.

x = (1, 2, 3)

y = ("apple", "banana", "cherry")


Dictionaries: An unordered collection of key-value pairs, such as {"name": "John", "age": 30}.

x = {"name": "John", "age": 30}

y = {"fruit": ["apple", "banana", "cherry"]}


Booleans: A data type that has only two possible values, True and False.

x = True

y = False


The type() function can be used to check the data type of a variable.

x = 5
print(type(x)) #

y = "hello"
print(type(y)) #


In addition to the basic data types, Python also has some advanced data types such as sets and arrays. You can use them according to your requirements.

Python Operators

Python operators are symbols that perform operations on one or more operands. Operands are the values or variables on which the operations are performed.

Here are some common Python operators:

Arithmetic operators: perform mathematical operations such as addition, subtraction, multiplication, division, and modulus.

  x = 5
  y = 2

  # addition
  print(x + y) # 7

  # subtraction
  print(x - y) # 3

  # multiplication
  print(x * y) # 10

  # division
  print(x / y) # 2.5

  # modulus
  print(x % y) # 1

Assignment operators:
assign values to variables.

  x = 5
  y = 2

  x += y # x = x + y

  x -= y # x = x - y

  x *= y # x = x * y

  x /= y # x = x / y

  x %= y # x = x % y

Comparison operators: compare values and return a Boolean value.

  x = 5
  y = 2

  print(x == y) # False

  print(x != y) # True

  print(x > y) # True

  print(x = y) # True

  print(x 

Logical operators: perform logical operations such as and, or, and not.

  x = True
  y = False

  print(x and y) # False

  print(x or y) # True

  print(not x) # False

Identity operators: compare the memory location of two variables.

  x = [1, 2, 3]
  y = [1, 2, 3]
  z = x

  print(x is y) # False

  print(x is z) # True

  print(x is not y) # True      

Membership operators: check if an item is present in a sequence (e.g.
list, tuple, string, etc.).

  x = [1, 2, 3]
  y = 2

  print(y in x) # True

  print(y not in x) # False

These are some of the most commonly used operators in Python. There are also other specialized operators, such as bitwise operators and operator precedence, which can be used in more advanced programming scenarios.

Python Loops

Python loops are used to repeatedly execute a block of code. There are two types of loops in Python: for loops and while loops.

For Loops

A for loop is used to iterate over a sequence (such as a list, tuple, or string) or other iterable object. The syntax for a for loop is as follows:

for variable in iterable: # code to be executed

Here's an example of using a for loop to iterate over a list of numbers and print each one:

numbers = [1, 2, 3, 4, 5]

for num in numbers:
    print(num)        

While Loops

A while loop is used to repeatedly execute a block of code as long as a certain condition is true. The syntax for a while loop is as follows:

while condition: # code to be executed

Here's an example of using a while loop to repeatedly print "Hello, World!" until a variable counter reaches 5:

counter = 0

while counter     
print("Hello, World!") counter += 1

Control flow statements

Python provides several control flow statements such as break, continue, pass which can be used inside loops.

break statement is used to exit the loop prematurely when a certain condition is met.

for num in range(10):
    if num == 5:
        break
    print(num)

continue statement is used to skip the current iteration of the loop and move on to the next one.

for num in range(10):
    if num % 2 == 0:
        continue
    print(num)

pass statement is used as a placeholder and does nothing when executed.

for num in range(10):
    if num % 2 == 0:
        pass
    else:
        print(num)

These are the basic concepts of loops in Python. There are also more advanced concepts such as nested loops and loop control statements that can be used in more complex programming scenarios.

Python Numbers

Python numbers are used to represent numeric values in a program. Python supports several types of numbers, including:

Integers

Integers are whole numbers (positive or negative) that do not have a decimal component. For example, 1, -5, and 100 are all integers. In Python, integers can be of unlimited size.

Floating-point numbers

Floating-point numbers are numbers that have a decimal component. For example, 3.14, -0.01, and 1.0 are all floating-point numbers. Python uses the standard IEEE 754 floating-point representation for these numbers, which supports both single and double precision.

Complex numbers

Complex numbers are numbers that have both a real and an imaginary component. For example, 3 + 4j, -1 + 2j, and 0 + 1j are all complex numbers. The "j" in the number represents the imaginary component.

Boolean

Boolean values are used to represent true or false values in python. True and False are the two Boolean values in python.
Conversion

You can convert one data type to another using the following built-in functions:
  • int() - converts a number or a string to an integer
  • float() - converts a number or a string to a floating-point number
  • complex() - creates a complex number from a real and an imaginary component
  • bool() - converts a value to a Boolean

Example:

x = 5
y = 2.5
z = 1 + 2j

a = int(y)

b = float(x)

c = complex(x, y)

d = bool(z)

These are the basic types of numbers supported in Python. You can perform various mathematical operations on these numbers using built-in operators and functions, such as addition, subtraction, multiplication, division, etc.

Python Strings

In Python, strings are used to represent text and are enclosed in quotation marks (either single or double). Here are a few examples of strings in Python:

"Hello, World!"

'This is a string'

"12345"


You can use the + operator to concatenate strings, the * operator to repeat a string multiple times, and the [] operator to access a specific character in a string.

first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name

print(full_name) # John Doe

string = "Hello"

print(string * 3) # HelloHelloHello

string = "Python"

print(string[2]) # t

You can also use the [:] operator to slice a string and return a specific portion of the string

string = "Python"
print(string[1:4]) #yth

Python also provides several built-in functions for working with strings, such as:

len() - returns the number of characters in a string

str() - converts a value to a string

upper() - converts a string to uppercase

lower() - converts a string to lowercase

strip() - removes whitespace characters from the beginning and end of a string

You can also use the in operator to check if a substring is present in a string.

string = "Python is a programming language"
print("programming" in string) # True

There are also string formatting techniques in python like f-strings, format method, %-formatting etc.

Example of f-string :

name = "John"
age = 25

print(f"My name is {name} and I am {age} years old.")

Example of format method :

name = "John"
age = 25

print("My name is {} and I am {} years old.".format(name, age))

These are some of the basic concepts of strings in Python. There are also more advanced concepts such as string formatting, regular expressions, and string methods that can be used in more complex programming scenarios.

Python Lists

In Python, lists are used to store a collection of items. A list is created by placing a comma-separated sequence of items inside square brackets ([]). Here's an example of a list in Python:

fruits = ["apple", "banana", "orange"]

You can access items in a list by their index. Python uses zero-based indexing, so the first item in the list has an index of 0, the second item has an index of 1, and so on. Here's an example of accessing items in a list:

fruits = ["apple", "banana", "orange"]

print(fruits[0]) # "apple"

print(fruits[1]) # "banana"


You can use the + operator to concatenate lists, and the * operator to repeat a list multiple times.

fruits = ["apple", "banana"]
more_fruits = ["orange", "mango"]

all_fruits = fruits + more_fruits

print(all_fruits) # ['apple', 'banana', 'orange', 'mango']


fruits = ["apple"]

print(fruits * 3) # ['apple', 'apple', 'apple']

You can use the len() function to find the number of items in a list and the in operator to check if an item is in a list.

fruits = ["apple", "banana", "orange"]

print(len(fruits)) # 3

print("banana" in fruits) # True


You can also use the [:] operator to slice a list and return a specific portion of the list.

fruits = ["apple", "banana", "orange", "mango", "lemon"]

print(fruits[1:4]) # ['banana', 'orange', 'mango']


You can also change, add and remove items from a list using the following methods :

  • append(item) adds an item to the end of the list.
  • insert(index, item) inserts an item at the specified index.
  • remove(item) removes the first occurrence of the specified item.
  • pop() removes the item at the specified index (if no index is specified, the last item is removed).
  • sort() sorts the items of the list in ascending order.
  • reverse() reverses the order of the items in the list
Examples :

fruits = ["apple", "banana", "orange"]

fruits.append("mango")

print(fruits) # ['apple', 'banana', 'orange', 'mango']

fruits.insert(1,"kiwi")

print(fruits) # ['apple', 'kiwi', 'banana', 'orange', 'mango']

fruits.remove("kiwi")

print(fruits) # ['apple', 'banana', 'orange', 'mango']

fruits.pop(2)

print(fruits) # ['apple', 'banana', 'mango']

fruits.sort()

print(fruits) # ['apple', 'banana', 'mango']

fruits.reverse()

print(fruits) # ['mango', 'banana', 'apple']

Python Tuples

In Python, tuples are similar to lists, but they are immutable, meaning their values cannot be changed after they are created. A tuple is created by placing a comma-separated sequence of items inside parentheses (()). Here's an example of a tuple in Python:

fruits = ("apple", "banana", "orange")

You can access items in a tuple by their index, just like with lists. Python uses zero-based indexing, so the first item in the tuple has an index of 0, the second item has an index of 1, and so on. Here's an example of accessing items in a tuple:

fruits = ("apple", "banana", "orange")

print(fruits[0]) # "apple"
print(fruits[1]) # "banana"

You can also use the + operator to concatenate tuples, and the * operator to repeat a tuple multiple times.

fruits = ("apple", "banana")
more_fruits = ("orange", "mango")

all_fruits = fruits + more_fruits

print(all_fruits) # ('apple', 'banana', 'orange', 'mango')


fruits = ("apple",)

print(fruits * 3) # ('apple', 'apple', 'apple')


You can use the len() function to find the number of items in a tuple and the in operator to check if an item is in a tuple.

fruits = ("apple", "banana", "orange")

print(len(fruits)) # 3

print("banana" in fruits) # True

You can also use the [:] operator to slice a tuple and return a specific portion of the tuple.

fruits = ("apple", "banana", "orange", "mango", "lemon")

print(fruits[1:4]) # ('banana', 'orange', 'mango')

Since Tuples are immutable, you can't add, remove or change values of tuple after it is created.

fruits = ("apple", "banana", "orange")

fruits[1] = "kiwi" # This will raise a TypeError, as tuples are immutable

Because of its immutability, tuples can be used as keys in a dictionary, whereas lists cannot be used as dictionary keys.

Python Dictionary

Python dictionary is a collection of key-value pairs, where each key is unique. Dictionaries are also known as associative arrays or hash maps. They are enclosed in curly braces ({}) and are created by specifying keys and values, separated by colons (:). Here's an example of a dictionary in Python:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

You can access the value associated with a particular key using the square brackets ([]) notation:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print(person['name']) # 'John Doe'

You can add a new key-value pair to a dictionary using the square brackets ([]) notation:

person = {'name': 'John Doe', 'age': 30}
person['gender'] = 'male'

print(person) # {'name': 'John Doe', 'age': 30, 'gender': 'male'}

You can also use the del statement to remove a key-value pair from a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}
del person['gender']

print(person) # {'name': 'John Doe', 'age': 30}

You can use the in operator to check if a key is in a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print('name' in person) # True

You can use the len() function to find the number of items in a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print(len(person)) # 3

You can use the items() method to get a list of key-value pairs in a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print(person.items()) # [('name', 'John Doe'), ('age', 30), ('gender', 'male')]

You can use the keys() method to get a list of keys in a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print(person.keys()) # ['name', 'age', 'gender']

You can use the values() method to get a list of values in a dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}

print(person.values()) # ['John Doe', 30, 'male']

You can also use the update() method to merge two dictionaries together, where the keys in the second dictionary will overwrite the keys in the first dictionary if they already exist.

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}
address = {'city': 'New York', 'state': 'NY'}

person.update(address)

print(person) # {'name': 'John Doe', 'age': 30, 'gender': 'male', 'city': 'New York', 'state': 'NY'}

Python Functions

Python function is a block of code that can be reused multiple times. Functions are defined using the def keyword, followed by the function name and a set of parentheses that may include parameters. The code inside the function is indented under the function definition.

Here is an example of a simple function in Python that takes no parameters and returns nothing:

def say_hello():
	print("Hello, World!")

# Call the function
say_hello() # prints "Hello, World!"

Functions can also take parameters, which are variables that are passed to the function when it is called. The parameters are specified inside the parentheses in the function definition. Here is an example of a function that takes a single parameter and returns a string:

def say_hello(name):
	return "Hello, " + name + "!"

# Call the function
print(say_hello("John")) # prints "Hello, John!"

Functions can also return a value using the return keyword. The returned value can be assigned to a variable or used as an input for another function. Here is an example of a function that takes two numbers as parameters and returns their sum:

def add(a, b):
    return a + b

# Call the function
result = add(3, 4)

print(result) # prints 7

Python also allows you to define default values for parameters, which means that the parameter will take on this default value if no value is provided when the function is called. Here is an example of a function with a default parameter value:

def say_hello(name="John"):
    return "Hello, " + name + "!"


# Call the function
print(say_hello()) # prints "Hello, John!"

print(say_hello("Jane")) # prints "Hello, Jane!"

You can also use the *args and **kwargs syntax to define function that can take any number of arguments. *args allows you to pass a variable number of non-keyword arguments to a function, while **kwargs allows you to pass a variable number of keyword arguments. Here is an example of a function that takes any number of arguments:

def print_args(*args, **kwargs):
    print(args)
    print(kwargs)

# Call the function

print_args(1, 2, 3) # prints (1, 2, 3) {}

print_args(a=1, b=2, c=3) # prints () {'a': 1, 'b': 2, 'c': 3}

print_args(1, 2, 3, a=1, b=2, c=3) # prints (1, 2, 3) {'a': 1, 'b': 2, 'c': 3}

Functions are an important aspect of Python, they provide a way to organize your code, and make it more readable and maintainable. They also promote code reuse, and you can use them to build more complex programs.

Python Code Debugging

There are several ways to debug Python code, some of the most common methods include:

Using the print() function: One of the simplest ways to debug your code is to insert print() statements in strategic locations throughout your code. This allows you to see the values of variables, check the flow of control, and see the output of your code as it runs.

Using the pdb module: The pdb module is a built-in library in Python that provides an interactive source code debugger. You can start debugging your code by inserting the following line at the point where you want to start debugging:

import pdb; pdb.set_trace()

Using an Integrated Development Environment (IDE): Many IDEs, such as PyCharm, have built-in debugging features that allow you to step through your code, set breakpoints, and inspect variables. These tools can make it easier to find and fix bugs in your code.

Using an external library: Some external libraries, such as ipdb and pudb, provide additional features that can be useful for debugging. For example, ipdb allows you to debug code running in IPython, while pudb provides a full-screen console-based debugger.

Using the assert statement: The assert statement allows you to check for conditions in your code, and raise an error if the conditions are not met. This can be useful for catching bugs early in the development process, before they cause more serious problems.

Here is an example of using assert statement for debugging.

def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

print(divide(10, 5)) # prints 2.0
print(divide(10, 0)) # raises AssertionError: Cannot divide by zero

It's important to note that debugging is an iterative process, and it may take several attempts to find and fix bugs in your code. However, by using the techniques discussed above, you can make the debugging process more efficient and effective.

Python Known Errors

There are several known errors that developers may encounter when working with Python. Some of the most common include:
  • IndentationError: This error occurs when the indentation of code is not consistent or not in the correct format. For example, using tabs instead of spaces to indent code.
  • SyntaxError: This error occurs when the Python interpreter encounters code that does not conform to the language's rules. For example, forgetting a colon at the end of a for loop statement.
  • NameError: This error occurs when the interpreter encounters an undefined variable or function. For example, trying to use a variable that has not been defined.
  • TypeError: This error occurs when an operation or function is applied to the wrong type of object. For example, trying to use the + operator to concatenate a string and an integer.
  • IndexError: This error occurs when trying to access an index that is out of range in a list or tuple. For example, trying to access the 10th element of a list that only has 5 elements.
  • ValueError: This error occurs when a value passed to a function or method is of the correct type but has an inappropriate value. For example, passing a string to a function that expects an integer.
  • ImportError: This error occurs when the interpreter is unable to find a module or package that has been imported. For example, importing a non-existent module or importing a module that has a typo in its name.
  • KeyError: This error occurs when trying to access a dictionary key that does not exist.
  • AttributeError: This error occurs when an object does not have a specific attribute.
  • FileNotFoundError: This error occurs when a file is not found in the specified path. For example, trying to open a file that doesn't exist.
These are some of the known errors that developers may encounter while working with Python. By understanding these errors and how to fix them, you can become a more effective Python developer.


Make sure to subscribe to my YouTube channel for the latest videos and blogs.


This post first appeared on Tsarde, please read the originial post: here

Share the post

Python Beginners Tutorial - Zero To Hero for Beginners

×

Subscribe to Tsarde

Get updates delivered right to your inbox!

Thank you for your subscription

×