You are reading the article **Python Numpy Tutorial For Beginners: Learn With Examples** updated in December 2023 on the website Daihoichemgio.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. *Suggested January 2024 Python Numpy Tutorial For Beginners: Learn With Examples*

What is NumPy in Python?

NumPy is an open source library available in Python, which helps in mathematical, scientific, engineering, and data science programming. It is a very useful library to perform mathematical and statistical operations in Python. It works perfectly for multi-dimensional arrays and matrix multiplication. It is easy to integrate with C/C++ and Fortran.

For any scientific project, NumPy is the tool to know. It has been built to work with the N-dimensional array, linear algebra, random number, Fourier transform, etc.

NumPy is a programming language that deals with multi-dimensional arrays and matrices. On top of the arrays and matrices, NumPy supports a large number of mathematical operations. In this part, we will review the essential functions that you need to know for the tutorial on ‘TensorFlow.’

Why use NumPy?NumPy is memory efficiency, meaning it can handle the vast amount of data more accessible than any other library. Besides, NumPy is very convenient to work with, especially for matrix multiplication and reshaping. On top of that, NumPy is fast. In fact, TensorFlow and Scikit learn to use NumPy array to compute the matrix multiplication in the back end.

In this Python NumPy Tutorial, we will learn:

How to Install NumPyTo install NumPy library, please refer our tutorial How to install TensorFlow. NumPy is installed by default with Anaconda.

In remote case, NumPy not installed-

You can install NumPy using Anaconda:

conda install -c anaconda numpy

In Jupyter Notebook :

import sys !conda install --yes --prefix {sys.prefix} numpy Import NumPy and Check VersionThe command to import numpy is:

import numpy as npAbove code renames the Numpy namespace to np. This permits us to prefix Numpy function, methods, and attributes with ” np ” instead of typing ” numpy.” It is the standard shortcut you will find in the numpy literature

To check your installed version of NumPy, use the below command:

print (np.__version__)Output:

1.18.0 What is Python NumPy Array?NumPy arrays are a bit like Python lists, but still very much different at the same time. For those of you who are new to the topic, let’s clarify what it exactly is and what it’s good for.

As the name kind of gives away, a NumPy array is a central data structure of the numpy library. The library’s name is actually short for “Numeric Python” or “Numerical Python”.

Creating a NumPy ArraySimplest way to create an array in Numpy is to use Python List

myPythonList = [1,9,8,3]To convert python list to a numpy array by using the object np.array.

numpy_array_from_list = np.array(myPythonList)To display the contents of the list

numpy_array_from_listOutput:

array([1, 9, 8, 3])In practice, there is no need to declare a Python List. The operation can be combined.

a = np.array([1,9,8,3])NOTE: Numpy documentation states use of np.ndarray to create an array. However, this the recommended method.

You can also create a numpy array from a Tuple.

Mathematical Operations on an ArrayYou could perform mathematical operations like additions, subtraction, division and multiplication on an array. The syntax is the array name followed by the operation (+.-,*,/) followed by the operand

Example:

numpy_array_from_list + 10Output:

array([11, 19, 18, 13])This operation adds 10 to each element of the numpy array.

Shape of ArrayYou can check the shape of the array with the object shape preceded by the name of the array. In the same way, you can check the type with dtypes.

import numpy as np a = np.array([1,2,3]) print(a.shape) print(a.dtype) (3,) int64An integer is a value without decimal. If you create an array with decimal, then the type will change to float.

#### Different type b = np.array([1.1,2.0,3.2]) print(b.dtype) float64 2 Dimension ArrayYou can add a dimension with a “,”coma

Note that it has to be within the bracket []

### 2 dimension c = np.array([(1,2,3), (4,5,6)]) print(c.shape) (2, 3) 3 Dimension ArrayHigher dimension can be constructed as follow:

### 3 dimension d = np.array([ [[1, 2,3], [4, 5, 6]], [[7, 8,9], [10, 11, 12]] ]) print(d.shape) (2, 2, 3)Objective Code

Create array array([1,2,3])

print the shape array([.]).shape

What is numpy.zeros()?numpy.zeros() or np.zeros Python function is used to create a matrix full of zeroes. numpy.zeros() in Python can be used when you initialize the weights during the first iteration in TensorFlow and other statistic tasks.

numpy.zeros() function Syntax

numpy.zeros(shape, dtype=float, order='C')Python numpy.zeros() Parameters

Here,

Shape: is the shape of the numpy zero array

Dtype: is the datatype in numpy zeros. It is optional. The default value is float64

Order: Default is C which is an essential row style for numpy.zeros() in Python.

Python numpy.zeros() Example

import numpy as np np.zeros((2,2))Output:

array([[0., 0.], [0., 0.]])Example of numpy zero with Datatype

import numpy as np np.zeros((2,2), dtype=np.int16)Output:

array([[0, 0], [0, 0]], dtype=int16) What is numpy.ones()?np.ones() function is used to create a matrix full of ones. numpy.ones() in Python can be used when you initialize the weights during the first iteration in TensorFlow and other statistic tasks.

Python numpy.ones() Syntax

numpy.ones(shape, dtype=float, order='C')Python numpy.ones() Parameters

Here,

Shape: is the shape of the chúng tôi Python Array

Dtype: is the datatype in numpy ones. It is optional. The default value is float64

Order: Default is C which is an essential row style.

Python numpy.ones() 2D Array with Datatype Example

import numpy as np np.ones((1,2,3), dtype=np.int16)Output:

array([[[1, 1, 1], [1, 1, 1]]], dtype=int16)numpy.reshape() function in Python

Python NumPy Reshape function is used to shape an array without changing its data. In some occasions, you may need to reshape the data from wide to long. You can use the np.reshape function for this.

Syntax of np.reshape()

numpy.reshape(a, newShape, order='C')Here,

a: Array that you want to reshape

newShape: The new desires shape

Order: Default is C which is an essential row style.

Example of NumPy Reshape

import numpy as np e = np.array([(1,2,3), (4,5,6)]) print(e) e.reshape(3,2)Output:

[[1 2 3] [4 5 6]] array([[1, 2], [3, 4], [5, 6]])numpy.flatten() in Python

