Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4K views

Python 3 - A Comprehensive Guide

Uploaded by

Anjana Maganti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Python 3 - A Comprehensive Guide

Uploaded by

Anjana Maganti
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

Python 3 - A comprehensive guide


Level : Beginner

Python, the brainchild of Guido van Rossum, is interpreted and not compiled. What do these
two fancy words mean? Now that’s a typical interview question pals.
● Compiler​ : Converts the whole code into machine language and gives the error at the
end. C++ is a compiler based language.
● Interpreter​ : Executes the code line by line. It shows the error as and when it meets it,
this makes debugging super easy. Python is a language that is interpreted.

Why learn python?


Because it’s a part of my semester curriculum, duh?
Well not exactly. Learning python is fun and somewhat necessary because important sectors of
the IT industry are now solely based on python. For example :
● Machine Learning
● Artificial Intelligence
● Data mining
● Data Science
Besides, it’s the easiest language out there! There are hundreds of open source software and
tools along with a wonderful supportive community out there to help you out.

Basics
➔ Note​ : Python takes indentation very seriously. Instead of using
curly brackets to mark blocks, it uses indentation (or a tab
space) to mark the beginning of a new block.

Print statements
Let’s start by doing our favorite thing, greeting the world.

print​(​"Hello world"​)

To take input from a user, this is what you do!

# Python program showing


© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# a use of input()

val = input(​"Enter your value: "​)


print(val)

Variables
A variable can be thought of as an empty container that holds your information. Think of an
empty box. Now you want to keep the number 3 in it. How do you do this in python? Using
variables! We create a variable, assign it a number and we’re done.
Here we create a variable, assign it number 3 and then print the contents of the variable.
num​ = ​3
print​(​num​)

Data Structures
Now, let’s talk about the various important data structures available in python. What are data
structures? Well, they’re types of containers where you can store data. Just like boxes can be
big, small, straight, curvy, data structures can be varied.

1. Lists

Lists in Python are one of the most versatile collection object types available. The other two
types are dictionaries and tuples, but they are really more like variations of lists.
● Python lists do the work of most of the collection data structures found in other
languages and since they are built-in, you don’t have to worry about manually creating
them.
● Lists can be used for any type of object, from numbers and strings to more lists.
● They are accessed just like strings (e.g. slicing and concatenation) so they are simple to
use and they’re variable length, i.e. they grow and shrink automatically as they’re used.
● In reality, Python lists are C arrays inside the Python interpreter and act just like an array
of pointers.
 
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# Python program to illustrate


# A simple list

# Declaring a list
L = [1, ​"a"​ , "
​ string"​ , 1+2]
print​ L

# add 6 to the above list


L.append(6)
print​ L

# pop deletes the last element of the list


L.pop()
2. Dictionary

In python, dictionary is similar to hash or maps in other languages. It consists of 


key value pairs. The value can be accessed by unique key in the dictionary. 
● Keys are unique & immutable objects. 
● Syntax: 
dictionary = {"key name": value}

# Python program to illustrate


# dictionary

# Create a new dictionary


d = dict() ​# or d = {}

# Add a key - value pairs to dictionary


d[​'xyz'​] = ​123
d[​'abc'​] = ​345

# print the whole dictionary


print​ d

# print only the keys


print​ d.keys()

# print only values


print​ d.values()
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# iterate over dictionary


for​ i ​in​ d :
​print​ ​"%s %d"​ %(i, d[i])

# another method of iteration


for​ index, value ​in​ enumerate(d):
​print​ index, value , d[value]

# check if key exist


print​ ​'xyz'​ ​in​ d

# delete the key-value pair


del​ d[​'xyz'​]

# check again
print​ ​"xyz"​ ​in​ d

3. Tuple

Python tuples work exactly like Python lists except they are immutable, i.e. they can’t be
changed in place. They are normally written inside parentheses to distinguish them from lists
(which use square brackets), but as you’ll see, parentheses aren’t always necessary. Since
tuples are immutable, their length is fixed. To grow or shrink a tuple, a new tuple must be
created.
Here’s a list of commonly used tuples:
● () An empty tuple
● t1 = (0, ) A one-item tuple (not an expression)
● t2 = (0, 1, 2, 3) A four-item tuple
● t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis)
● t3 = (‘abc’, (‘def’, ‘ghi’)) Nested tuples
● t1[n], t3[n][j] Index
● t1[i:j], Slice
● len(tl) Length

# Python program to illustrate


# tuple
tup = (1, ​"a"​, ​"string"​, 1+2)
print​ tup
print​ tup[1]
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

Decision statements
If statement

if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.

Syntax:
if condition:
# Statements to execute if
# condition is true

Here, condition after evaluation will be either true or false. if statement accepts boolean values –
if the value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.
# Python program to illustrate If statement

