# Python Essential for Data Science Beginners

Are you a beginner looking to learn Python fundamentals for data science? Python is a powerful programming language widely used in the data science community for data analysis, machine learning, artificial intelligence, deep learning and more. In this post, we'll cover the essential Python basics you need to know to start your journey in data science with confidence. Let's get started!

## What is Python?

Python is a very easy-to-learn language. It is a popular high-level programming language that is widely used for general-purpose programming. It is known for its simplicity, ease of use, and readability, which makes it an ideal choice for beginners learning to code. Python3 is also widely used in a variety of fields such as web development, data science, machine learning, artificial intelligence, and many more.

* *Python is an interpreted language, which means that it does not need to be compiled before it can be run. It runs the code line by line. This makes it a highly flexible language and also allows for rapid prototyping and development.*
    
* *Python supports multiple programming paradigms, including procedural, functional, and object-oriented programming.*
    
* *Python is considered a* ***Write Once Run Anywhere(WORA)*** *language because it can run on multiple platforms like Windows, macOS, and Linux.*
    

## First Program In Python

```python
print("Welcome! Data Pioneers! and non-Data Pioneers!😀")
_________________________________________________________
#output: Welcome! Data Pioneers! and non-Data Pioneers!😀
```

Here, We have used the `print()` function in the above code. We use this function to show the output in our terminal.

## Variables

Basically, In Python, variables are names that point to memory locations where data values are stored. In a nutshell, It's a container that holds some values. Very similar to our wardrobe we can store our clothes, jewelry, shoes and more.

### Rules to define variables in Python

* A variable name must start with a letter or an underscore (\_).
    
* A variable name cannot start with a number.
    
* A variable name can only contain alphanumeric characters (A-Z, a-z, 0-9) and underscores (\_).
    
* Variable names are case-sensitive (name, Name, and NAME are different variables).
    
* The reserved words (keywords) in Python cannot be used as variable names.
    

***That's how we define variables:***

```python
blog_name = "Data Pioneers"
Author_Name = "Aspersh Upadhyay"
country = "India" 
Country_Code = 91
```

## Data Types

The data type is simply, what types of values we want to store in the variables. This is required in programming to do various operations without causing an error.

**Python built-in data types:**

<table><tbody><tr><td colspan="1" rowspan="1" colwidth="63"><p><strong>Data Types</strong></p></td><td colspan="1" rowspan="1" colwidth="132"><p>One Word Definition</p></td><td colspan="1" rowspan="1"><p><strong>Defining each data type</strong></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>int</p></td><td colspan="1" rowspan="1" colwidth="132"><p>integer number</p></td><td colspan="1" rowspan="1"><p><code>x = 15</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>float</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Decimal Value</p></td><td colspan="1" rowspan="1"><p><code>y = 33.5</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>str</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Text</p></td><td colspan="1" rowspan="1"><p><code>name = "Aspersh Upadhyay"</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>list</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Collection</p></td><td colspan="1" rowspan="1"><p><code>grocery_list = ["rice", "wheat", "pulses", "oil", "sugar"]</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>dict</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Key-value pairs</p></td><td colspan="1" rowspan="1"><p><code>word = {"age": 22, "name": "Shyam"}</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>set</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Unique Collection</p></td><td colspan="1" rowspan="1"><p><code>fruits = {"apple": 50, "banana": 20, "orange": 30}</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>tuple</p></td><td colspan="1" rowspan="1" colwidth="132"><p>Immutable Collection</p></td><td colspan="1" rowspan="1"><p><code>colors = ("red", "green", "blue")</code></p></td></tr><tr><td colspan="1" rowspan="1" colwidth="63"><p>bool</p></td><td colspan="1" rowspan="1" colwidth="132"><p>True / False</p></td><td colspan="1" rowspan="1"><p><code>x = 10 result = bool(x)</code></p></td></tr></tbody></table>

## String

Strings in Python are used to store and manipulate textual data. They are a sequence of characters, enclosed in quotes.

### Creating a string

You can create a string in Python by enclosing a sequence of characters within either single quotes (' ') or double quotes (" ").

Example:

```python
my_string = "Data pioneers!"
print(my_string)
```

Some operations that we can perform on Strings.