Python NumPy Flatten function is used to return a copy of the array in one-dimension. When you deal with some neural network like convnet, you need to flatten the array. You can use the np.flatten() functions for this.

Syntax of np.flatten()

numpy.flatten(order='C')Order: Default is C which is an essential row style.

Example of NumPy Flatten

e.flatten()Output:

array([1, 2, 3, 4, 5, 6])What is numpy.hstack() in Python?

Numpy.hstack is a function in Python that is used to horizontally stack sequences of input arrays in order to make a single array. With hstack() function, you can append data horizontally. It is a very convenient function in NumPy.

Lets study hstack in Python with an example:

Example:

## Horitzontal Stack import numpy as np f = np.array([1,2,3]) g = np.array([4,5,6]) print('Horizontal Append:', np.hstack((f, g)))Output:

Horizontal Append: [1 2 3 4 5 6]What is numpy.vstack() in Python?

Numpy.vstack is a function in Python which is used to vertically stack sequences of input arrays in order to make a single array. With vstack() function, you can append data vertically.

Lets study it with an example:

Example:

## Vertical Stack import numpy as np f = np.array([1,2,3]) g = np.array([4,5,6]) print('Vertical Append:', np.vstack((f, g)))Output:

Vertical Append: [[1 2 3] [4 5 6]]After studying NumPy vstack and hstack, let’s learn an example to generate random numbers in NumPy.

Generate Random Numbers using NumPyTo generate random numbers for Gaussian distribution, use:

numpy.random.normal(loc, scale, size)Here,

Loc: the mean. The center of distribution

Scale: standard deviation.

Size: number of returns

Example:

## Generate random nmber from normal distribution normal_array = np.random.normal(5, 0.5, 10) print(normal_array) [5.56171852 4.84233558 4.65392767 4.946659 4.85165567 5.61211317 4.46704244 5.22675736 4.49888936 4.68731125]If plotted the distribution will be similar to following plot

Example to Generate Random Numbers using NumPy

NumPy Asarray FunctionThe asarray()function is used when you want to convert an input to an array. The input could be a lists, tuple, ndarray, etc.

Syntax:

numpy.asarray(data, dtype=None, order=None)[source]Here,

data: Data that you want to convert to an array

dtype: This is an optional argument. If not specified, the data type is inferred from the input data

Order: Default is C which is an essential row style. Other option is F (Fortan-style)

Example:

Consider the following 2-D matrix with four rows and four columns filled by 1

import numpy as np A = np.matrix(np.ones((4,4)))If you want to change the value of the matrix, you cannot. The reason is, it is not possible to change a copy.

np.array(A)[2]=2 print(A) [[1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.] [1. 1. 1. 1.]]Matrix is immutable. You can use asarray if you want to add modification in the original array. Let’s see if any change occurs when you want to change the value of the third rows with the value 2.

np.asarray(A)[2]=2 print(A)Code Explanation:

np.asarray(A): converts the matrix A to an array

[2]: select the third rows

Output:

[[1. 1. 1. 1.] [1. 1. 1. 1.] [2. 2. 2. 2.] # new value [1. 1. 1. 1.]] What is numpy.arange()?numpy.arange() is an inbuilt numpy function that returns an ndarray object containing evenly spaced values within a defined interval. For instance, you want to create values from 1 to 10; you can use np.arange() in Python function.

Syntax:

numpy.arange(start, stop, step, dtype)Python NumPy arange Parameters:

Start: Start of interval for np.arange in Python function.

Stop: End of interval.

Step: Spacing between values. Default step is 1.

Dtype: Is a type of array output for NumPy arange in Python.

Example:

import numpy np np.arange(1, 11)Output:

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])Example:

If you want to change the step in this NumPy arange function in Python example, you can add a third number in the parenthesis. It will change the step.

import numpy np np.arange(1, 14, 4)Output:

array([ 1, 5, 9, 13]) NumPy Linspace FunctionLinspace gives evenly spaced samples.

Syntax:

numpy.linspace(start, stop, num, endpoint)Here,

Start: Starting value of the sequence

Stop: End value of the sequence

Num: Number of samples to generate. Default is 50

Endpoint: If True (default), stop is the last value. If False, stop value is not included.

Example:

For instance, it can be used to create 10 values from 1 to 5 evenly spaced.

import numpy as np np.linspace(1.0, 5.0, num=10)Output:

array([1. , 1.44444444, 1.88888889, 2.33333333, 2.77777778, 3.22222222, 3.66666667, 4.11111111, 4.55555556, 5. ])If you do not want to include the last digit in the interval, you can set endpoint to false

np.linspace(1.0, 5.0, num=5, endpoint=False)Output:

array([1. , 1.8, 2.6, 3.4, 4.2]) LogSpace NumPy Function in PythonLogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as np.linspace.

Syntax:

numpy.logspace(start, stop, num, endpoint)Example:

np.logspace(3.0, 4.0, num=4)Output:

array([ 1000. , 2154.43469003, 4641.58883361, 10000. ])Finaly, if you want to check the memory size of an element in an array, you can use itemsize

x.itemsize

Output:

16Each element takes 16 bytes.

Indexing and Slicing in PythonExample:

## Slice import numpy as np e = np.array([(1,2,3), (4,5,6)]) print(e) [[1 2 3] [4 5 6]]Remember with numpy the first array/column starts at 0.

## First column print('First row:', e[0]) ## Second col print('Second row:', e[1])Output:

First row: [1 2 3] Second row: [4 5 6]In Python, like many other languages,

The values before the comma stand for the rows

The value on the rights stands for the columns.

If you want to select a column, you need to add : before the column index.

: means you want all the rows from the selected column.

print('Second column:', e[:,1]) Second column: [2 5]To return the first two values of the second row. You use : to select all columns up to the second

## Second Row, two values print(e[1, :2]) [4 5] Statistical Functions in PythonNumPy has quite a few useful statistical functions for finding minimum, maximum, percentile standard deviation and variance, etc from the given elements in the array. The functions are explained as follows −

Numpy is equipped with the robust statistical function as listed below

Function Numpy

Min np.min()

Max np.max()

Mean np.mean()

Median np.median()

Standard deviation np.std()

Consider the following Array:

Example:

import numpy as np normal_array = np.random.normal(5, 0.5, 10) print(normal_array)Output:

[5.56171852 4.84233558 4.65392767 4.946659 4.85165567 5.61211317 4.46704244 5.22675736 4.49888936 4.68731125]Example of NumPy Statistical function

### Min print(np.min(normal_array)) ### Max print(np.max(normal_array)) ### Mean print(np.mean(normal_array)) ### Median print(np.median(normal_array)) ### Sd print(np.std(normal_array))Output:

4.467042435266913 5.612113171990201 4.934841002270593 4.846995625786663 0.3875019367395316 What is numpy dot product?Numpy.dot product is a powerful library for matrix computation. For instance, you can compute the dot product with chúng tôi chúng tôi product is the dot product of a and b. numpy.dot() in Python handles the 2D arrays and perform matrix multiplications.

Syntax:

numpy.dot(x, y, out=None)Parameters

Here,

x,y: Input arrays. x and y both should be 1-D or 2-D for the np.dot() function to work

out: This is the output argument for 1-D array scalar to be returned. Otherwise ndarray should be returned.

Returns

The function numpy.dot() in Python returns a Dot product of two arrays x and y. The dot() function returns a scalar if both x and y are 1-D; otherwise, it returns an array. If ‘out’ is given then it is returned.

Raises

Dot product in Python raises a ValueError exception if the last dimension of x does not have the same size as the second last dimension of y.

Example:

## Linear algebra ### Dot product: product of two arrays f = np.array([1,2]) g = np.array([4,5]) ### 1*4+2*5 np.dot(f, g)Output:

14 Matrix Multiplication in PythonThe Numpy matmul() function is used to return the matrix product of 2 arrays. Here is how it works

1) 2-D arrays, it returns normal product

3) 1-D array is first promoted to a matrix, and then the product is calculated

Syntax:

numpy.matmul(x, y, out=None)Here,

x,y: Input arrays. scalars not allowed

out: This is optional parameter. Usually output is stored in ndarray

Example:

In the same way, you can compute matrices multiplication with np.matmul

### Matmul: matruc product of two arrays h = [[1,2],[3,4]] i = [[5,6],[7,8]] ### 1*5+2*7 = 19 np.matmul(h, i)Output:

array([[19, 22], [43, 50]]) DeterminantLast but not least, if you need to compute the determinant, you can use np.linalg.det(). Note that numpy takes care of the dimension.

Example:

## Determinant 2*2 matrix ### 5*8-7*6np.linalg.det(i)Output:

-2.000000000000005 Summary

NumPy is an open source library available in Python, which helps in mathematical, scientific, engineering, and data science programming.

numpy.zeros() or np.zeros Python function is used to create a matrix full of zeroes.

numpy.ones() in Python can be used when you initialize the weights during the first iteration in TensorFlow and other statistic tasks.

Python NumPy Reshape function is used to shape an array without changing its data.

Python NumPy Flatten function is used to return a copy of the array in one-dimension.

Numpy.hstack is a function in Python that is used to horizontally stack sequences of input arrays in order to make a single array.

Numpy.vstack is a function in Python which is used to vertically stack sequences of input arrays in order to make a single array.

numpy.arange() is an inbuilt numpy function that returns an ndarray object containing evenly spaced values within a defined interval.

Numpy.dot product is a powerful library for matrix computation.

The Numpy matmul() function is used to return the matrix product of 2 arrays.

You're reading __Python Numpy Tutorial For Beginners: Learn With Examples__

## Interesting Python Projects With Code For Beginners – Part 2

1. Convert the image to Gray using cv2.COLOR_BGR2GRAY.

cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)

2. Finding contours in the image:

To find contours use cv2.findContours(). It takes three parameters: the source image, contour retrieval mode, contour approximation method. This will return a python list of all contours. Contour is nothing but a NumPy array of (x,y) coordinates of boundary points in the object.

3. Apply OCR.

By looping through each contour, take x,y and width, height using cv2.boundingRect() function. Then draw a rectangle function in image using cv2.rectange(). This has five parameters: input image, (x, y), (x+w, y+h), boundary colour for rectangle, size of the boundary.

4. Crop the rectangular region and pass that to tesseract to extract text. Save your content in a file by opening it in append mode.

Code:

import cv2 import pytesseract # path to Tesseract-OCR in your computer pytesseract.pytesseract.tesseract_cmd = 'path_to_tesseract.exe' img = cv2.imread("input.png") #input image gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Converting image to gray scale # performing OTSU threshold # give structure shape and kernel size # kernel size increases or decreases the area of the rectangle to be detected. rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (18, 18)) #dilation on the threshold image dilation = cv2.dilate(img_thresh , rect_kernel, iterations = 1) img_contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) im2 = img.copy() file = open("Output.txt", "w+") #text file to save results file.write("") file.close() #loop through each contour for contour in img_contours: x, y, w, h = cv2.boundingRect(contour) rect = cv2.rectangle(im2, (x, y), (x + w, y + h), (0, 255, 0), 2) cropped_image = im2[y:y + h, x:x + w] #crop the text block file = open("Output.txt", "a") text = pytesseract.image_to_string(cropped_image) #applying OCR file.write(text) file.write("n") file.close()Input image:

Output image:

2. Convert your PDF File to Audio Speech

Say you have some book as PDF to read, but you are feeling too lazy to scroll; how good it would be then if that PDF is converted to an audiobook. So, let’s implement this using python.

We will need these two packages:

pyttsx3: It is for Text to Speech, and it will help the machine speak.

PyPDF2: It is a PDF toolkit. It is capable of extracting document information, merging documents, etc.

Install them using these commands:

pip install pyttsx3 pip install PyPDF2Steps:

Import the required modules.

Use PdfFileReader() to read PDF file.

getPage() method is used to select the page to be read from.

Extract the text using extract text().

By using pyttx3, speak out the text.

Code:

# import the modules import PyPDF2 import pyttsx3 # path of your PDF file path = open('Book.pdf', 'rb') # PdfFileReader object pdfReaderObj = PyPDF2.PdfFileReader(path) # the page with which you want to start from_page = pdfReaderObj.getPage(12) content = from_page.extractText() # reading the text speak = pyttsx3.init() speak.say(content) speak.runAndWait()That’s it! It will do the job. This small code is beneficial to you when you don’t want to read; you can hear.