i = 10
if​ (i > 15):
​print​ (​"10 is less than 15"​)
print​ (​"I am Not in if"​)

If - else statements

The if statement alone tells us that if a condition is true it will execute a


block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false. Here comes the
else statement. We can use the else statement with if statement to
execute a block of code when the condition is false.

Syntax​:
if (condition):
# Executes this block if
# condition is true
else:
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# Executes this block if


# condition is false

# python program to illustrate If else statement


#!/usr/bin/python

i = 20;
if​ (i < 15):
​print​ (​"i is smaller than 15"​)
​print​ (​"i'm in if Block"​)
else​:
​print​ (​"i is greater than 15"​)
​print​ (​"i'm in else Block"​)
print​ (​"i'm not in if and not in else Block"​)

Loops
When you want to repeat your statements until a following condition is reached, you use loops.
For example, if you wish to print 0 to 100, you will need 8 minutes to write a print statement with
all the numbers, however, you will be able to write a loop to do the same in a minute!

While loop
# prints Hello Geek ​3​ ​Times
count​ = ​0
while​ (​count​ < ​3​):
​count​ = ​count​+​1
​print​(​"Hello Geek"​)

For loop
# Iterating over a list
print​(​"List Iteration"​)
l = [​"geeks"​, ​"for"​, ​"geeks"​]
for​ i ​in​ l:
​print​(i)
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# Iterating over a tuple (immutable)


print​(​"\nTuple Iteration"​)
t = (​"geeks"​, ​"for"​, ​"geeks"​)
for​ i ​in​ t:
​print​(i)

# Iterating over a String


print​(​"\nString Iteration"​)
s = ​"Geeks"
for​ i ​in​ s :
​print​(i)

# Iterating over dictionary


print​(​"\nDictionary Iteration"​)
d = dict()
d[​'xyz'​] = 123
d[​'abc'​] = 345
for​ i ​in​ d :
​print​(​"%s %d"​ %(i, d[i]))

Functions
A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and again for different inputs, we can
call the function.
Python provides built-in functions like print(), etc. but we can also create your own functions.
These functions are called user-defined functions.

# A simple Python function to check


# whether x is even or odd
def​ ​evenOdd​( x ):
​if​ (x % ​2​ == ​0​):
​print​ ​"even"
​else​:
​print​ ​"odd"

# Driver code
evenOdd(​2​)
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

evenOdd(​3​)

Recursive Functions
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called recursive function. Using recursive algorithm, certain problems
can be solved quite easily.
In the recursive program, the solution to the base case is provided and the solution of the bigger
problem is expressed in terms of smaller problems.
 
int​ ​fact​(​int​ ​n​)
{
​if​ (​n​ < = ​1​) // ​base​ case
return ​1​;
else
return ​n​*​fact​(n​ ​-​1​);
}
 
In the above example, base case for n < = 1 is defined and larger value of number can be
solved by converting to smaller one till base case is reached.
The idea is to represent a problem in terms of one or more smaller problems, and add one or
more base conditions that stop the recursion. For example, we compute factorial n if we know
factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.

# A Python 3 program to
# demonstrate working of
# recursion

def printFun(​test​):

​if​ (​test​ < 1):


​return
​else​:

​print​( ​test​,end = ​" "​)


printFun(​test​-1) ​# statement 2
​print​( ​test​,end = ​" "​)
​return
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

test​ = 3
printFun(​test​)

Modules
A module is a file containing Python definitions and statements. A module can define functions,
classes and variables. A module can also include runnable code. Grouping related code into a
module makes the code easier to understand and use.

Import
# importing module calc.py
import calc

print​ ​add​(10, 2)
 

File Handling
Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files.
 
# a file named "geek", will be opened with the reading mode.
file​ = ​open​(​'geek.txt'​, ​'r'​)
# This will print every line one by one in the file
for​ ​each​ ​in​ ​file​:
print (​each​)
 
# Python code to create a file
file​ = ​open​(​'geek.txt'​,​'w'​)
file​.​write​(​"This is the write command"​)
file​.​write​(​"It allows us to write in a particular file"​)
file​.​close​()
 
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# Python code ​to​ illustrate ​append​() ​mode


file​ = ​open​(​'geek.txt'​,​'a'​)
file​.​write​(​"This will add this line"​)
file​.​close​()
 
 

Numpy
Numpy is a general-purpose array-processing package. It provides a high-performance
multidimensional array object, and tools for working with these arrays. It is the fundamental
package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-dimensional
container of generic data.

# Python program for


# Creation of Arrays
import numpy as np

# Creating a rank ​1​ Array


arr = np.array([​1​, ​2​, ​3​])
print(​"Array with Rank 1: \n"​,arr)

# Creating a rank ​2​ Array