```python
# Creating a string
my_string = "Data Pioneers!"
print(my_string)

# Accessing characters in a string
print(my_string[0])    # Output: D
print(my_string[-1])   # Output: !

# Slicing a string
print(my_string[0:4])  # Output: Data

# Modifying a string
new_string = my_string + " Welcome to the world of data!"
print(new_string)      # Output: Data Pioneers! Welcome to the world of data!

# String methods
print(my_string.lower())                    # Output: data pioneers!
print(my_string.upper())                    # Output: DATA PIONEERS!
print(my_string.strip())                    # Output: Data Pioneers!
print(my_string.replace("Pioneers", "Experts"))    # Output: Data Experts!
print(my_string.split(" "))                  # Output: ['Data', 'Pioneers!']
```

Next, we'll be discussing lists, tuples and dictionaries in the ompound Data Structures section.

To check the types of your variables use ***the*** `type()` function:

```python
x = 15 
y = 33.5 
your_name = "Aspersh Upadhyay" 
print(type(x), type(y), type(your_name))
____________________________________________________
#output: <class 'int'> <class 'float'> <class 'str'>
```

## Take Input from the User

To get data from the user in Python, we can use the built-in function `input()`. This function takes a string argument that is displayed as a prompt to the user and returns the user’s input as a string.

```python
# Ask the user to enter their name.
your_name = input("Enter your name: ") 
print(your_name)
______________________________________
#output: Aspersh Upadhyay
```

If we want to convert the user’s input to a different data type, such as an integer or a float, we can use the corresponding type conversion functions, such as `int()` or `float()`.

For example:

```python
your_age = int(input("Enter your age: ")) # 35 
print(your_age) # it will print 35
_________________________________________
#output: 35
```

## Conditional Statement

Condition statements are a fundamental part of programming that allows you to make decisions based on certain conditions. These statements are used to evaluate whether a specific condition is true or false, and then execute certain code blocks based on the result of the evaluation.

In Python, there are three types of condition statements: `if statements`, `if-else` `statements`, and `elif statements`(to add additional conditional).

### If Statement

If statements are used to execute a certain code block if a specific condition is true.

For example:

```python
your_age = 25

if your_age >= 18:
    print("You are old enough to vote!")
________________________________________
#output: You are old enough to vote.
```

In this code, the if statement evaluates whether the variable "age" is greater than or equal to 18. If it is, then the message "You are old enough to vote!" will be printed.

### If-else Statement

If-else statements are used to execute one code block if a condition is true, and another code block if the condition is false.

For example:

```python
your_age = 16

if your_age >= 18:
    print("You are old enough to vote!")
else:
    print("You are not old enough to vote.")
____________________________________________
#output: You are not old enough to vote.
```

In this code, the if statement evaluates whether the variable "age" is greater than or equal to 18. Since the condition is false, the code block under the else statement will be executed, which will print the message "You are not old enough to vote."

### Elif statement

Elif statements to add additional conditions to your code.

For example:

```python
your_age = 25

if your_age >= 18 and your_age < 21:
    print("You are old enough to vote, but you cannot drink.")
elif your_age >= 21:
    print("You are old enough to vote and drink!")
else:
    print("You are not old enough to vote.")
______________________________________________________________
# output: You are old enough to vote and drink!
```

## Loop Statement

Loop statements are an important aspect of programming, and they allow you to repeat a block of code multiple times. There are two main types of loops in Python: `for` loops and `while` loops.

### For Loop

A `for` loop is used to iterate over a sequence of items, such as a list or a string. The loop continues until all the items in the sequence have been processed.

Here's an example of a `for` loop that prints each item in a list:

```python
fruits = ["apple", "banana", "cherry"] #list of fruits
for fruit in fruits:
  print(fruit)
_______________________________________________________
#output: 
  apple
  banana
  cherry
```

In this code, the `for` loop iterates over the list of fruits, and the `fruit` variable is set to each item in the list in turn. The `print()` statement then prints each item.

### While Loop

A `while` loop is used to repeat a block of code while a certain condition is true. The loop continues until the condition becomes false.

Here's an example of a `while` loop that prints a "Data Pioneers" 5 times:

```python
i = 1
while i <= 5:
  print("Data Pioneers!")
  i += 1
_____________________________________
#output: 
Data Pioneers
Data Pioneers
Data Pioneers
Data Pioneers
Data Pioneers
```