Next, you can provide a GUI to this project using tikinter or anything else. You can give a GUI to enter the pdf path, the page number to start from, a stop button. Try this!

Let’s move to the next project.

3. Reading mails and downloading attachments from the mailboxLet’s understand what the benefit of reading the mailbox with Python is. So, let’s suppose if we are working on a project where some data comes daily in word or excel, which is required for the script as input or to Machine learning model as input. So, if you have to download this data file daily and give it to the hand, it will be hectic. But if we can automate this step, read this file, and download the required attachment, it would be a great help. So, let’s implement this.

We will use pywin32 to implement automatic attachment download from a particular mail. It can access Windows applications like Excel, PowerPoint, Word, Outlook, etc., to perform some actions. We will focus on Outlook and download attachments from the outlook mailbox.

Note: This does not need authentication like user email id or password. It can access Outlook that is already logged in to your machine. (Keep the outlook app open while running the script).

In the above example, we chose smtplib because it can only send emails and not download attachments. So, we will go with pywin32 to download attachments from Outlook, and it will be pretty straightforward. Let’s look at the code.

Command to install: pip install pywin32

Import module

import win32com.clientNow, establish a connection to Outlook.

outlook = win32com.client.Dispatch(“Outlook.Application”).GetNamespace(“MAPI”)

Let’s try to access Inbox:

inbox = outlook.GetDefaultFolder(number)This function takes a number/integer as input which will tell the index of the inbox folder in our outlook app.

To check the index of all folders, just run this code snippet:

import win32com.client outlook=win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") for i in range(50): try: box = outlook.GetDefaultFolder(i) name = box.Name print(i, name) except: passOutput:

3 Deleted Items 4 Outbox 5 Sent Items 6 Inbox 9 CalendarAs you can see in the output Inbox index is 6. So we will use 6 in the function.

inbox = outlook.GetDefaultFolder(6)If you want to print the subject of all the emails in the inbox, use this:

messages = inbox.Items # get the first email message = messages.GetFirst() # to loop through all the email in the inbox while True: try: print(message.subject) # get the subject of the email message = messages.GetNext() except: message = messages.GetNext()There are other properties also like “message. subject”, “message. senton”, which can be used accordingly.

Downloading AttachmentIf you want to print all the names of attachments in a mail:

for attachment in message.Attachments: print(attachment.FileName)Let’s download an attachment (an excel file with extension .xlsx) from a specific sender.

import win32com.client import re import os outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") inbox = outlook.GetDefaultFolder(6) messages = inbox.Items message = messages.GetFirst() while True: try: if re.search('Data Report', str(message.Subject).lower()) != None and re.search("ABC prasad", str(message.Sender).lower()) != None: attachments = message.Attachments for attachment in message.Attachments: if ".xlsx" in attachment.FileName or ".XLSX" in attachment.FileName: attachment_name = str(attachment.FileName).lower() attachment.SaveASFile(os.path.join(download_folder_path, attachment_name)) else: pass message = messages.GetNext() except: message = messages.GetNext() exit ExplanationThis is the complete code to download an attachment from Outlook inbox. Inside try block, you can change conditions. For example, I am searching for those mails which have subjects such as Data Report and Sender name “ABC prasad”. So, it will iterate from the first mail in the inbox, and if the condition gets true, it will then look if that particular mail has an attachment with the extension .xlsx or .XLSX. So you can change all these things subject, sender, file type and download the file you want. Once it finds the file, it is saved to a path given as “download_folder_path”.

End NotesWe discussed three projects in a previous article and three in this article. I hope these python projects with codes helped you to polish your skill set. Just do some hands-on and try these; you will enjoy coding them. I hope you find this article helpful. Let’s connect on Linkedin.

Thanks for reading 🙂

Happy coding!

The media shown in this article is not owned by Analytics Vidhya and are used at the Author’s discretion.

## How To Use Smartsheet: A Tutorial For Beginners

For a cloud- and web-based tool for tracking projects, tasks, lists, team members, and more, chúng tôi offers extensive and flexible features.

If you’re considering giving it a try or have already signed up for a free trial, making the most of the tool means knowing what it can do for you and your team. Let’s delve into how to use Smartsheet for beginners just getting started.

Table of Contents

What is Smartsheet?If you’ve ever used applications like Asana, chúng tôi or similar project management software, Smartsheet is comparable in purpose, structure, and features. You can use it alone or collaborate with others, create dashboards for quick access to items, and enjoy multiple views like Kanban, calendar, and grid.

Smartsheet also provides automated workflows, templates for quick starts, helpful reports, custom forms, and integrations with other applications to streamline your processes.

The best way to begin using Smartsheet is to create or import a project, sheet, or list of tasks that you want to track. We’ll then walk you through the features of each tool.

Create, Import, or Use a TemplateChoose Create, and you have eight options for Grid, Project, Cards, Task List, Form, Report, and Dashboard/Portal. Select the type of item you want to create, give it a name, and pick Create.

Choose Import if you have a project plan or task sheet elsewhere that you’d like to start with. Pick Microsoft Excel, Microsoft Project, Google Sheets, or Atlassian Trello. Then follow the prompts to import the item.

If you’d like to start with a template or template set, choose Browse All Solutions, select an industry, or use the Search box to find something specific.

Select a template or set to see additional information. Then to use a template, select the Use button.

For a template set, select Learn More to get full details on what’s included and download the set.

Use the Project AssistantIf it’s a new project that you want to start with, you can also use the Project Assistant. This gives you a head start on setting up the project.

In the Solution Center, select Project Assistant. Name your project, enter two tasks to get started, and add two subtasks for Task #1.

You’ll then see the Grid View layout for your new project with the tasks and subtasks you entered.

Project FeaturesTracking your project in Smartsheet is easy with project management tools built right in like the Gantt View.

You can add baselines and show or hide the critical path using the icons on the top right.

Select the gear icon to open the Project Settings. Then adjust the Dependency Settings, Timeline Display, and Resource Management.