arr = np.array([[​1​, ​2​, ​3​],
[​4​, ​5​, ​6​]])
print(​"Array with Rank 2: \n"​, arr)

# Creating an array from tuple


arr = np.array((​1​, ​3​, ​2​))
print(​"\nArray created using "
​"passed tuple:\n"​, arr)

Basic operations

# Python program to demonstrate


# basic operations on single array
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

import numpy as np

# Defining Array 1
a = np.array([[​1​, ​2​],
[​3​, ​4​]])

# Defining Array 2
b = np.array([[​4​, ​3​],
[​2​, ​1​]])

# Adding 1 to every element


print (​"Adding 1 to every element:"​, a + ​1​)

# Subtracting 2 from each element


print (​"\nSubtracting 2 from each element:"​, b - ​2​)

# sum of array elements


# Performing Unary operations
print (​"\nSum of all array "
​"elements: "​, a.sum())

# Adding two arrays


# Performing Binary operations
print (​"\nArray sum:\n"​, a + b)

Pandas
Pandas DataFrame​ is two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). A Data frame is a two-dimensional data
structure, i.e., data is aligned in a tabular fashion in rows and columns. Pandas DataFrame
consists of three principal components, the ​data​, ​rows​, and ​columns​.

Creating a dataframe
# import pandas ​as​ pd
import pandas ​as​ pd
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# list ​of​ strings


lst = [​'Geeks'​, ​'For'​, ​'Geeks'​, ​'is'​,
​'portal'​, ​'for'​, ​'Geeks'​]

# Calling DataFrame ​constructor​ ​on​ ​list


df​ = ​pd​.​DataFrame​(lst)
print​(df)

# Python code demonstrate creating


# DataFrame from dict narray / lists
# By default addresses.

import pandas as pd

# intialise data of lists.


data = {​'Name'​:[​'Tom'​, ​'nick'​, ​'krish'​, ​'jack'​],
​'Age'​:[​20​, ​21​, ​19​, ​18​]}

# Create DataFrame
df = pd.DataFrame(data)

# Print the output.


print(df)

# Import pandas package


import​ pandas ​as​ pd

# Define a dictionary containing employee data


data​ = {'​Name​':['​Jai​', '​Princi​', '​Gaurav​', '​Anuj​'],
'​Age​':[27, 24, 22, 32],
'​Address​':['​Delhi​', '​Kanpur​', '​Allahabad​', '​Kannauj​'],
'​Qualification​':['​Msc​', '​MA​', '​MCA​', '​Phd​']}
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

# Convert the dictionary into DataFrame


df​ = pd.​DataFrame​(​data​)

# select two columns


print​(df[['​Name'​, '​Qualification'​]])

Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a
multi-platform data visualization library built on NumPy arrays and designed to work with the
broader SciPy stack. It was introduced by John Hunter in the year 2002.

Line plot:
#​ importing matplotlib module
from matplotlib import pyplot as plt

#​ x-axis values
x = [5, 2, 9, 4, 7]

#​ Y-axis values
y = [10, 5, 8, 4, 2]

#​ Function to plot
plt.plot(x,y)

#​ ​function​ to show the plot


plt.show()

Bar Plot
# importing matplotlib module
from matplotlib import pyplot as plt

# x-axis values
x = [5, 2, 9, 4, 7]

# Y-axis values
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

y = [10, 5, 8, 4, 2]

# Function to plot the bar


plt.bar(x,y)

# function to show the plot


plt.show()

Histogram
# importing matplotlib module
from​ matplotlib ​import​ pyplot a
​ s​ plt

# Y-axis values
​ ​, ​8​, ​4​, ​2​]
y = [​10​, 5

# Function to plot histogram


plt.hist(y)

# Function to show the plot


plt.show()

Scatter Plot
#​ importing matplotlib module
from matplotlib import pyplot as plt

#​ x-axis values
x = [5, 2, 9, 4, 7]

#​ Y-axis values
y = [10, 5, 8, 4, 2]

#​ Function to plot scatter


plt.scatter(x, y)

#​ ​function​ to show the plot


plt.show()

And that’s where our basics end!


© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

Guide to become a Python 3 expert


Follow the steps below to master Python :

1. Log on to ​https://www.codecademy.com/learn/learn-python-3​ and finish this course in a


week. Move on to the second step.
2. Log on to ​https://www.codechef.com/problems/easy​ and solve at least one problem a
day.
3. Once done with the Easy problems in the link above, move onto Medium and Hard
problems.

If you code daily, almost in a ritualistic manner, you will definitely become an expert. Your
competitive coding skills will also improve, which means you’ve got 25 L per annum starting
salary moving towards you (or that’s what everyone says!)

Thank you!

Happy Coding! 
© Python in Pyjamas 2019 by IEEE WIE | ACM Women’s

You might also like