Nitin Sharma Python Report
Nitin Sharma Python Report
IT REPORT
ON
TAKEN AT
Rajasthan
2020-2021
DECLARATION
I hereby declare that the seminar report entitled “ PYTHON BOOTCAMP ” was carried
out and written by me under the guidance of MR. NITIN SHARMA (Assistant
Professor),
A project of such a vast coverage cannot be realized without help from numerous
sources and people in the organization .I am thankful to the department of CSE for
providing me a platform to carry out such a training successfully.
I am also very grateful to Dr. Rohit Kumar Singhal (HOD,CSE) for his kind support.
I would like to take this opportunity to show my gratitude towards all my supporting
facultywho helped me in successful completion of my Second Year Practical Training.
They have guided , motivated & appreciated and were source of inspiration for me to carry
out the necessary proceedings for the training to be completed successfully.
I am also grateful to Nitin Sharma sir from udemy for his guidance and support.
I would also like to express my heartfelt gratitude to all of my friends whose direct or
indirect suggestions help me to develop this project and to entire team members for their
valuable Suggestions.
Lastly, thanks to all faculty members of Computer Science Engineering Department
for their moral support and guidance.
This is to certify that NITIN SHARMA of B.Tech 3rd year Computer Science Engineering
has submitted major project report entitled PYTHON BOOTCAMP in partial fulfillment
for the award of degree of Bachelor of Technology from Bikaner Technical University,
Rajasthan in the session 2020-21. This is to further certify that it is a bonafide record of
the work carried out under my supervision.
Name of Guide : Nitin Sharma
IET Alwar
ABSTRACT
From numerical weather prediction to processing data from weather radars or visualizing
atmospheric conditions, computers have become an integral tool in the fields of meteorology and
atmospheric science. However, computers require specific directions in the form of software. The
ability to write this software, often customized for the particular needs of the user, goes hand-in
hand with research and operations. This process can be time consuming and overly burdensome in
many programming languages. Writing software to address the challenges in meteorology is simple
using the Python programming language due to the language design, available libraries and
community culture.
Python is a general purpose, high-level programming language which is widely used in
meteorology and elsewhere. The language facilitates a rapid development cycle with its interpreted
and interactive nature. A focus on code readability makes the language easy to learn, and the
expressive syntax leads to short, clear programs. Additionally, Python has excellent support for
interfacing with legacy code written in C, C++ and Fortran making it an excellent tool for
integrating existing software.
Python has an extensive and comprehensive collection of freely available packages covering a
variety of topics. Scientific Python libraries such as NumPy, SciPy, and pandas provide efficient
implementation of numerical operations and tasks common in science and engineering. These
libraries provide a strong base from which more advanced scientific software can be built without
needing to worry about low-level algorithms. Additionally, many domain specific packages exist
which address the scientific needs of the meteorological community.
The Python community provides a welcoming and vibrant culture. The tutorials and other
documentation provided for learning the language are rich and reinforce good programming
practices. Videos, books, websites, mailing lists, and user groups provide opportunities for
continued learning for beginners and experts alike. Python conferences around the world allow
Pythonistas to discuss ideas, challenges, and new developments in an open and collaborative
environment.
Python is a practical key to unlocking powerful computational resources that can open the door to a
variety of new career opportunities or that can enhance productivity in your current position. The
author will detail his own experience of how Python led him to meteorology.
Table of content
Cover Page ….Candidate’s Declaration …..
4.1 Number …… 4.2 String …… 4.3 List ……. 4.4 Tuple ……..
…… Chapter 8 Reference
CHAPTER 1 ABOUT PYTHON
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:
∙ Python is Interpreted − Python is processed at runtime by the interpreter. You do
∙ Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Characteristics of Python
∙ It provides very high-level dynamic data types and supports dynamic type checking.
∙ It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
As mentioned before, Python is one of the most widely used language over the web. I'm
going to list few of them here:
∙ Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
∙ Easy-to-read − Python code is more clearly defined and visible to the eyes. ∙
∙ A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
∙ Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
∙ Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
∙ Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
∙ GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
∙ Scalable − Python provides a better structure and support for large programs than
shell scripting.
Enviourment setup:-
To check if you have python installed on a Windows PC, search in the start bar for Python
or run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:
python --version
If you find that you do not have python installed on your computer, then you can download
it for free from the following website: https://www.python.org/
Python Quickstart
Python is an interpreted programming language, this means that as a developer you write
Python (.py) files in a text editor and then put those files into the python interpreter to be
executed.
The way to run a python file is like this on the command line:
Let's write our first Python file, called helloworld.py, which can be done in any text
editor. helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where
you saved your file, and run:
Hello, World!
To test a short amount of code in python sometimes it is quickest and easiest not to write
the code in a file. This is made possible because Python can be run as a command line
itself.
C:\Users\Your Name>python
Or, if the "python" command did not work, you can try "py":
C:\Users\Your Name>py
From there you can write any python, including our hello world example from earlier in
the tutorial:
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more
information. >>> print("Hello, World!")
C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more
information. >>> print("Hello, World!")
Hello, World!
Whenever you are done in the python command line, you can simply type the following to
quit the python command line interface: exit ()
CHAPTER 2
As we learned in the previous page, Python syntax can be executed by writing directly in
the Command Line:
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
Python Indentation
Example
Variables in Python:
x = 5
y = "Hello, World!"
Comments
Comments start with a #, and Python will render the rest of the line as a comment:
Example
Comments in Python:
#This is a comment.
print("Hello, World!")
Python comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Creating a Comment
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment
Comments does not have to be text to explain the code, it can also be used to prevent
Python from executing code:
Example
#print("Hello, World!")
print("Cheers, Mate!")
Multi Line Comments
Python does not really have a syntax for multi line comments.
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a
multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then
ignore it, and you have made a multiline comment.
Variables
Creating Variables
Example
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
You can get the data type of a variable with the type() function.
Example
x = 5
y = "John"
print(type(x))
print(type(y))
quotes: Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a = 4
A = "Sally"
#A will not overwrite
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_ (underscore))
Variable names are case-sensitive (age, Age and AGE are three different
variables) Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Remember that variable names are case-sensitive
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
Python Variables - Assign Multiple Values
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two
values: Example
print(10 + 5)
Python divides the operators in the following groups:
∙ Arithmetic operators
∙ Assignment operators
∙ Comparison operators
∙ Logical operators
∙ Identity operators
∙ Membership operators
∙ Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
+ Addition x + y
- Subtraction x - y
* Multiplication
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
Assignment Operators
Assignment operators are used to assign Python
values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
== Equal x == y
!= Not equal x != y
not Reverse the result, returns False if the result is true not(x < 5 and
x < 10)
not in Returns True if a sequence with the specified value is x not in y
not present in the object
<< Zero fill left shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> shift Shift right by pushing copies of the leftmost bit in
om the left, and let the rightmost bits fall off
CHAPTER 4
PYTHON DATA TYPES
Variables can store data of different types, and different types can do different
things. Python has the following data types built-in by default, in these categories:
You can get the data type of any object by using the type() function:
Example
x = 5
print(type(x))
x = 20 Int
x = 20.5 Float
x = 1j Complex
x = range(6) Range
x = True Bool
x = b"Hello" Bytes
x = bytearray(5) Bytearray
x = memoryview(bytes(5)) Memoryview
If you want to specify the data type, you can use the following constructor functions:
Example Data Type
x = int(20) Int
x = float(20.5) Float
x = complex(1j) complex
x = range(6) Range
x = bool(5) Bool
x = bytes(5) Bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z)
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of
10. Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers: Example
Import the random module, and display a random number between 1 and
9: import random
print(random.randrange(1, 10))
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three
quotes: Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the
code. Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string
with a length of 1.
Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for
loop. Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Check String
To check if a certain phrase or character is present in a string, we can use the keyword
in. Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free" in txt)
Use it in an if statement:
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
Use it in an if statement:
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if "expensive" not in txt:
print("Yes, 'expensive' is NOT present.")
Escape Character
To insert characters that are illegal in a string, use an escape character. An escape
character is a backslash \ followed by the character you want to insert. An example of an
illegal character is a double quote inside a string that is surrounded by double quotes:
Example
You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
txt = "We are the so-called "Vikings" from the north."
To fix this problem, use the escape character \":
Example
The escape character allows you to use double quotes when you normally would not be
allowed:
txt = "We are the so-called \"Vikings\" from the north."
Escape Characters
Other escape characters used in Python:
Code Result
\\ Backslash
\t Tab
\b Backspace
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of
where it was found
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position
of where it was found
rindex() Searches the string for a specified value and returns the last position
of where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Python Lists
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List Items
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that
order will not change.
If you add new items to a list, the new items will be placed at the end of the list. Note:
There are some list methods that will change the order, but in general: the order of the
items will not change.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it
has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
Lists allow duplicate values:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
List Items - Data Types
List items can be of any data type:
Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types:
Example
A list with strings, integers and boolean values:
list1 = ["abc", 34, True, 40, "male"]
type()
From Python's perspective, lists are defined as objects with the data type
'list': <class 'list'>
Example
What is the data type of a list?
mylist = ["apple", "banana", "cherry"]
print(type(mylist))
Python Collections (Arrays)
There are four collection data types in the Python programming language: List is a
collection which is ordered and changeable. Allows duplicate members. Tuple is a
collection which is ordered and unchangeable. Allows duplicate members. Set is a
collection which is unordered and unindexed. No duplicate members. Dictionary is a
collection which is unordered and changeable. No duplicate members. When choosing a
collection type, it is useful to understand the properties of that type. Choosing the right
type for a particular data set could mean retention of meaning, and, it could mean an
increase in efficiency or security.
Access Items
List items are indexed and you can access them by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Note: The first item has index 0.
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new list with the specified
items. Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"] print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not
included). Remember that the first item has index 0.
By leaving out the start value, the range will start at the first
item: Example
This example returns the items from the beginning to, but NOT included, "kiwi":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])
By leaving out the end value, the range will go on to the end of the
list: Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"] print(thislist[2:])
When we say that tuples are ordered, it means that the items have a defined order, and that
order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Allow Duplicates
Since tuple are indexed, tuples can have items with the same value:
Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
Tuple Items - Data Types
Tuple items can be of any data type:
Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
A tuple can contain different data types:
Example
A tuple with strings, integers and boolean values:
tuple1 = ("abc", 34, True, 40, "male")
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':
<class 'tuple'>
Example
What is the data type of a tuple?
mytuple = ("apple", "banana", "cherry")
print(type(mytuple))
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double
round-brackets print(thistuple)
Python Sets
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage. A set is a
collection which is both unordered and unindexed.
Sets are written with curly brackets.
Example
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Note: Sets are unordered, so you cannot be sure in which order the items will
appear. Set Items
Set items are unordered, unchangeable, and do not allow duplicate
values. Unordered
Unordered means that the items in a set do not have a defined order. Set items can appear
in a different order every time you use them, and cannot be referred to by index or key.
Unchangeable
Sets are unchangeable, meaning that we cannot change the items after the set has been
created.
Once a set is created, you cannot change its items, but you can add new
items. Duplicates Not Allowed
print(thisset)
type()
From Python's perspective, sets are defined as objects with the data type
'set': <class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))
Python Dictionaries
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is unordered, changeable and does not allow
duplicates. Dictionaries are written with curly brackets, and have keys and values:
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Dictionary Items
Dictionary items are unordered, changeable, and does not allow duplicates. Dictionary
items are presented in key:value pairs, and can be referred to by using the key name.
Example
Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Unordered
When we say that dictionaries are unordered, it means that the items does not have a defined
order, you cannot refer to an item by using an index.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the
dictionary has been created.
Dictionary Length
To determine how many items a dictionary has, use the len()
function: Example
Print the number of items in the dictionary:
print(len(thisdict))
type()
From Python's perspective, dictionaries are defined as objects with the data type
'dict': <class 'dict'>
Example
Print the data type of a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(type(thisdict))
CHAPTER 5 PYTHON DECISION MAKING
AND LOOPS
Decision making
Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages −
Python programming language assumes any non-zero and non-null values as TRUE, and
if it is either zero or null, then it is assumed as FALSE value.
1 if statements
You can use one if o r else if statement inside another if or else if statement(s).
Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
You can use one or more loop inside any another while, for or do..while
loop.
Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.
Creating a Function
Example
def my_function():
print("Hello from a function")
Calling a Function
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full
name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Parameters or Arguments?
The terms parameter and argument c an be used for the same thing: information that are
passed into a function.
definition. An argument is the value that is sent to the function when it is called.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that
if your function expects 2 arguments, you have to call the function with 2 arguments, not
more, and not less.
Example
Example
If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple o f arguments, and can access the items
accordingly:
Example
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
Keyword Arguments
value s yntax.
You can also send arguments with the key =
Example
If you do not know how many keyword arguments that will be passed into your function,
add two asterisk: ** before the parameter name in the function definition.
This way the function will receive a dictionary o f arguments, and can access the items
accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before the parameter
name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
Example
E.g. if you send a List as an argument, it will still be a List when it reaches the
function: Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass
Recursion
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a
result.
The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically-elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements (-1) every time we recurse. The
recursion ends when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to
find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
CHAPTER 7
Example
class MyClass:
x = 5
Create Object
Example
p1 = MyClass()
print(p1.x)
All classes have a function called __init__(), which is always executed when the class is
being initiated.
Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
Example
Create a class named Person, use the __init__() function to assign values for name and
age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and is used to
access variables that belong to the class.
The self parameter is a reference to the current instance of the class, and is used to access
variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:
Example
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Example
p1.age = 40
Example
del p1.age
Delete Objects
Example
del p1
class definitions cannot be empty, but if you for some reason have a class d
efinition with
no content, put in the pass statement to avoid getting an error.
Example
class Person:
pass
CHAPTER 8
LIBRARIES IN PYTHON
NUMPY
NumPy targets the CPython reference i mplementation of Python, which is a non
optimizing bytecode interpreter. Mathematical algorithms written for this version of Python
often run much slower than compiled equivalents. NumPy addresses the slowness
problem partly by providing multidimensional arrays and functions and operators that
operate efficiently on arrays, requiring rewriting some code, mostly inner loops, using
NumPy.
Using NumPy in Python gives functionality comparable to MATLAB since they are both
interpreted,[18] and they both allow the user to write fast programs as long as most
operations work on arrays or matrices instead of scalars.
Example
Array creation
PANDAS
In computer programming, pandas is a software library written for the Python
programming language for data manipulation and analysis. In particular, it offers data
structures and operations for manipulating numerical tables and time series. It is free
The name is derived from the
software released under the three-clause BSD license.[2]
term "panel data", an econometrics term for data sets that include observations over
multiple time periods for the same individuals
Viewing and Inspecting Data
Now that you’ve loaded your data, it’s time to take a look. How does the data
frame look? Running the name of the data frame would give you the entire
table, but you can also get the first n rows with df.head(n) o
r the last n rows
with df.tail(n). df.shape w
ould give you the number of rows and columns.
df.info() would give you the index, datatype and memory information. The
command s.value_counts(dropna=False) w
ould allow you to view unique
values and counts for a series (like a column or a few columns). A very useful
command is df.describe() w
hich inputs summary statistics for numerical
columns. It is also possible to get statistics on the entire data frame or a
series (a column etc):
MATPLOTLIB
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension NumPy. It provides an object-oriented A
PI for embedding plots
into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.
There is also a procedural "pylab" interface based on a state machine (like OpenGL),
designed to closely resemble that of MATLAB, though its use is
discouraged.[3] SciPy makes use of Matplotlib.
Examples
∙
Line plot
∙
Histogram
∙
Scatter plot
∙
Image plot
∙
Scatter plot
∙
Line plot
SEABORN
Seaborn is a library for making statistical graphics in Python. It builds on top
of matplotlib and integrates closely with pandas data structures.
Seaborn helps you explore and understand your data. Its plotting functions operate on
dataframes and arrays containing whole datasets and internally perform the necessary
semantic mapping and statistical aggregation to produce informative plots. Its dataset
oriented, declarative API lets you focus on what the different elements of your plots
mean, rather than on the details of how to draw them
# Create a visualization
sns.relplot(
data=tips,
x="total_bill", y="tip", col="time",
hue="smoker", style="smoker", size="size",
)
Conclusion
REFERENCE
https://www.tutorialspoint.com/python/python_basic_operators.ht
m https://www.w3schools.com/python/python_syntax.asp