Task List FeaturesThe task list has exactly what you need to track your to-dos from start to finish.

Enter the task name, due date, assignee, and status. Use the Done column to mark tasks completed and the Comments section for notes.

Cards FeaturesIf you like the Kanban method of project management, you can use the Cards layout, whether for yourself or your team.

You’ll start with lanes for Uncategorized, Backlog, Planning, In Progress, and Complete. However, you can change these labels per your project.

Choose between a compact or full view of your cards and adjust the Card View settings with the gear icon on the top right.

Grid Features Form FeaturesBuilding a custom form is a useful feature for all sorts of projects. With Smartsheet, you can design your form and adjust its settings easily.

Add and remove Form Elements with the section on the left. Then, select a form field to adjust its particular settings on the right. For example, you can make a field required, include a label or help text, use validation, and add logic.

Adjust the form settings for the Theme and Brand, Security, Form Submission, and emails for submissions.

Report FeaturesCreate a Row Report, Summary Report, or both. Select the sheet or project and add the columns. You can add filters, sort and group columns, and include a summary at the top.

Dashboard FeaturesBy creating a Smartsheet dashboard, you can see a snapshot of your project, check on active items, see a handy chart, or view metrics.

Give your dashboard a name, and then choose the widgets you want to use. You’ll see a nice selection of widgets on the right and simply select one to add it.

Smartsheet Navigation, Layout, and ToolsSmartsheet offers an easy way to navigate the application as well as use the tools.

Left-Hand NavigationOn the left side you have the main navigation for Home, Notifications, Browse, Recents, Favorites, WorkApps, and the Solution Center. When you log into Smartsheet, select where you’d like to start.

At the bottom, select the Help icon (question mark) icon for assistance or the Account icon to adjust your profile and settings.

Right-Side ToolsOn the right side are tools. You’ll see these on the screen for each item you use, such as a Project, Task List, or Cards. Exceptions are the Dashboard and Report.

When you select a tool, a sidebar displays containing the corresponding items. You have Conversations, Attachments, Proofs, Update Requests, Publish, Activity Log, and Summary.

Top ToolbarOn the top of each item, you have additional tools. On the left side, you can save, print, undo, or redo an action. Directly next to that, you can change your view which is quite handy. Switch between the Grid, Gantt, Card, or Calendar views.

You’ll also see font and format buttons similar to what you see in Microsoft Word. This allows you to change the font style, size, or color, change the alignment, format as currency, and more.

Additional Smartsheet Features and OptionsOnce you learn the basics of how to use Smartsheet, take a look at these additional features and options.

Sharing: Along with the real-time conversations and collaboration tools, you can adjust the sharing and permission settings for your team. Use the Share button on the top right to view your options.

Integrations: Connect Smartsheet to apps like Slack, Google Drive, Gmail, OneDrive, Jira, and more. To view your options, go to the Solution Center, pick Browse All Solutions, and select See More Add-Ons in the Add-Ons section.

Automated Workflows: Automate tasks for your project or sheet by selecting a trigger and action. You can automate things like notifications, approval requests, recording a date, or locking rows. Select the Automation tab above the top toolbar.

You can also create a workspace, use conditional formatting, and check out functionality for creating a web or mobile app for your company.

Smartsheet is a full-featured, robust tool for managing projects of all sizes. Be sure to check out their subscription plan pricing for the best fit for you.

## Python Range() Function: A Complete Guide (With Examples)

In Python, you can use the built-in range() function to generate a range of numbers from a start point to an end point.

For instance, let’s create a range of numbers from 0 to 5 and print them out:

numbers = range(0,6) for number in numbers: print(number)Output:

0 1 2 3 4 5Notice how the last number in the range() call is 6. This means the last number included in the range is actually 5.

In Python, you can call the range() function with one, two, or three parameters.

Here are some examples:

# Range from 0 to 9 range(10) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # Range from 5 to 9 range(5, 10) # 5, 6, 7, 8, 9 # Range from 1 to 100 with step size of 10 range(0, 110, 10) # 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 # Reversed range from 100 to 0 with step size of -10. range(100, -10, -10) # 100, 90, 80, 70, 60, 50, 40, 30, 20, 10If you’re looking for a short answer, I’m sure the above examples help you. But to truly learn how to use the range() function in different situations, I recommend reading the entire post.

This is a comprehensive guide to the range() function in Python. In this guide, you will learn thoroughly how to use the range() function in Python.

The range() Function in PythonIn Python, the built-in range() function produces an immutable sequence of numbers between start and end values.

The complete syntax of using range() function is as follows:

range(start, stop, step)Where:

start is the lower limit for the range. This is an optional parameter with a default value of 0.

stop is the upper limit for the range. The range consists of numbers until this value. Notice how it never includes the stop value in the range!

step is the step size for the range. This is an optional argument that defaults to 1. Each number in the range is generated by adding step to the previous value.

The range() function returns a range object. You can loop through this range object with a for loop. It is also possible to convert the range object into a list.

In Python 3, there are three syntactical variations of how to use the range() function:

range(stop)

range(start, stop)

range(start, stop, step)

Let’s go through each of these alternatives in more detail.

1. range(start)The most basic way to use the range() function in Python is by specifying only the end value for the range.

range(stop)When you do this, the range automatically starts from 0 and takes steps of size 1. It ends one before the stop value.

For example, let’s generate a range of numbers from 0 to 5:

numbers = range(6) for number in numbers: print(number)Output:

0 1 2 3 4 5Here the range starts from 0 because you did not specify a starting value. The range ends at the value of 5 instead of 6 due to the exclusive nature of range() function.

2. range(start, stop)Another way you can call the range() function in Python is by specifying both start and stop values. This is useful if you want the range to start from a value other than 0, which commonly is the case.

range(start, stop)For instance, let’s generate values from 5 to 10:

numbers = range(5,11) for number in numbers: print(number)Output:

5 6 7 8 9 10Notice that the start value 5 is included in the range, but the end value 11 is not. This might cause confusion if it’s your first time using the range() function.

3. range(start, stop, step)The third option to call the range() function is by specifying start, stop, and step parameters.

range(start, stop, step)The step parameter sets the interval for the range. In other words, it affects the way the range is generated by adding a value other than 1 to the previous number.

