Question:
Perform the following operations on the below tuple (‘abc’, ‘def’, ‘ghi’, ‘jklm’, ‘nopqr’, ‘st’, ‘uv’, ‘wxyz’, ’23’, ‘s98’, ‘123’, ’87’)
prints the length of the tuple
Slicing
Reverse all items in the tuple
Removing whole tuple
Concatenate two tuples
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
tup = ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') # prints the length of the tuple print('\ntuple: ', tup) print('Length of the tuple is : ', len(tup)) # Slicing # shows only items starting from 0 upto 3 print('\ntuple: ', tup) print('tuple showing only items starting from 0 upto 3\n', tup[:3]) # shows only items starting from 4 to the end print('\ntuple: ', tup) print('tuple showing only items starting from 4 to the end\n', tup[4:]) # shows only items starting from 2 upto 6 print('\ntuple: ', tup) print('tuple showing only items starting from 2 upto 6\n', tup[2:6]) # reverse all items in the tuple print('\ntuple: ', tup) print('tuple items reversed \n', tup[::-1]) # removing whole tuple del tup tup_0 = ("ere", "sad") tup_1 = ("sd", "ds") print('\nfirst tuple: ', tup_0) print('second tuple: ', tup_1) tup = tup_0 + tup_1 print('Concatenation of 2 tuples \n', tup) |
Explanation:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') Length of the tuple is : 12 tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 0 upto 3 ('abc', 'def', 'ghi') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 4 to the end ('nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple showing only items starting from 2 upto 6 ('ghi', 'jklm', 'nopqr', 'st') tuple: ('abc', 'def', 'ghi', 'jklm', 'nopqr', 'st', 'uv', 'wxyz', '23', 's98', '123', '87') tuple items reversed ('87', '123', 's98', '23', 'wxyz', 'uv', 'st', 'nopqr', 'jklm', 'ghi', 'def', 'abc') first tuple: ('ere', 'sad') second tuple: ('sd', 'ds') Concatenation of 2 tuples ('ere', 'sad', 'sd', 'ds') |
Question:
Write a program to check the validity of password input by users.
Accept a sequence of comma separated passwords and check them according to the above criteria. Print the valid passwords
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import re value = [] items=[x for x in raw_input("Enter passwords separated by commas for checking validity.Press Enter to end.\n").split(',')] for p in items: if len(p)<6 or len(p)>12: continue else: pass if not re.search("[a-z]",p): continue elif not re.search("[0-9]",p): continue elif not re.search("[A-Z]",p): continue elif not re.search("[$#@]",p): continue elif re.search("\s",p): continue else: pass value.append(p) print "Valid passwords",value |
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
3. At least 1 letter between [A-Z]
4. At least 1 character from [$#@]
5. Minimum length of transaction password: 6
6. Maximum length of transaction password: 12
Output:
1 2 3 4 5 |
Enter passwords separated by commas for checking validity.Press Enter to end globalsqa,#GlobalSQA2 Valid passwords ['#GlobalSQA2'] |
Question:
Write a program to print the following pattern
1 2 3 4 5 |
* * * * * * * * * * * * * * * |
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# on to demonstrate printing pattern def invert_triangle(n): # number of spaces k = 2*n - 2 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 2 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") n = 5 invert_triangle(n) |
Question:
Print the below pattern
1 2 3 4 5 6 7 8 |
1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 6 5 4 3 2 1 7 6 5 4 3 2 1 8 7 6 5 4 3 2 1 |
Program:
1 2 3 4 |
for i in range(1, 8 + 1): for j in range(i, 0, -1): print(j), print("") |
Question:
Write a program to print the following pattern
1 2 3 4 5 |
* * * * * * * * * * * * * * * |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
def pyramid(n): # number of spaces k = 2*n - 2 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") n = 5 pyramid(n) |
Question:
With a given list [5,3,5,3,6,8,3,1,9,4,5,9,0,7], write a program to print this list after removing all duplicate values with original order reserved.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 |
<strong>def removeD</strong>uplicate( li ): newli=[] seen = set() for item in li: if item not in seen: seen.add( item ) newli.append(item) return newli li=[5,3,5,3,6,8,3,1,9,4,5,9,0,7] print (removeDuplicate(li)) |
Explanation:
Set() function stores number of values without duplicate.
Output:
1 |
[5, 3, 6, 8, 1, 9, 4, 0, 7] |
Question :
Swap two variables without using a third temporary variable
Program:
1 2 3 4 5 |
num1= int(input("Enter the first number:")) num2=int(input("Enter the second number:")) print "num1:",num1,"num2:", num2 num1,num2=num2,num1 print "After swap: num1:",num1,"num2:", num2 |
Explanation:
Here num1, num2 acts as a tuple. Since tuples are mutable, the above assignment works perfectly well
Output:
1 2 3 4 |
Enter the first number:8 Enter the second number:99 num1: 8 num2: 99 After swap: num1: 99 num2: 8 |
Question:
A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following:
UP 5
DOWN 3
LEFT 3
RIGHT 2
The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer.
Example:
If the following tuples are given as input to the program:
UP 5
DOWN 3
LEFT 3
RIGHT 2
Then, the output of the program should be:2
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import math pos = [0,0] while True: s = raw_input() if not s: break movement = s.split(" ") direction = movement[0] steps = int(movement[1]) if direction=="UP": pos[0]+=steps elif direction=="DOWN": pos[0]-=steps elif direction=="LEFT": pos[1]-=steps elif direction=="RIGHT": pos[1]+=steps else: pass print int(round(math.sqrt(pos[1]**2+pos[0]**2))) |
Explanation:
The distance formula is derived from the Pythagorean theorem. To find the distance between two points (x1,y1) and (x2,y2), all that you need to do is use the coordinates of these ordered pairs and apply the formula d=√{(x2−x1)2+(y2−y1)2}.This formula is used to find the distance.
Output:
1 2 3 4 5 6 |
UP 20 RIGHT 70 UP 20 Left 60 81 |
Question:
Write a program that accepts a sequence of whitespace separated words as input and prints the words after removing all duplicate words and sorting them alphanumerically.
Program:
1 2 3 |
s = raw_input() words = [word for word in s.split(" ")] print " ".join(sorted(list(set(words)))) |
Explanation:
The string is accepted to s and split to a list using s.split. the list is then sorted and then joined to form the output string
Output:
1 2 |
GLOBALSQL is the best place to learn to code the best GLOBALSQL best code is learn place the to |
Question:
Define a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.Use yield.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
def putNumbers(n): i = 0 while i<n: j=i i=i+1 if j%7==0: yield j for i in putNumbers(100): print i |
Explanation
The yield statement is used to define generators, replacing the return of a function to provide a result to its caller without destroying local variables. Unlike a function, where on each call it starts with new set of variables, a generator will resume the execution where it was left off.
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
0 7 14 21 28 35 42 49 56 63 70 77 84 91 98 |
Question:
Write a program to sort the (name, age, height) tuples by ascending order where name is string, age and height are numbers.
1: Sort based on name;
2: Then sort based on age;
3: Then sort by score.
The priority is that name > age > score.
We use itemgetter to enable multiple sort keys.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from operator import itemgetter, attrgetter l = [] while True: s = raw_input("Enter Details: (Name,Age,Score)[Press Enter to end\n") if not s: break l.append(tuple(s.split(","))) print sorted(l, key=itemgetter(0,1,2)) |
Explanation:
operator
is a built-in module providing a set of convenient operators. In two words operator.itemgetter(n)
constructs a callable that assumes an iterable object (e.g. list, tuple, set) as input, and fetches the n-th element out of it.
Output:
1 2 3 4 5 6 7 8 9 |
Enter Details: (Name,Age,Score)Press Enter to end Lily,19,84 Enter Details: (Name,Age,Score)Press Enter to end Tom,21,67 Enter Details: (Name,Age,Score)Press Enter to end Mark,15,86 Enter Details: (Name,Age,Score)Press Enter to end [('Lily', '19', '84'), ('Mark', '15', '86'), ('Tom', '21', '67')] |
Question:
Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.
Program:
1 2 3 4 5 6 7 8 9 10 11 |
freq = {} # frequency of words in text line = raw_input("Enter Text:") for word in line.split(): freq[word] = freq.get(word,0)+1 words = freq.keys() words.sort() print "Frequency chart" for w in words: print "%s:%d" % (w,freq[w]) |
Explanation:
The sort() method sorts the elements of a given list in a specific order – Ascending or Descending.
Output:
1 2 3 4 5 6 7 8 9 10 11 |
Enter Text:Hey There! Hello and hello and welcome to GlobalSQA Welcome Frequency chart GlobalSQA:1 Hello:1 Hey:1 There!:1 Welcome:1 and:2 hello:1 to:1 welcome:1 |
Question:
Write a program to sort the string accepted from the user
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Program to sort alphabetically the words form a string provided by the user my_str = raw_input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word) |
Explanation:
The sort function returns the sorted data item.
Output:
1 2 3 4 5 6 |
Enter a string: GlobalSQA is the best! The sorted words are: GlobalSQA best! is the |
Below is a list of the top 20 Open Source Libraries. Note that the list is neither exhaustive or stagnant. In a strong community as that Python has, the list is prone to change. The list has been prepared on the basis of popularity, no of users, python community feedback etc. The 20 below does not fall in any specific order and arrangement is quite random.
At the end of the day, it’s not which library you use. It’s how well you get the job done.
So here goes the list!
Zappa is a system for running “serverless” Python web applications using AWS Lambda and AWS API Gateway. It handles all of the configuration and deployment automatically . Now it is easy to deploy an infinitely scalable application to the cloud with a just single command at the least possible cost often just a small fraction of the cost of a traditional web server.
OpenCV is a cross-platform library using which we can develop real-time computer vision applications.Originally developed by Intel, it was later supported by Willow Garage and is now maintained by Itseez.It was built to provide a common infrastructure for computer vision applications and to accelerate the use of machine perception in the commercial products. Being a BSD-licensed product, OpenCV makes it easy for businesses to utilize and modify the code.
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django takes care of the repetitive work for you so that you don’t have to reinvent the wheel all over again.
Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It is an incredible tool for pulling out information from a webpage. You can use it to extract tables, lists, paragraph and you can also put filters to extract information from web page.
TensorFlow is an open source software library for machine learning across a range of tasks, and developed by Google to meet their needs for systems capable of building and training neural networks to detect and decipher patterns and correlations, analogous to the learning and reasoning which humans use. Checkout SQL cheatsheet by clicking here
NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries, and an active discussion forum.
Requests is an elegant and simple Apache2 licensed HTTP library for PythonIt is designed to be used by humans to interact with the language. This means you don’t have to manually add query strings to URLs, or form-encode your POST data.
NumPy is the fundamental package for scientific computing with Python. It contains a powerful N-dimensional array object,sophisticated (broadcasting) functions,tools for integrating C/C++ and Fortran code,useful linear algebra, Fourier transform, and random number capabilities and much more. The handy tool for any scientific computing.
Flask is a BSD licensed microframework for Python based on Werkzeug, Jinja 2 and good intentions. With simplified and easy to write and maintain code, flask has certainly won a lot of hearts.
SQLAlchemy is an open-source Python Database toolkit, which is also an ORM Mapper.It allows you to write easy to read programs and remove the necessity of writing tedious and error-prone raw SQL statements. Checkout SQL cheatsheet by clicking here
Pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Checkout Pandas cheatsheet by clicking here
Cryptography is a method of storing and transmitting data in a particular form so that only those for whom it is intended can read and process it. It has become a highly important function in the modern world where security of data means everything.Cryptography is an actively developed library in python that provides cryptographic recipes and primitives.It is divided into two layers of recipes and hazardous materials (hazmat) catering it’s best to your various cryptographic needs.
Scrapy is an open source and collaborative framework for extracting the data you need from websites in a fast, simple, yet extensible way.Comparing with Beautiful Soup, you need to provide a specific url, and Beautiful Soup will help you get the data from that page. You can give Scrapy a start url, and it will go on, crawling and extracting data, without having to explicitly give it every single URL.Also scrapy is a website scraping tool that uses Python, because Scrapy can crawl the contents of your webpage prior to extracting
Marshmallow is a lightweight library for converting complex datatypes to and from native Python datatypes.It is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes.
Arrow is a Python library that offers a sensible, human-friendly approach to creating, manipulating, formatting and converting dates, times, and timestamps. It implements and updates the datetime type, plugging gaps in functionality, and provides an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code.
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits. Checkout Matplotlib cheatsheet by clicking here
The pillow is one of the core libraries for image manipulation in Python. Now there’s an actively developed fork of PIL called Pillow which is making quite a good round in the python community.
Bokeh is a Python interactive visualization library that targets modern web browsers for presentation. It’s goal is to provide elegant, concise construction of novel graphics in the style of D3.js, and to extend this capability with high-performance interactivity over very large or streaming datasets.
The easy to handle python library for all your CSV needs.CSV stands for Comma Separated Variables.They are like incredibly simplified spreadsheets whose contents are just plain text. Python’s CSV library makes working with them extremly simplified.
Milk is a machine learning toolkit for python. It’s focus is on supervised classification.Several classifiers available:SVMs (based on libsvm), k-NN, random forests, decision trees. It also performs
feature selection.
There are a lot more amazing libraries in Python that would come of as as a huge boon such as Asyncpg, urllib2,Theano,Tkinder, Pycrypto, Pygame etc. Want to add more to this list. Comment your suggestion below. We love hearing from you!
Flask is a micro web framework written in Python
Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.
virtualenv which is a virtual Python environment builder, is used to help a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.
The following command installs virtualenv
1 |
sudo pip install virtualenv |
Once installed, a new virtual environment is created in a folder.
1 2 3 |
mkdir FlaskTest cd FlaskTest virtualenv Test |
So now we have a virtual environment Test created in the FlaskTest folder
We now install Flask in this environment.
1 |
sudo pip install Flask |
Now we have Flask installed in our system and we can import it in our projects.
As we have setup environment to work with Flask library, lets run a sample code to test Flask. Let’s create a python file HelloWorld.py and write the following code:
1 2 3 4 5 6 7 |
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'HELLO WORLD’ if __name__ == '__main__': app.run() |
1 |
app.run(host, port, debug, options) |
All parameters for the run function are optional
host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). You have to set it to ‘0.0.0.0’ to have server available externally
port
Default value is 5000
debug
Default value is false. If it is set to true, we get debug information
options
To be forwarded to underlying Werkzeug server.
Now we can execute the program and see its working. Execute the program using the command
1 |
python HelloWorld.py |
You will get the following output.
1 |
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) |
Now if you open your browser and type in your localhost address that is, 127.0.0.1 along with the port number 5000
You can see HELLO WORLD being printed on your browser.
You can use Ctrl+C to stop running the program.
Now if you need to set a specific URL other than the homepage of localhost, you can specify it in the route() function.
If you change the route function in the above code to:
1 |
@app.route('/hello') |
And run the program again, you can see that opening the homepage of localhost renders no output, but instead if you add the URL specified in route function to the homepage address:
Now you can see your program being run…
Have fun working with Flask library
Maintaining the backends or servers is always a part of the headache for the programer. And here walk in the solution, serverless Architectures.
It refer to applications that significantly depend on third-party services (known as Backend as a Service or “BaaS”) or on custom code that’s run in ephemeral containers (Function as a Service or “FaaS”), the best known vendor host of which currently is AWS Lambda
Using an amazing library called Zappa, it is now easy to deploy in AWS Lambda.
Zappa is a system for running “serverless” Python web applications using AWS Lambda and AWS API Gateway. It handles all of the configuration and deployment automatically . Now it is easy to deploy an infinitely scalable application to the cloud with a just single command at the least possible cost often just a small fraction of the cost of a traditional web server.
You can install zappa easily using
1 |
pip install zappa |
To install AWS command tools,
1 |
pip install --dev awscli |
So before we start using Zappa, let’s create a simple hello world website using flask and run it on our locla server
At a directory of your choice, save the following program as Prg.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello world! ", 200 # We only need this for local development. if __name__ == '__main__': app.run() |
And run it on your local server using the following commands at your cmd
1 2 3 |
export FLASK_APP=Prg.py flask run |
Now check out http://127.0.0.1.5000/. You can see a simple webpage like below.
Before we get our hands on some zappa, we need to ensure we have a valid AWS account.
You can create a AWS account by following the steps one by one here.
After creating an account, run the following command to configure your AWS account in your command line and and fill in the access key id, the secret access key and the default region..
1 |
aws configure |
Let’s configure Zappa now.
Run the follwing command in your project directory
1 |
zappa init |
This creates a file named zappa_settings.json
inside our project directory with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
{ "dev": { "app_function": "Prg.app", "s3_bucket": "zappa-some-random-id", "runtime": "python3.6" } } |
Now deploy zappa using
1 |
zappa deploy |
And it’s done!!Thtat’s all it takes.!Just a single command!
To learn more of zappa, which I am sure you would want to, check out these sites:
Tensorflow considered one of most used Machine Learning library offered by Google. It is fast, flexible and easy for beginners as well as professionals. Below is the list of free Tensorflow ebooks with their download link curated from different sources. Hope, you will find them useful in preparing for Tensorflow.
If you would like to list your ebook free of cost or would like to contribute, do comment or reach out to us.
Below is a list of free Machine Learning Ebooks with their download link curated from different sources. There are in different formats like mobi, epub and pdf. In case, you don’t have mobi or epub reader please download it separately to view those files. I expect you must be having pdf viewer. Below mentioned books are not only associated with specific language or profile. Hope, you will find them useful in preparing for Machine Learning.
If you would like to list your ebook free of cost or would like to contribute, do comment or reach out to us.
Did you check Free TensorFlow ebooks? Click on the link below:
Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.
Matplotlib tries to make easy things easy and hard things possible. You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with just a few lines of code
For simple plotting the pyplot module provides a MATLAB-like interface, particularly when combined with IPython. For the power user, you have full control of line styles, font properties, axes properties, etc, via an object oriented interface or via a set of functions familiar to MATLAB users.
In debian or Ubuntu systems, you can install matplotlib using
1 |
sudo apt-get install python-matplotlib |
or use yum in fedora or Redhat:
1 |
sudo yum install python-matplotlib |
For more installation guidelines, check out https://matplotlib.org/users/installing.html
Let’s import matplotlib
1 |
>>> import matplotlib.pyplot as plt |
Let’s draw a simple graph
1 2 3 4 5 |
>>> plt.plot([1,2,3,4]) >>> plt.ylabel('some numbers') >>> plt.show() |
You obtain the following figure 1
How did python decide the x axis values?
If you provide a single list or array to the plot() command, matplotlib assumes it is a sequence of y values, and automatically generates the x values for you. Since python ranges start with 0, the default x vector has the same length as y but starts with 0. Hence the x data are [0,1,2,3].
Draw the graph of y=x2
Program:
1 2 3 4 5 6 7 |
>>> plt.plot([-4,-3,-2,-1,0,1,2,3,4],[16,9,4,1,0,1,4,9,16]) >>> plt.ylabel('Squares') >>> plt.xlabel('Numbers') >>> plt.show() |
Output:
Now lets say you wanted red dots instead of lines of say a graph y=5*x
1 2 3 4 5 6 7 |
>>> plt.plot([1,2,3,4], [1,4,9,16], 'ro') >>> plt.axis([0, 6, 0, 20]) [0, 6, 0, 20] >>> plt.show() |
You get the following graph
MatPlotLib is not limited to just using list. Usually it is used in combination to numpy, and hence it has varied effective uses that makes analysing large amount of data easy.
For more of matplotlib like drawing histograms or multiple graphs on a single plot etc, check out https://matplotlib.org/users/pyplot_tutorial.html
For more examples, check out https://matplotlib.org/examples/index.html
Checkout matplotlib cheatsheet at following link:
https://www.globalsqa.com/data-visualisation-in-python-matplotlib-cheat-sheet
Have fun with matplotlib!
Question:
Write a program to convert decimal to binary, octal and hexadecimal using inbuilt functions
Program:
1 2 3 4 5 6 7 |
# Python program to convert decimal number into binary, octal and hexadecimal number system # Take decimal number from user dec = int(input("Enter an integer: ")) print("The decimal value of",dec,"is:") print(bin(dec),"in binary.") print(oct(dec),"in octal.") print(hex(dec),"in hexadecimal.") |
Explanation:
A binary number is a number expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: typically 0 (zero) and 1 (one). The base-2 system is a positional notation with a radix of 2.
The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. Octal numerals can be made from binary numerals by grouping consecutive binary digits into groups of three (starting from the right). For example, the binary representation for decimal 74 is 1001010.
Hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.
Output:
1 2 3 4 5 |
Enter an integer: 56 The decimal value of 56 is: 0b111000 in binary. 0o70 in octal. 0x38 in hexadecimal. |