**Note:** Using Loop statement you can iterate tedious tasks.

### Break & Continue Statement

* **The break statement** is used to exit the loop entirely when a certain condition is met.
    
* **The continue statement** is used to skip over the current iteration of the loop and move on to the next iteration.
    

Example:

```python
#break
for i in range(1, 6):
    if i == 3:
        break
    print(i)  # Output: 1, 2

#continue
for i in range(1, 6):
    if i == 3:
        continue
    print(i)  # Output: 1, 2, 4, 5
```

## Compound Data Structure

A compound data structure is a data type that can hold multiple values. The most common compound data structures in Python are `lists`, `tuples`, and `dictionaries`.

### List

A list is an ordered collection of elements enclosed in square brackets (\[\]). Elements in a list can be of different data types, including other lists. Lists are mutable, meaning you can add, remove, and change elements after creating them.

Here is an example of a list:

```python
fruits = ['apple', 'banana', 'orange', 'mango']
```

Now let's look at some of the basic operations that can be performed on a list:

```python
# Creating a list
my_list = [1, 2, 3, 4, 5]

# Accessing elements in a list
print(my_list[2])   # Output: 3

# Slicing a list
print(my_list[1:4])   # Output: [2, 3, 4]

# Modifying a list
my_list[0] = 10
print(my_list)   # Output: [10, 2, 3, 4, 5]

# Adding elements to a list
my_list.append(6)
print(my_list)   # Output: [10, 2, 3, 4, 5, 6]

# Removing elements from a list
my_list.remove(4)
print(my_list)   # Output: [10, 2, 3, 5, 6]

# Sorting a list
my_list.sort()
print(my_list)   # Output: [2, 3, 5, 6, 10]
```

### Tuples

Tuple is an ordered and immutable collection of elements. It is similar to a list in many ways, but the key difference is that you cannot modify the elements of a tuple once it is created. It is similar to lists, but they are faster and consume less memory. Tuples are created using round brackets or parentheses.

**Creating a Tuple**

To create a tuple, we can use parentheses and separate the elements with commas.

For example:

```python
tup = (1, 2, 3, 'apple')
```

Various operations that we can perform on tuples:

```python
my_tuple = (1, 2, 3, 4, 3, 5)

#Accessing elements in a tuple
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 5

# Slicing a tuple
print(my_tuple[1:4]) # Output: (2, 3, 4)

# Modifying a tuple (not possible)
# t[0] = 10 # TypeError: 'tuple' object does not support item assignment

# Concatenating two tuples
t2 = (6, 7, 8)
t3 = t + t2
print(t3) # Output: (1, 2, 3, 4, 5, 6, 7, 8)

# Counting the occurrences of a value in a tuple
print(my_tuple.count(2)) # Output: 1

# Getting the index of the first occurrence of a value in a tuple
print(my_tuple.index(3)) # Output: 2

# Returns the length of the tuple
print(len(my_tuple))  # Output: 6
```

**Simple Use Case**

One common use case for tuples is when you have a function that returns multiple values. Instead of returning the values as separate variables, you can return them as a tuple. Here's an example:

```python
def get_name_and_age():
    name = "Data Pioneers!"
    age = 25
    return (name, age)

result = get_name_and_age()
print(result)  # Output: ("Data Pioneers!", 25)
```

We can also unpack a tuple into separate variables:

```python
name, age = get_name_and_age()
print(name)  # Output: "Data Pionners!"
print(age)   # Output: 25
```

### Dictionaries

A dictionary is a data structure in Python that is used to store key-value pairs. Each key in a dictionary maps to a specific value. In other programming languages, this data structure is sometimes referred to as an associative `array`, `hash table`, or `map`.

**Creating a dictionary:**

To create a dictionary in Python, we can use curly braces `{}` or the built-in `dict()` function.

Here is an example:

```python
# Creating a dictionary using curly braces
my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

# Creating a dictionary using dict() function
my_dict = dict(key1="value1", key2="value2", key3="value3")
```

Here are some operations that we can perform on it.