For example, let’s generate a range of values from 50 to 100 with by using 10 as a step size:

numbers = range(50,110,10) for number in numbers: print(number)Output:

50 60 70 80 90 100 The range() Function Return ValueNow that you know how to use the range() function in Python, let’s take a closer look at the return value.

In Python, the range() function returns a range object.

For example, let’s create a range of numbers and print the object. Let’s also print the type of the range using the built-in type() function:

numbers = range(5, 10) print(numbers) print(type(numbers))Output:

range(5, 10)The result of printing the range is not a list of numbers as you might expect. Instead, it’s a range object. In other words, the range() function returns a special range object.

The range object is iterable by nature. This means you can loop through it like any other iterable, such as a list. This is what you already saw in the previous examples.

Of course, you can also convert the range object into another iterable type, such as a list.

For example, let’s generate a range of numbers and convert it to a list with the built-in list() function:

numbers = range(50,110,10) numbers_list = list(numbers) print(numbers_list)Output:

[50, 60, 70, 80, 90, 100]Now the result is a regular Python list instead of a range object. So if you need to generate a range as a list, you can easily cast the range object into a list.

Keep in mind the range object is a range object for performance reasons. If there’s no need to cast the range to a list, don’t do it!

Reversed Range in PythonIn Python, it is possible to create a reversed range by specifying a negative step size to the range() function call.

For example, let’s generate a range of numbers from 100 to 50:

numbers = range(100, 40, -10) for number in numbers: print(number)Output:

100 90 80 70 60 50Make sure you understand why this works.

The range starts from the start parameter, but it stops one step before the stop parameter. Thus the stop is set to 40 to include 50 in the range.

As the step is -10, the range takes steps of size -10. In other words, it decreases the start by 10 until the stop value.

But why do you need to specify the step value at all? How about range(100, 40)?

As you remember, the range(100, 40) would mean that the step is 1 (by default) which would mean range(100, 40, 1).

This confuses Python as it tries to get from 100 to 40 by adding ones to 100, which is impossible.

Thus the result is an empty range.

numbers = range(100, 40) numbers_list = list(numbers) print(numbers_list)Output:

[] Negative Range in PythonIn Python, you can use the built-in range() function to produce a range of negative numbers.

When speaking about negative ranges in Python, you may refer to:

Negative range with increasing numbers, that is, a positive step.

Negative range with decreasing numbers, that is, a negative step.

Let’s see an example of each.

Negative Range with Increasing NumbersFor example, let’s create a range of numbers from -1 to -5:

numbers = range(-1, -6, -1) for number in numbers: print(number)Output:

-1 -2 -3 -4 -5Notice how you need a negative step size to make the range work. This is because it is not possible to get smaller values by adding positive values.

In other words, if you did not specify a negative step:

numbers = range(-1, -6) print(list(numbers))Your result would be an empty range, that is, no values at all:

[] Negative Range with Increasing NumbersTo produce a range of negative values in increasing order, use the built-in range() function the same as you use it with positive numbers.

For example, let’s create a range of negative numbers from -10 to -5.

numbers = range(-10, -4) for number in numbers: print(number)Output:

-10 -9 -8 -7 -6 -5Notice how the step parameter is not needed as you are increasing the numbers by one.

Range Indexing in PythonIn Python, the range() function produces a range object. This range object supports indexing the same way other iterables, such as lists, do.

For example, let’s get the second number in a range of numbers:

numbers = range(1, 6) # 1, 2, 3, 4, 5 second = numbers[1] print(second)Output:

2Needless to mention range objects support negative indexing too.

For example, let’s get the last element of a range using negative indexing -1:

numbers = range(1, 6) # 1, 2, 3, 4, 5 last = numbers[-1] print(last)Output:

5 Range Slicing in PythonPython range objects support slicing. This means you can get a partial group of numbers from a range using slicing.

When you slice a range object in Python, you get a range object as a result. This range object contains the part of the original range.

If you are unfamiliar with slicing in Python, feel free to check this article.

For example, let’s get the first 3 numbers in a range:

numbers = range(1, 10) first_three = numbers[0:3] for number in first_three: print(number)Output:

range(1, 4)A common way to use slicing in Python is to reverse an iterable with slicing by [::-1]. You can do the same for a range of numbers too.

For instance, let’s reverse a range of numbers from 1 to 5:

numbers = range(1, 6) rev = numbers[::-1] for number in rev: print(number)Output:

5 4 3 2 1 Inclusive RangeThe Python range() function produces a range of values that does not include the last value by default.

For example range(0,5) produces a range of values 0, 1, 2, 3, 4.

To create an inclusive range, that is, to add the stop value into the range too, add the step value to the stop value.

For example, let’s create a range of values from 1 to 5 inclusively:

step = 1 numbers = range(1, 5 + step, step) print(list(numbers))Output:

[1, 2, 3, 4, 5] For Loops with range() in PythonA common way to utilize the range() function is with for loops.

Loop Through Numbers with range()The most basic use case is when looping through numbers from n to m.

For example, let’s print numbers from 1 to 5:

numbers = range(1,6) for number in numbers: print(number)Output:

1 2 3 4 5 Loop with an Index Using range() FunctionAnother common use case for the range() is to access the index (or indexes) of an element with a for loop.

For example, let’s print a list of names and their index in the list:

queue = ["Alice", "Bob", "Charlie", "David"] for pos in range(len(queue)): print(f"{pos}: {queue[pos]}")Output:

0: Alice 1: Bob 2: Charlie 3: DavidAlthough there’s a much better solution to get the indexes by using the enumerate() function. Let’s have a look at how this function works.

Alternative to range() Function with For LoopsNow you know the range() can be used in a for loop to get the index of the elements. Meanwhile, this is commonly taught for beginners, it is not the ideal way to do it.

Instead, you should use a built-in enumerate() function.

For example, let’s repeat the example of printing the list of names and their index. Let’s not use range() this time, but enumerate() instead:

queue = ["Alice", "Bob", "Charlie", "David"] for pos, name in enumerate(queue): print(f"{pos}: {name}")Output:

0: Alice 1: Bob 2: Charlie 3: DavidIn short, the enumerate() function couples the list elements with their index.

In the above example, the enumerate(queue) produces an object with position, name pairs:

[(0, 'Alice'), (1, 'Bob'), (2, 'Charlie'), (3, 'David')] ConclusionToday you learned how to use the range() function in Python.

To recap, the range() function returns a range of values from n until m.

For example range(5) returns numbers 0,1,2,3,4.

The result of the range() function is a range object. You can use the range object to loop through the range. Alternatively, you can cast the range object to a list to get a list that represents a range of numbers.

There are three ways to call the range function in Python:

range(start)

range(start, stop)

range(start, stop, step)

Thanks for reading. Happy coding!

Further Reading50 Python Interview Questions

## Python Generators And Iterators In 2 Minutes For Data Science Beginners

This article was published as a part of the Data Science Blogathon

IntroductionWe are continuing our Python: Understanding in 2 minutes series where we cover the medium-level topics that are also frequently asked in Python and Data Science interviews. Last time, we talked about an important topic called *args and **kwargs in 2 minutes. This series is dedicated to aspiring data scientists who want to take the “next step” in Python after learning the basics. Today, we’ll continue our discussion with yet another important topic called Generator and Iterator.

Iterators in PythonThe dictionary meaning of “iterate” is to “perform a task repeatedly”.

In computer programming, Wikipedia defines iterators as:

An iterator is an object that enables a programmer to traverse a container, particularly lists.

So, we get the idea that iterators have got to do something with traversing the elements.

Now, what does it mean when something is iterable? It simply means that the items can be looped over. The list is an example of an iterable because we can loop the elements.

Image source: Github user Ethen8181

Let’s try a very simple example by considering this logic. We will first create a list and will try to implement Python’s built-in iter() method to our list.

my_list = [1,2,3,5,8,13] # converting to a list_iterator with iter() final_list = iter(my_list) final_listThe output would look something like this:

Let’s try to implement the next() function to our final_list.

next(final_list)Output:

1This is the first item on our list.

Again, try doing the same thing:

next(final_list)Output:

2This is the second item on our list.

One more time:

next(final_list)Output:

3This is the third item on our list.

So, basically, we get the idea that the iter() method makes converts an iterable item (such as a list) to an iterator.

To summarize:

An iterable is an object that can be converted into an iterator (just the way we converted a list into a list_iterator).

An iterator is an object that has a next() method.

I assume we don’t have any confusion with iterable and iterator now.

GeneratorsImage Source: Morioh

Wikipedia defines Generators as:

One way of implementing iterators is to use a restricted form of coroutine, known as a generator. By contrast with a subroutine, a generator coroutine can yield values to its caller multiple times, instead of returning just once.

We shift our focus to Generators now. Python generators are a simple way of creating iterators. It is a function that returns an object (iterator) which we can iterate over (one value at a time). Let’s see a simple example without a generator and then try to implement a generator to the same operation. We would like to create a function that squares up all the elements in the list. Let’s see how we perform this operation normally.

def square(my_list): result = [] for i in my_list: result.append(i**2) return resultAnd now, let’s pass a list and see the result.

final = square([1,2,3,4,5]) finalOutput:

[1, 4, 9, 16, 25]The process was pretty straightforward. We implemented a function where we initialized a new empty list called “result”. Then, we looped through “my_list” that we wanted to pass and we appended the squared result to our previously empty “result” list one by one. Pretty straightforward, right? And on top of that, it’s calculating everything at once. This means, it’s consuming more memory, and performance-wise, this process may be inefficient.

What if we try out the same thing with a generator?

def square(my_list): for i in my_list: yield i**2And let’s pass a list:

final = square([1,2,3,4,5]) finalOutput:

Notice, it created a generator object, and therefore, we can implement a next() function to our final variable. Let’s try:

next(final)Output:

1Let’s do it again!

next(final)Output:

4One more time:

next(final)Output

9What did we do differently here? In our second example, we created a function like the previous. Then, instead of initializing an empty list, we directly looped through our list to be passed on. In each loop, we yield the corresponding square value and that was it! Finally, we created a “final” variable to pass our intended list. This is our generator. Upon applying the next() method, we obtained the squared values every time. This means, not every result was calculated at once. This is called lazy evaluation in Python. In short, a lazy evaluation is a process in which an object is evaluated when it is needed, not when it is created.

What is “yield” doing?Yield simply produces a sequence of values. We generally use yield when we want to iterate over a sequence, but the idea is that the yield method doesn’t store the entire sequence in memory but executes only when they are told. Note that you can have multiple yield statements inside a function but you cannot have multiple returns.

Closing up, Generators do not store all the values in memory. They yield one result at a time. They are best for calculating large result sets where you don’t want to allocate the memory for all results at the same time.

In the endThe concepts of iterators, iterable, yield, and generators are mostly intermediate-level stuff that beginners often aren’t familiar with. Also, from my professional experience, these topics are frequently asked in the interview process as well. Understanding these concepts demands practice.

About the Author:Hi there! My name is Akash and I’ve been working as a Python developer for over 4 years now. In the course of my career, I began as a Junior Python Developer at Nepal’s biggest Job portal site, Merojob. Later, I was involved in Data Science and research at Nepal’s first ride-sharing company, Tootle. Currently, I’ve been actively involved in Data Science as well as Web Development with Django.

You can find my other projects on:

Connect me on LinkedIn

End Notes:Thanks for reading!

Previous blog posts in this series:

**args and **kwargs in 2 minutes

I am also planning to start The Data Science Blog on my Github page. I will try to include how real companies have been working in the field of Data Science, how to excel in Data Science and/or tech interviews, and other useful content related to Python and general programming. Feel free to check them once in a while.

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.

Related

## Asp.net Web Forms Tutorial: User Controls Examples

In chúng tôi it is possible to create re-usable code. The re-usable code can be used in many places without having the need to write the code again.

The re-usable code helps in reducing the amount of time spent by the developer after writing the code. It can be done once and reused at multiple places.

In this tutorial, you will learn-

Create User Control in ASP.NetASP.Net has the ability to create Web controls. These controls contain code which can be re-used. It can be used across application as per the requirement.

Let’s take a look at an example of how we can create a web user control in ASP.Net