```python
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Accessing values
print(my_dict['name'])  # Output: 'John'
print(my_dict.get('age'))  # Output: 30

# Modifying values
my_dict['age'] = 35
print(my_dict)  # Output: {'name': 'John', 'age': 35, 'city': 'New York'}

# Adding new key-value pairs
my_dict['job'] = 'Software Engineer'
print(my_dict)  # Output: {'name': 'John', 'age': 35, 'city': 'New York', 'job': 'Software Engineer'}

# Removing key-value pairs
my_dict.pop('city')
print(my_dict)  # Output: {'name': 'John', 'age': 35, 'job': 'Software Engineer'}

# Checking if key exists
if 'name' in my_dict:
    print('Name exists in dictionary')
else:
    print('Name does not exist in dictionary')

# Getting all keys and values
print(my_dict.keys())  # Output: dict_keys(['name', 'age', 'job'])
print(my_dict.values())  # Output: dict_values(['John', 35, 'Software Engineer'])

# Looping through the dictionary
for key, value in my_dict.items():
    print(key, value)
# Output:
# name John
# age 35
# job Software Engineer
```

## Functions

Functions in Python are blocks of code that perform a specific task. They help to break a large program into smaller, more manageable pieces. Functions can be called from other parts of the program as many times as needed, which can help to reduce duplication of code and make the program more modular.

### Define a Function

To define a function in Python, you use the `def` keyword followed by the name of the function, a set of parentheses containing any parameters the function takes (which may be empty), and a colon. The body of the function is indented and typically contains a series of statements that accomplish the task of the function. Finally, the function may return a value using the `return` statement.

Here's an example of a simple function that adds two numbers and returns the result:

```python
def add_numbers(a, b):
    result = a + b
    return result
```

This function takes two parameters, `a` and `b`, adds them together, stores the result in a variable called `result`, and then returns the result. To call this function, you simply use its name followed by parentheses containing the arguments you want to pass to it:

```python
x = 5
y = 7
z = add_numbers(x, y) # calling function
______________________________
print(z)  # Output: 12
```

This code calls the `add_numbers` function with arguments `x` and `y`, which are both integers. The function adds them together and returns the result, which is stored in a variable called `z`. Finally, the program prints the value of `z`, which is `12`.

Functions can also have default parameter values, which are used if the function is called without specifying a value for that parameter. Here's an example:

```python
def greet(name, greeting="Hello"):
    print(f'{greeting }, {name}!')
```

This function takes a required parameter `name` and an optional parameter `greeting`, which defaults to `"Hello"`. The function prints out a message that includes the name and greeting. Here are some examples of how to call this function:

```python
greet("Data Pioneers")  # Output: Hello, Data Pioneers!
greet("Aspersh", "Hi")  # Output: Hi, Aspersh!
greet(greeting="Hola", name="Readers")  # Output: Hola, Readers!
```

In the first example, the function is called with only the `name` argument, so the default greeting of `"Hello"` is used. In the second example, both the `name` and `greeting` arguments are specified. In the third example, the arguments are passed by name, which can be useful when there are many parameters or when you want to specify them in a different order than they are defined.

Functions can also return multiple values using tuples. Here's an example:

```python
def calculate_statistics(numbers):
    total = sum(numbers) 
    count = len(numbers)
    mean = total / count
    variance = sum((x - mean) ** 2 for x in numbers) / count
    return total, count, mean, variance
```

This function takes a list of numbers, calculates some statistics (total, count, mean, and variance), and returns them as a tuple. Here's how you can call this function and unpack the returned values:

```python
data = [3, 5, 2, 7, 8, 1]
#unpack the values returned by the function
total, count, mean, variance = calculate_statistics(data)
print("Total:", total)
print("Count:", count)
print("Mean:", mean)
print("Variance:", variance)
_________________________________________________________
# output: (26, 6, 4.333333333333333, 6.5555555555555545)
```

This code calls the `calculate_statistics` function with a list of numbers and stores the returned values in variables. It then prints out each of the returned values.

## Object-Oriented Programming(OOP) Concept:

Object-oriented programming (OOP) is a programming style that helps organize code by creating objects that hold data and the code that operates on that data. In Python, classes are used to create objects, and there are three important concepts to know: `classes` and `objects`, `encapsulation`, `inheritance`, and `polymorphism`

### **Classes and Objects**:

**A class** is like a blueprint for creating objects. It defines what kind of data and code an object will have.

**An object** is an instance of a class. So, if you have a class that defines a dog, you can create multiple objects of that class, each representing a different dog.

Here's an example of a simple dog class:

```python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed
    
    def bark(self):
        print("Woof!")
```

This dog class has two attributes (name and breed) and one method (bark). To create an object of this class, you can use code like this:

```python
my_dog = Dog("Fido", "Golden Retriever")
```

This creates an object called my\_dog, which has the name "Fido" and a breed of "Golden Retriever".

### Encapsulation:

Encapsulation is a way to protect the data inside an object from being accidentally changed. This means that the internal data of an object can only be accessed through special methods that the class defines.

Here's an example of encapsulation being used in the dog class:

```python
class Dog:
    def __init__(self, name, breed):
        self._name = name
        self._breed = breed
    
    def bark(self):
        print("Woof!")
    
    def get_name(self):
        return self._name
    
    def set_name(self, name):
        self._name = name
```

In this updated dog class, the name and breed attributes are now marked as private using an underscore. This means that they can't be accessed directly from outside the class. Instead, the class provides [**getter** and **setter**](https://realpython.com/courses/getters-and-setters-python/) methods for the name attribute so that it can be safely accessed.

### Inheritance:

Inheritance is a way to create a new class based on an existing class. The new class will have all the attributes and methods of the existing class, and can also add new attributes and methods of its own.

Here's an example of inheritance being used to create a class for a poodle, which is a type of dog:

```python
class Poodle(Dog):
    def __init__(self, name, breed, color):
        super().__init__(name, breed)
        self.color = color
    
    def groom(self):
        print(f"{self.get_name()} is getting groomed!")
```

In this example, the Poodle class is inherited from the Dog class. It has its own color attribute and groom method. The Poodle class also calls the constructor of the Dog class using the super() function. This allows it to reuse the code from the Dog class.

### Polymorphism

Polymorphism means that objects of different classes can be used in the same way. In Python, we achieve polymorphism through method overriding and method overloading.

1. **&lt; Method overriding &gt;**
    

Is when a subclass defines a method with the same name as a method in its superclass. This allows the subclass to provide its implementation of the method. When we call this method on an object of the subclass, Python will call the subclass's implementation of the method.

For example:

```python
class Animal:
    def speak(self):
        print("I'm an animal")

class Dog(Animal):
    def speak(self):
        print("Woof!")

class Cat(Animal):
    def speak(self):
        print("Meow!")

my_dog = Dog()
my_cat = Cat()

my_dog.speak()  # Output: Woof!
my_cat.speak()  # Output: Meow!
```

In this example, we have a superclass called Animal with a method called speak that prints "I'm an animal". We then create two subclasses, Dog and Cat, that override the speak method with their implementation. When we call the speak method on an object of the Dog class, Python will call the Dog class's implementation of the method, which prints "Woof!". When we call the speak method on an object of the Cat class, Python will call the Cat class's implementation of the method, which prints "Meow!".

1. **&lt; Method overloading** &gt;
    

Is when a class defines multiple methods with the same name, but with different parameter lists. This allows the class to provide multiple ways of calling the same method. When we call this method with different arguments, Python will call the appropriate implementation of the method.

For example:

```python
class Calculator:
    def add(self, x, y):
        return x + y
    
    def add(self, x, y, z):
        return x + y + z

my_calculator = Calculator()

print(my_calculator.add(1, 2))      # Output: 3
print(my_calculator.add(1, 2, 3))   # Output: 6
```

In this example, we have a class called Calculator with two add methods. The first add method takes two arguments, while the second add method takes three arguments. When we call the add method with two arguments, Python will call the first add method, which returns the sum of the two arguments. When we call the add method with three arguments, Python will call the second add method, which returns the sum of the three arguments.

## Conclusion

In this post, we covered essential Python basics such as variables, data types, strings, taking user input, conditional statements, loop statements, and compound data structure. We also discussed how functions can be used to break up a large program into smaller, more manageable pieces, and how OOP helps organize code by creating objects that hold data and the code that operates on that data.

---

I have tried to pack all the important topics into one article. If you find this article helpful for you, feel free to follow me and hit a like. It will boost my confidence and I would love to share an interesting topic like this.

If you have any questions regarding the data science field so join the [Data Pioneers](http://datapioneers.quora.com) community and ask your question over there and I will try to resolve your issues.

If you want to support me [buy me a cup of coffee☕.](http://ko-fi.com/aspershupadhyay)

Happy learning Python!😀