In our example,

We are going to create a web control.

It will be used to create a header component.

It will contain the below mentioned text.”Guru99 Tutorials

“This Tutorial is for ASP.Net”

Let’s work with our current web application created in the earlier sections. Let’s follow the below steps to create a Web user control.

Step 1) The first step is to create a web user control and add it to our Visual Studio Solution.

Step 2) In the next step, we need to choose the option of creating a web user control

We then give a name for the Web Control “Guru99Control”.

You will the see the “Guru99Control” added to the solution.

Step 4) Now it’s time to add the custom code to the Web user control. Our code will be based on pure HTML syntax. Add the following code to the ‘Guru99Control.ascx’ file

Code Explanation:-

In our Web Control file, we are first creating a table element. This will be used to hold 2 rows of text which will be used to display

“Guru99 Tutorials” and

“This Tutorial is for ASP.Net.”

Next, we define our first table row and put the text as “Guru99 Tutorials.”

We then define our second table row and put the text as “This Tutorial is for ASP.Net.”

NOTE: Now we cannot execute this code and show the output. The only way to see if this works is to include it in our application (aspx file). We will see this in the sub-sequent topic.

Registering User Controls on a chúng tôi web formsIn the earlier section, we saw how we can create a custom web control. This can be used to display the following two lines in a web form

“Guru99 Tutorials”

“This Tutorial is for ASP.Net.”

Once the custom ‘control’ is created, we need to use it in our web application. The first step is to register the component in our application (Demo.aspx). This is the pre-requisite to use in any custom web control in an chúng tôi application.

Let’s look at how we can achieve this. The below steps are a continuation to the previous section. In the previous section, we have created our custom control. In this section, we will use the control in our Demo.aspx web form.

First, we will register our custom ‘control’ into the chúng tôi file.

The default code consists of steps, which are required to ensure that the form can run as an chúng tôi web form in the browser.

Step 2) Now let’s add our code to register the user control. The screenshot below shows registration of the user control to the above basic code.

Code Explanation:-

The first step is to register the web user control. This comprises of the below basic parameters

The ‘Register’ keyword is used to register the web user control.

The src parameter is used to define the name of the control, which in our case is Guru99Control.ascx.

The tagname and Tagprefix are individual names given to the control. This is done so that they can references in HTML pages as a normal HTML control.

Next, we reference our Web user control via the TagPrefix:TagName which was assigned earlier. The TagPrefix:TagName is an indicator that we want to use our custom web control. When the page is processed by the web server, you can see we have used the TWebControl:WebControl tag. It will then process the ‘Guru99Control’ chúng tôi our example, it is TWebControl:WebControl.

An optional ID is given to the control of “Header”. It’s generally a good practice to give an ID to an HTML control.

Finally, the runat=server attribute so that the control will run on the web server. For all chúng tôi controls, this is the default attribute. All chúng tôi controls (including custom controls) have to be run on the server. Their output is then sent from the server to the client and displayed in the browser accordingly.

When the above code is set, and the project is executed using Visual Studio. You will get the below output.

Output:-

The output message displayed in the browser shows that the web user control was successfully executed.

Registering chúng tôi controls globally in the web config configuration file aspSometimes one might want to use user controls in multiple pages in a .Net application. At this point, you don’t want to keep on registering user controls on each and every chúng tôi page.

In .Net you can carry out the registration in the ‘web.config’ file.

The web.config file is a common configuration file used by all web pages in .Net project.

It contains necessary configuration details for the chúng tôi web project. For example, one common configuration in the web.config file is the target framework parameter.

This parameter is used to identify the .Net framework version used by the application.

Below is a snapshot of the default code in the web.config file. The highlighted part is the target framework part.

Let’s see how we can register our Guru99Control in the web.config file.

When you open the web.config file, you might see the below configuration. The ‘web.config’ is added automatically by Visual Studio when the project is created. This is the basic configuration required to make the chúng tôi project work properly.

Step 2) Now let’s register our component in the web.config file. We need to add the below lines for that.

The registration comprises of the below substeps

Then we register the user control with the additional tag. The remaining parameters of tagPrefix, tagName and src remain the same as before.

Step 3) Remember to go the ‘demo.aspx’ page and remove the lines for control, which had the registration of the Guru99 component. If you don’t perform this step, then the ‘Guru99Control.ascx’ a file will be executed from the ‘demo.aspx’ file instead of ‘web.config’ file.

The above code is set, and the project is executed using Visual Studio. You will get the below output.

Output:-

The output message shows that the web user control was successfully executed.

Adding public properties to a web controlDemo Form

The ‘div’ tag is used to create a section in an HTML document. The ‘div’ tag has a property called a style property. This can be used to give a different style to the text displayed in the div tag. Normally you would see the code for the div tag as shown below.

So the color attribute is nothing but a key-value pair which gives more information on the tag itself. In the above case, the key name is ‘style’ and the key value is ‘color:#0000FF’.

Similarly, for user controls, you can create your own properties that describe the control.

Let’s take a simple example and build upon our ‘Guru99Control’ created in the earlier sections.

In our example, we are going to add a simple integer property called MinValue. This value would represent the minimum number of characters in the text displayed in the user control.

Let’s carry out the below-mentioned steps to get this in place.

Step 1) Open the chúng tôi file. Add the code for adding the MinValue property.

public int MinValue = 0;

Code Explanation:-

The script runat=server attribute is used to indicate that we are adding chúng tôi specific code and that it needs to be run on the web server.

This is required for processing any property added to the user control. We then add our property MinValue and give it a default value of 0.

Step 2) Now let’s reference this property in our chúng tôi file. All we are doing now is just referencing the MinValue property and assigning a new value of 100.

NOTE: – When you run this code, it will not show any output. This is because the output falls under 100 character limit.

Summary

ASP.Net has the ability to create user controls. User controls are used to have code which is used multiple times in an application. The user control can then be reused across the application.

The user control needs to be registered on the chúng tôi page before it can be used.

To use user control across all pages in an application, register it into the web.config file.

Properties can also be added to a web user control.

Update the detailed information about **Python Numpy Tutorial For Beginners: Learn With Examples** on the Daihoichemgio.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!