SlideShare ist ein Scribd-Unternehmen logo
1 von 91
Downloaden Sie, um offline zu lesen
Dr.D.Sugumar
Associate Prof/ECE
Karunya University
PYTHON PROGRAMMING Intro
BasicPythonProgramming
v04
Python ( What and Why ?)
• Python is the most popular programming language & choice for
Data Scientist / Data Engineer across the world
• Very rich libraries & functions
• Community support
• Easy to deploy in production
• Support for all the new state of the art technologies ( like deep
learning)
3
Not this python,unfortunately
4
But thisPython!
5
ButthisPython!
Programming Language
6
ButthisPython!
Programming Language
Created in 1991 by Guido van Rossum
7
ButthisPython!
Cross Platform
Programming Language
Created in 1991 by Guido van Rossum
8
ButthisPython!
Programming Language
Freely Usable Even for Commercial Use
Created in 1991 by Guido van Rossum
Cross Platform
9
10
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python" +" is "+"cool!")
11
print("Python" +" is "+"cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python"+" is"+"cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
12
print("Python"+" is"+"cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
print("Hello world!")
13
14
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python" +" is "+"cool!")
● Python works on Windows, Linux, Mac,
Raspberry Pi, NVidia boards (linux), PYNQ
FPGA etc.
● Few lines of Programming
● Prototyping of Python programming is fast
● Syntax is same as like normal English
language
● It relies on Indentation, whitespace, scope of
loops, functions and classes
● Latest version of python is version3 (3.9).
Why Python?.
Python IDE.
IDLE : Python Software foundation license
PYCHARM: Apache license
SPYDER: MIT license
● Python is a popular programming language. It
was created by Guido van Rossum, and
released in 1991.
● Python is a programming language that lets
you work more quickly and integrate your
systems more effectively.
1. Web development
2. Handle Big data
3. Handles complex Mathematics
4. Software development
5. Connects to database systems
Python & Uses.
print("Python" +" is "+"cool!")
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com/ Pluralsight Platform
18
Big names using Python
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python"+" is"+"cool!")
https://opencv.org/
Image Processing using Python
19
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python"+" is"+"cool!")
https://www.pygame.org
Game Development using Python
20
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
16
print("Python"+" is"+"cool!")
https://matplotlib.org/
Data Science using Python
"Python is easy to use, powerful, and versatile, making it a great choice
for beginners and experts alike." – codeschool.com
print("Python"+" is"+"cool!")
https://github.com/amueller/word_cloud
Natural Language Processing (NLP) and Text Mining using Python
22
print("Python" +" is "+"cool!")
Top programming languages 2019 by IEEE Spectrum
2
3
Let's now explorethePythonuniverse!
24
Google Colab
• Colaboratory, or “Colab” for short, is a product from
Google Research.
• Colab allows anybody to write and execute arbitrary
python code through the browser, and is especially well
suited to machine learning, data analysis and education.
• More technically, Colab is a hosted Jupyter notebook
service that requires no setup to use, while providing free
access to computing resources including GPUs (graphics
processing unit ).
Google Colab
How to open:
Google Colab
How to open:
Google Colab
How to open:
Google Colab
How to open:
'py' is a regular python file. It's plain text and contains just your code. ...
'ipynb' is a python notebook and it contains the notebook code, the execution results and
other internal settings in a specific format.
How to install Python the Anaconda way
1. Download Anaconda (which includes Python):
https://www.anaconda.com/download/
2. Run the installer and follow the installation instructions
3. Run the Spyder editor and create your first Python program "helloworld.py"
PythonSetup
30
How to install Python the Anaconda way
1. Download Anaconda (which includes Python and
relevant libraries): https://www.anaconda.com/distribution/
2. Run the installer and follow the instructions
3. Run the Spyder editor or Jupyter Notebook and create your first Python program "helloworld.py"
PythonSetup
31
Installation Steps
Install using the instruction given in the below links -
1. Install Jupyter - http://jupyter.org/install
Preferred installation method is through Anaconda distribution.
Install Python 3.8 version.
2. Anaconda 5.2 For Linux Installer - https://www.anaconda.com/download/#linux
3. Anaconda 5.2 For macOS Installer - https://www.anaconda.com/download/#macos
4. Anaconda 5.2 For Windows Installer - https://www.anaconda.com/download/#windows
(You need to download the version compatible with your OS)
32
Python Install
33
Many PCs and Macs will have python already installed.
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):
C:UsersYour Name>python --version
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
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:
C:UsersYour Name>python helloworld.py
Execute Python Syntax
34
As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:
print("Hello, Karunyans!")
Hello, Karunyans!
Or by creating a python file on the server, using the .py file extension, and running it in the Command Line:
C:UsersYour Name>python myfile.py
Practical session
Installing Python
IDLE
PYTHON.ORG | MICROSOFT VISUAL STUDIO
Setting Python in
Environment Varaibles to
access from Command
window
Installing Python
Libraries
Basic Python
Programming
print(‘Hello world’)
Indentation in python!!
40
Indentation refers to the spaces at the beginning of a code line.
(Where in other programming languages the indentation in code is for readability only, the indentation in Python is very
important)
Python uses indentation to indicate a block of code.
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will give you an error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Syntax Error:
Add two number.
a = 5.4
b = 4.6
sum = float(a) + float(b)
print(sum)
User Input.
a = input(“Enter number1: “)
b = input(“Enter number2: “)
sum = int(a) + int(b)
print(“The sum of {0} and {1} is
{2}”.format(a, b, sum))
Slicing
42
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[:5])
b = "Hello, World!"
print(b[2:])
b = "Hello, World!"
print(b[-5:-2])
43
• String is a sequence of characters, like "Python is cool"
• Each character has an index
•Accessing a character: string[index]
x = "Python i s cool"
print(x[10])
•Accessing a substring via slicing: s t r i n g [ s t a r t : f i n i s h ]
p r i n t ( x [ 2 : 6 ] )
String
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
44
>>> x = "Python is cool"
>>> "cool" in x
>>> len(x)
>>> x + "?"
>>> x.upper()
# membership
# length of string x
# concatenation
# to upper case
>>> x.replace("c", "k") # replace characters in a string
StringOperations
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
>>> x = "Python is cool"
StringOperations:Split
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
P y t h o n
0 1 2 3 4 5
i s
0 1
c o o l
0 1 2 3
x . s p l i t ( " " )
>>> x.split(" ") 45
>>> x = "Python is cool"
>>> y = x.split(" ")
>>> ",".join(y) 40
StringOperations:Join
P y t h o n , i s , c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
P y t h o n
0 1 2 3 4 5
i s
0 1
c o o l
0 1 2 3
" , " . j o i n ( y )
Strings in RealLife
47
Conditionals and Loopsin RealLife
48
Conditionals andLoops
49
• Cores of programming!
• Rely on boolean expressions which return either True or False
• 1 < 2 : True
• 1.5 >= 2.5 : False
• answer == "Computer Science" :
can be True or False depending on the value of variable answer
• Boolean expressions can be combined with: and, or, not
• 1 < 2 and 3 < 4 : True
• 1.5 >= 2.5 or 2 == 2 : True
• not 1.5 >= 2.5 : True
ConditionalsandLoops
50
Conditionals: SimpleForm
i f condition:
i f - code
else:
else- code
51
Conditionals:GenericForm
if bolean-expression-1:
code-block-1
elif boolean-expression-2:
code-block-2 (as many elif's as you want)
else:
code-block-last
If & Elif. a = 33
b = 33
if a > b:
print(“a is greater than b")
elif a == b:
print("a and b are same")
else:
print("b is greater than a")
AND | OR. a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
#if a > b or c > a:
# print(“only one is True")
53
Conditionals:(Drivinglicenseage)
age = 20
if age < 16:
print("Not Eligible for Driving license!")
else:
print("OK, You are eligible to get your Driving license!")
54
Conditionals:usingInput()
age = int(input("Enter your age: "))
if age < 16:
print("Not Eligible for Driving license!")
else:
print("OK, You are eligible to get your Driving license!")
55
Conditionals:Grading
grade = int(raw_input("Numeric grade: "))
if grade >= 80:
print("A")
elif grade >= 65:
print("B")
elif grade >= 55:
print("C")
else:
print("E")
56
Loops
• Useful for repeating code!
• Two variants:
while boolean-expression:
code-block
for element i n collection:
code-block
While Loops
57
while boolean-expression:
code-block
while input("Which is the best subject? ") != "ECE":
print("Try again!")
print("Of course it is!")
58
WhileLoops
x = 5
while x > 0:
print (x )
x -= 1
print("While loop i s over now!")
while boolean-expression:
code-block
While Loops
59
while boolean-expression:
code-block
while input("Which i s the best subject? " ) != "Computer Science":
print("Try again!")
print("Of course i t i s ! " )
So far, we have seen (briefly) two kinds of collections:
string and list
For loops can be used to visit each collection's element:
60
ForLoops
for element i n collection:
code-block
for chr in "string":
print(chr)
for elem in [ 1 ,3,5]:
print(elem)
While.
i = 1
while i < 20:
print(i)
i += 1
FOR.
for x in range(10):
print(x)
for x in range(1, 10):
print(x)
for x in range(1, 10, 2):
print(x)
Expression and Arithmetic
62
Assume variable a holds 10 and variable b holds 20, then −
Expression and Arithmetic
63
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print ("Line 2 - Value of c is ", c)
c = a * b
print ("Line 3 - Value of c is ", c)
c = a / b
print ("Line 4 - Value of c is ", c)
c = a % b
print ("Line 5 - Value of c is ", c)
a = 2
b = 3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b = 5
c = a//b
print ("Line 7 - Value of c is ", c)
ref: https://realpython.com/python-operators-expressions/
Extra notes
String manipulation in python
64
• Working with data heavily involves reading and writing!
• Data come in two types:
• Text: Human readable, encoded in ASCII/UTF-8, example: .txt, .csv
• Binary: Machine readable, application-specific encoding,
example: .mp3, .mp4, .jpg
Input/Output
65
66
python
is
cool
Input
cool.txt
x = open("cool.txt", "r") # read mode
y = x.read() # read the whole
print(y)
x.close()
python
is
cool
44
Input
cool.txt
x = open("cool. t x t " , " r " )
# read l i n e by l i n e
f o r l i n e i n x :
l i n e = l i n e . r e p l a c e ( "  n " , " " )
p r i n t ( l i n e )
x . close( )
68
python
is
cool
Input
cool.txt
x = open( "C:  User s  Desktop  coo l . tx t " , " r " ) # absolute location
f o r l i n e i n x :
l i ne = l ine. r eplace("  n" , " " )
p r i n t ( l i n e )
x.close()
Output
# write mode
x = open( "cool.t x t " , "w")
x.write("and Interesting n")
x . close()
# append mode
69
x = open( "cool.t x t " , "a")
x.write(" and Interesting n ")
x . close()
Write mode overwrites files,
while append mode does not overwrite files but instead appends at the end of the files' content
Input in RealLife
70
Output in RealLife
71
72
• Functions encapsulate code blocks
• Why functions? Modularization and reuse!
• You actually have seen examples of functions:
• print()
• input()
• Generic form:
Functions
def function-name(parameters):
code-block
return value
Functions in RealLife
73
Functions:CelciustoFahrenheit
def celsius_to_fahrenheit(celsius):
fahrenhe i t = celsiu s * 1.8 + 32.0
return fahrenheit
def function-name(parameters):
code-block
return value
74
75
Functions:DefaultandNamedParameters
def hello(name_man="Bro",name_woman="Sis"):
print("Hello, " + name_man +"&"+name_woman+ "!")
>>> hello() Hello,
Bro& Sis!
>>>hello(name_woman="Lady")
Hello, Bro & Lady!
>>> hello(name_woman=“Girls",name_man="Boys")
Hello, Boys & Girls!
Built-in Math Functions
76
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
x = abs(-7.25)
print(x)
x = pow(4, 3)
print(x)
import math
import math
x = math.sqrt(64)
print(x)
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
x = math.pi
print(x)
77
• Code made by other people shall be reused!
• Two ways of importing modules (= Python files):
• Generic form: importmodule_name
import math
print(math.sqrt(4))
• Generic form: from module_name import function_name
from math import sqrt
p r i n t ( s q r t ( 4 ) )
Imports
Math Methods
78
Method Description
math.acos() Returns the arc cosine of a number
math.acosh() Returns the inverse hyperbolic cosine of a number
math.asin() Returns the arc sine of a number
math.asinh() Returns the inverse hyperbolic sine of a number
math.atan() Returns the arc tangent of a number in radians
math.atan2() Returns the arc tangent of y/x in radians
math.atanh() Returns the inverse hyperbolic tangent of a number
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items without
repetition and order
math.copysign() Returns a float consisting of the value of the first parameter and the sign of
the second parameter
math.cos() Returns the cosine of a number
math.cosh() Returns the hyperbolic cosine of a number
math.degrees() Converts an angle from radians to degrees
math.dist() Returns the Euclidean distance between two points (p and q), where p and q
are the coordinates of that point
math.erf() Returns the error function of a number
math.erfc() Returns the complementary error function of a number
math.exp() Returns E raised to the power of x
math.expm1() Returns E
x
- 1
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.frexp() Returns the mantissa and the exponent, of a specified number
math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
math.gamma() Returns the gamma function at x
math.gcd() Returns the greatest common divisor of two integers
math.hypot() Returns the Euclidean norm
math.isclose() Checks whether two values are close to each other, or not
math.isfinite() Checks whether a number is finite or not
math.isinf() Checks whether a number is infinite or not
math.isnan() Checks whether a value is NaN (not a number) or not
math.isqrt() Rounds a square root number downwards to the nearest integer
math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
math.lgamma() Returns the log gamma value of x
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x
math.log1p() Returns the natural logarithm of 1+x
math.log2() Returns the base-2 logarithm of x
math.perm() Returns the number of ways to choose k items from n items with order and without
repetition
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
https://www.w3schools.com/python/module_math.asp
Math Methods
79
math.radians() Converts a degree value into radians
math.remainder() Returns the closest value that can make numerator
completely divisible by the denominator
math.sin() Returns the sine of a number
math.sinh() Returns the hyperbolic sine of a number
math.sqrt() Returns the square root of a number
math.tan() Returns the tangent of a number
math.tanh() Returns the hyperbolic tangent of a number
math.trunc() Returns the truncated integer parts of a number
Math Constants
Constant Description
math.e Returns Euler's number (2.7182...)
math.inf Returns a floating-point positive infinity
math.nan Returns a floating-point NaN (Not a Number) value
math.pi Returns PI (3.1415...)
math.tau Returns tau (6.2831...)
cmath Module
80
Method Description
cmath.acos(x) Returns the arc cosine value of x
cmath.acosh(x) Returns the hyperbolic arc cosine of x
cmath.asin(x) Returns the arc sine of x
cmath.asinh(x) Returns the hyperbolic arc sine of x
cmath.atan(x) Returns the arc tangent value of x
cmath.atanh(x) Returns the hyperbolic arctangent value of x
cmath.cos(x) Returns the cosine of x
cmath.cosh(x) Returns the hyperbolic cosine of x
cmath.exp(x) Returns the value of E
x
, where E is Euler's number (approximately
2.718281...), and x is the number passed to it
cmath.isclose() Checks whether two values are close, or not
cmath.isfinite(x) Checks whether x is a finite number
cmath.isinf(x) Check whether x is a positive or negative infinty
cmath.isnan(x) Checks whether x is NaN (not a number)
cmath.log(x[, base]) Returns the logarithm of x to the base
cmath.log10(x) Returns the base-10 logarithm of x
cmath Module
81
cmath.phase() Return the phase of a complex number
cmath.polar() Convert a complex number to polar coordinates
cmath.rect() Convert polar coordinates to rectangular form
cmath.sin(x) Returns the sine of x
cmath.sinh(x) Returns the hyperbolic sine of x
cmath.sqrt(x) Returns the square root of x
cmath.tan(x) Returns the tangent of x
cmath.tanh(x) Returns the hyperbolic tangent of x
cMath Constants
Constant Description
cmath.e Returns Euler's number (2.7182...)
cmath.inf Returns a floating-point positive infinity value
cmath.infj Returns a complex infinity value
cmath.nan Returns floating-point NaN (Not a Number) value
cmath.nanj Returns coplext NaN (Not a Number) value
cmath.pi Returns PI (3.1415...)
cmath.tau Returns tau (6.2831...)
Creating a Function -recap
82
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
my_function()
Creating a Function -recap
83
Arguments
• Information can be passed into functions as 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:
def my_function(fname):
print(fname + “ Keep doing")
my_function(“John")
my_function(“SAM")
my_function(“Raj")
Creating a Function -recap
84
Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective:
A parameter is the variable listed inside the parentheses in the 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.
If you try to call the function with 1 or 3 arguments, you will get an error:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Samuel", "Abhishek")
Creating a Function -recap
85
Arbitrary Arguments, *args
• 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 of arguments, and can access the items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function(“John", “SAM", “Raj")
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = “John", child2 = “SAM", child3 = “Raj")
Creating a Function -recap
86
Arbitrary Keyword Arguments, **kwargs
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 of arguments, and can access the items accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = “John", lname = “Sam")
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Creating a Function -recap
87
Passing a List as an Argument
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as
the same data type inside the function.
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
Return Values
To let a function return a value, use the return statement:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Creating a Function -recap
88
The pass Statement
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.
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.
Creating a Function -recap
89
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("nnRecursion Example Results")
tri_recursion(6)
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.
How to include pandas & numpy?
90
import numpy as np
import pandas as pd
Fuction.
def funName():
print("Hello from a function")
funName()
File Handling.
a = open(‘pantech.txt’, ‘r’)
print(a.read())
a.close()

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Python ppt
Python pptPython ppt
Python ppt
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 
Introduction to the Python
Introduction to the PythonIntroduction to the Python
Introduction to the Python
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Python ppt.pptx
Python ppt.pptxPython ppt.pptx
Python ppt.pptx
 
Python final ppt
Python final pptPython final ppt
Python final ppt
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Presentation on python
Presentation on pythonPresentation on python
Presentation on python
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python basic
Python basicPython basic
Python basic
 
Python ppt
Python pptPython ppt
Python ppt
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 

Ähnlich wie 05 python.pdf

python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdfgmadhu8
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfThe Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfssuser8b3cdd
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Seminar report on python 3 course
Seminar report on python 3 courseSeminar report on python 3 course
Seminar report on python 3 courseHimanshuPanwar38
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3Youhei Sakurai
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unitmichaelaaron25322
 
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfTraining report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfYadavHarshKr
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PuneEthan's Tech
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxlemonchoos
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
Py4 inf 01-intro
Py4 inf 01-introPy4 inf 01-intro
Py4 inf 01-introIshaq Ali
 

Ähnlich wie 05 python.pdf (20)

python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
Python
PythonPython
Python
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
 
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdfThe Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
The Python Book_ The ultimate guide to coding with Python ( PDFDrive ).pdf
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Seminar report on python 3 course
Seminar report on python 3 courseSeminar report on python 3 course
Seminar report on python 3 course
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
 
Python programming language introduction unit
Python programming language introduction unitPython programming language introduction unit
Python programming language introduction unit
 
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdfTraining report 1923-b.e-eee-batchno--intern-54 (1).pdf
Training report 1923-b.e-eee-batchno--intern-54 (1).pdf
 
Python Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech PunePython Training in Pune - Ethans Tech Pune
Python Training in Pune - Ethans Tech Pune
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
py4inf-01-intro.ppt
py4inf-01-intro.pptpy4inf-01-intro.ppt
py4inf-01-intro.ppt
 
Py4 inf 01-intro
Py4 inf 01-introPy4 inf 01-intro
Py4 inf 01-intro
 
Python Course
Python CoursePython Course
Python Course
 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
 

Mehr von SugumarSarDurai

Mehr von SugumarSarDurai (19)

Parking NYC.pdf
Parking NYC.pdfParking NYC.pdf
Parking NYC.pdf
 
Apache Spark
Apache SparkApache Spark
Apache Spark
 
Power BI.pdf
Power BI.pdfPower BI.pdf
Power BI.pdf
 
Unit 6.pdf
Unit 6.pdfUnit 6.pdf
Unit 6.pdf
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
07 Data-Exploration.pdf
07 Data-Exploration.pdf07 Data-Exploration.pdf
07 Data-Exploration.pdf
 
06 Excel.pdf
06 Excel.pdf06 Excel.pdf
06 Excel.pdf
 
00-01 DSnDA.pdf
00-01 DSnDA.pdf00-01 DSnDA.pdf
00-01 DSnDA.pdf
 
03-Data-Analysis-Final.pdf
03-Data-Analysis-Final.pdf03-Data-Analysis-Final.pdf
03-Data-Analysis-Final.pdf
 
UNit4.pdf
UNit4.pdfUNit4.pdf
UNit4.pdf
 
UNit4d.pdf
UNit4d.pdfUNit4d.pdf
UNit4d.pdf
 
Unit 4 Time Study.pdf
Unit 4 Time Study.pdfUnit 4 Time Study.pdf
Unit 4 Time Study.pdf
 
Unit 3 Micro and Memo motion study.pdf
Unit 3 Micro and Memo motion study.pdfUnit 3 Micro and Memo motion study.pdf
Unit 3 Micro and Memo motion study.pdf
 
02 Work study -Part_1.pdf
02 Work study -Part_1.pdf02 Work study -Part_1.pdf
02 Work study -Part_1.pdf
 
02 Method Study part_2.pdf
02 Method Study part_2.pdf02 Method Study part_2.pdf
02 Method Study part_2.pdf
 
01 Production_part_2.pdf
01 Production_part_2.pdf01 Production_part_2.pdf
01 Production_part_2.pdf
 
01 Production_part_1.pdf
01 Production_part_1.pdf01 Production_part_1.pdf
01 Production_part_1.pdf
 
01 Industrial Management_Part_1a .pdf
01 Industrial Management_Part_1a .pdf01 Industrial Management_Part_1a .pdf
01 Industrial Management_Part_1a .pdf
 
01 Industrial Management_Part_1 .pdf
01 Industrial Management_Part_1 .pdf01 Industrial Management_Part_1 .pdf
01 Industrial Management_Part_1 .pdf
 

Kürzlich hochgeladen

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Kürzlich hochgeladen (20)

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

05 python.pdf

  • 3. Python ( What and Why ?) • Python is the most popular programming language & choice for Data Scientist / Data Engineer across the world • Very rich libraries & functions • Community support • Easy to deploy in production • Support for all the new state of the art technologies ( like deep learning) 3
  • 9. ButthisPython! Programming Language Freely Usable Even for Commercial Use Created in 1991 by Guido van Rossum Cross Platform 9
  • 10. 10 "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com print("Python" +" is "+"cool!")
  • 11. 11 print("Python" +" is "+"cool!") "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com
  • 12. print("Python"+" is"+"cool!") "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } } 12
  • 13. print("Python"+" is"+"cool!") "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } } print("Hello world!") 13
  • 14. 14 "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com print("Python" +" is "+"cool!")
  • 15. ● Python works on Windows, Linux, Mac, Raspberry Pi, NVidia boards (linux), PYNQ FPGA etc. ● Few lines of Programming ● Prototyping of Python programming is fast ● Syntax is same as like normal English language ● It relies on Indentation, whitespace, scope of loops, functions and classes ● Latest version of python is version3 (3.9). Why Python?.
  • 16. Python IDE. IDLE : Python Software foundation license PYCHARM: Apache license SPYDER: MIT license
  • 17. ● Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. ● Python is a programming language that lets you work more quickly and integrate your systems more effectively. 1. Web development 2. Handle Big data 3. Handles complex Mathematics 4. Software development 5. Connects to database systems Python & Uses.
  • 18. print("Python" +" is "+"cool!") "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com/ Pluralsight Platform 18 Big names using Python
  • 19. "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com print("Python"+" is"+"cool!") https://opencv.org/ Image Processing using Python 19
  • 20. "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com print("Python"+" is"+"cool!") https://www.pygame.org Game Development using Python 20
  • 21. "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com 16 print("Python"+" is"+"cool!") https://matplotlib.org/ Data Science using Python
  • 22. "Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com print("Python"+" is"+"cool!") https://github.com/amueller/word_cloud Natural Language Processing (NLP) and Text Mining using Python 22
  • 23. print("Python" +" is "+"cool!") Top programming languages 2019 by IEEE Spectrum 2 3
  • 25. Google Colab • Colaboratory, or “Colab” for short, is a product from Google Research. • Colab allows anybody to write and execute arbitrary python code through the browser, and is especially well suited to machine learning, data analysis and education. • More technically, Colab is a hosted Jupyter notebook service that requires no setup to use, while providing free access to computing resources including GPUs (graphics processing unit ).
  • 29. Google Colab How to open: 'py' is a regular python file. It's plain text and contains just your code. ... 'ipynb' is a python notebook and it contains the notebook code, the execution results and other internal settings in a specific format.
  • 30. How to install Python the Anaconda way 1. Download Anaconda (which includes Python): https://www.anaconda.com/download/ 2. Run the installer and follow the installation instructions 3. Run the Spyder editor and create your first Python program "helloworld.py" PythonSetup 30
  • 31. How to install Python the Anaconda way 1. Download Anaconda (which includes Python and relevant libraries): https://www.anaconda.com/distribution/ 2. Run the installer and follow the instructions 3. Run the Spyder editor or Jupyter Notebook and create your first Python program "helloworld.py" PythonSetup 31
  • 32. Installation Steps Install using the instruction given in the below links - 1. Install Jupyter - http://jupyter.org/install Preferred installation method is through Anaconda distribution. Install Python 3.8 version. 2. Anaconda 5.2 For Linux Installer - https://www.anaconda.com/download/#linux 3. Anaconda 5.2 For macOS Installer - https://www.anaconda.com/download/#macos 4. Anaconda 5.2 For Windows Installer - https://www.anaconda.com/download/#windows (You need to download the version compatible with your OS) 32
  • 33. Python Install 33 Many PCs and Macs will have python already installed. 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): C:UsersYour Name>python --version 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 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: C:UsersYour Name>python helloworld.py
  • 34. Execute Python Syntax 34 As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: print("Hello, Karunyans!") Hello, Karunyans! Or by creating a python file on the server, using the .py file extension, and running it in the Command Line: C:UsersYour Name>python myfile.py
  • 36. Installing Python IDLE PYTHON.ORG | MICROSOFT VISUAL STUDIO
  • 37. Setting Python in Environment Varaibles to access from Command window
  • 40. Indentation in python!! 40 Indentation refers to the spaces at the beginning of a code line. (Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important) Python uses indentation to indicate a block of code. if 5 > 2: print("Five is greater than two!") Python will give you an error if you skip the indentation: if 5 > 2: print("Five is greater than two!") The number of spaces is up to you as a programmer, but it has to be at least one. if 5 > 2: print("Five is greater than two!") if 5 > 2: print("Five is greater than two!") You have to use the same number of spaces in the same block of code, otherwise Python will give you an error: if 5 > 2: print("Five is greater than two!") print("Five is greater than two!") Syntax Error:
  • 41. Add two number. a = 5.4 b = 4.6 sum = float(a) + float(b) print(sum) User Input. a = input(“Enter number1: “) b = input(“Enter number2: “) sum = int(a) + int(b) print(“The sum of {0} and {1} is {2}”.format(a, b, sum))
  • 42. Slicing 42 b = "Hello, World!" print(b[2:5]) b = "Hello, World!" print(b[:5]) b = "Hello, World!" print(b[2:]) b = "Hello, World!" print(b[-5:-2])
  • 43. 43 • String is a sequence of characters, like "Python is cool" • Each character has an index •Accessing a character: string[index] x = "Python i s cool" print(x[10]) •Accessing a substring via slicing: s t r i n g [ s t a r t : f i n i s h ] p r i n t ( x [ 2 : 6 ] ) String P y t h o n i s c o o l 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 44. 44 >>> x = "Python is cool" >>> "cool" in x >>> len(x) >>> x + "?" >>> x.upper() # membership # length of string x # concatenation # to upper case >>> x.replace("c", "k") # replace characters in a string StringOperations P y t h o n i s c o o l 0 1 2 3 4 5 6 7 8 9 10 11 12 13
  • 45. >>> x = "Python is cool" StringOperations:Split P y t h o n i s c o o l 0 1 2 3 4 5 6 7 8 9 10 11 12 13 P y t h o n 0 1 2 3 4 5 i s 0 1 c o o l 0 1 2 3 x . s p l i t ( " " ) >>> x.split(" ") 45
  • 46. >>> x = "Python is cool" >>> y = x.split(" ") >>> ",".join(y) 40 StringOperations:Join P y t h o n , i s , c o o l 0 1 2 3 4 5 6 7 8 9 10 11 12 13 P y t h o n 0 1 2 3 4 5 i s 0 1 c o o l 0 1 2 3 " , " . j o i n ( y )
  • 48. Conditionals and Loopsin RealLife 48 Conditionals andLoops
  • 49. 49 • Cores of programming! • Rely on boolean expressions which return either True or False • 1 < 2 : True • 1.5 >= 2.5 : False • answer == "Computer Science" : can be True or False depending on the value of variable answer • Boolean expressions can be combined with: and, or, not • 1 < 2 and 3 < 4 : True • 1.5 >= 2.5 or 2 == 2 : True • not 1.5 >= 2.5 : True ConditionalsandLoops
  • 50. 50 Conditionals: SimpleForm i f condition: i f - code else: else- code
  • 52. If & Elif. a = 33 b = 33 if a > b: print(“a is greater than b") elif a == b: print("a and b are same") else: print("b is greater than a") AND | OR. a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") #if a > b or c > a: # print(“only one is True")
  • 53. 53 Conditionals:(Drivinglicenseage) age = 20 if age < 16: print("Not Eligible for Driving license!") else: print("OK, You are eligible to get your Driving license!")
  • 54. 54 Conditionals:usingInput() age = int(input("Enter your age: ")) if age < 16: print("Not Eligible for Driving license!") else: print("OK, You are eligible to get your Driving license!")
  • 55. 55 Conditionals:Grading grade = int(raw_input("Numeric grade: ")) if grade >= 80: print("A") elif grade >= 65: print("B") elif grade >= 55: print("C") else: print("E")
  • 56. 56 Loops • Useful for repeating code! • Two variants: while boolean-expression: code-block for element i n collection: code-block
  • 57. While Loops 57 while boolean-expression: code-block while input("Which is the best subject? ") != "ECE": print("Try again!") print("Of course it is!")
  • 58. 58 WhileLoops x = 5 while x > 0: print (x ) x -= 1 print("While loop i s over now!") while boolean-expression: code-block
  • 59. While Loops 59 while boolean-expression: code-block while input("Which i s the best subject? " ) != "Computer Science": print("Try again!") print("Of course i t i s ! " )
  • 60. So far, we have seen (briefly) two kinds of collections: string and list For loops can be used to visit each collection's element: 60 ForLoops for element i n collection: code-block for chr in "string": print(chr) for elem in [ 1 ,3,5]: print(elem)
  • 61. While. i = 1 while i < 20: print(i) i += 1 FOR. for x in range(10): print(x) for x in range(1, 10): print(x) for x in range(1, 10, 2): print(x)
  • 62. Expression and Arithmetic 62 Assume variable a holds 10 and variable b holds 20, then −
  • 63. Expression and Arithmetic 63 a = 21 b = 10 c = 0 c = a + b print ("Line 1 - Value of c is ", c) c = a - b print ("Line 2 - Value of c is ", c) c = a * b print ("Line 3 - Value of c is ", c) c = a / b print ("Line 4 - Value of c is ", c) c = a % b print ("Line 5 - Value of c is ", c) a = 2 b = 3 c = a**b print ("Line 6 - Value of c is ", c) a = 10 b = 5 c = a//b print ("Line 7 - Value of c is ", c) ref: https://realpython.com/python-operators-expressions/ Extra notes
  • 65. • Working with data heavily involves reading and writing! • Data come in two types: • Text: Human readable, encoded in ASCII/UTF-8, example: .txt, .csv • Binary: Machine readable, application-specific encoding, example: .mp3, .mp4, .jpg Input/Output 65
  • 66. 66 python is cool Input cool.txt x = open("cool.txt", "r") # read mode y = x.read() # read the whole print(y) x.close()
  • 67. python is cool 44 Input cool.txt x = open("cool. t x t " , " r " ) # read l i n e by l i n e f o r l i n e i n x : l i n e = l i n e . r e p l a c e ( " n " , " " ) p r i n t ( l i n e ) x . close( )
  • 68. 68 python is cool Input cool.txt x = open( "C: User s Desktop coo l . tx t " , " r " ) # absolute location f o r l i n e i n x : l i ne = l ine. r eplace(" n" , " " ) p r i n t ( l i n e ) x.close()
  • 69. Output # write mode x = open( "cool.t x t " , "w") x.write("and Interesting n") x . close() # append mode 69 x = open( "cool.t x t " , "a") x.write(" and Interesting n ") x . close() Write mode overwrites files, while append mode does not overwrite files but instead appends at the end of the files' content
  • 72. 72 • Functions encapsulate code blocks • Why functions? Modularization and reuse! • You actually have seen examples of functions: • print() • input() • Generic form: Functions def function-name(parameters): code-block return value
  • 74. Functions:CelciustoFahrenheit def celsius_to_fahrenheit(celsius): fahrenhe i t = celsiu s * 1.8 + 32.0 return fahrenheit def function-name(parameters): code-block return value 74
  • 75. 75 Functions:DefaultandNamedParameters def hello(name_man="Bro",name_woman="Sis"): print("Hello, " + name_man +"&"+name_woman+ "!") >>> hello() Hello, Bro& Sis! >>>hello(name_woman="Lady") Hello, Bro & Lady! >>> hello(name_woman=“Girls",name_man="Boys") Hello, Boys & Girls!
  • 76. Built-in Math Functions 76 x = min(5, 10, 25) y = max(5, 10, 25) print(x) print(y) x = abs(-7.25) print(x) x = pow(4, 3) print(x) import math import math x = math.sqrt(64) print(x) x = math.ceil(1.4) y = math.floor(1.4) print(x) # returns 2 print(y) # returns 1 x = math.pi print(x)
  • 77. 77 • Code made by other people shall be reused! • Two ways of importing modules (= Python files): • Generic form: importmodule_name import math print(math.sqrt(4)) • Generic form: from module_name import function_name from math import sqrt p r i n t ( s q r t ( 4 ) ) Imports
  • 78. Math Methods 78 Method Description math.acos() Returns the arc cosine of a number math.acosh() Returns the inverse hyperbolic cosine of a number math.asin() Returns the arc sine of a number math.asinh() Returns the inverse hyperbolic sine of a number math.atan() Returns the arc tangent of a number in radians math.atan2() Returns the arc tangent of y/x in radians math.atanh() Returns the inverse hyperbolic tangent of a number math.ceil() Rounds a number up to the nearest integer math.comb() Returns the number of ways to choose k items from n items without repetition and order math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter math.cos() Returns the cosine of a number math.cosh() Returns the hyperbolic cosine of a number math.degrees() Converts an angle from radians to degrees math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point math.erf() Returns the error function of a number math.erfc() Returns the complementary error function of a number math.exp() Returns E raised to the power of x math.expm1() Returns E x - 1 math.fabs() Returns the absolute value of a number math.factorial() Returns the factorial of a number math.floor() Rounds a number down to the nearest integer math.fmod() Returns the remainder of x/y math.frexp() Returns the mantissa and the exponent, of a specified number math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.) math.gamma() Returns the gamma function at x math.gcd() Returns the greatest common divisor of two integers math.hypot() Returns the Euclidean norm math.isclose() Checks whether two values are close to each other, or not math.isfinite() Checks whether a number is finite or not math.isinf() Checks whether a number is infinite or not math.isnan() Checks whether a value is NaN (not a number) or not math.isqrt() Rounds a square root number downwards to the nearest integer math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i math.lgamma() Returns the log gamma value of x math.log() Returns the natural logarithm of a number, or the logarithm of number to base math.log10() Returns the base-10 logarithm of x math.log1p() Returns the natural logarithm of 1+x math.log2() Returns the base-2 logarithm of x math.perm() Returns the number of ways to choose k items from n items with order and without repetition math.pow() Returns the value of x to the power of y math.prod() Returns the product of all the elements in an iterable https://www.w3schools.com/python/module_math.asp
  • 79. Math Methods 79 math.radians() Converts a degree value into radians math.remainder() Returns the closest value that can make numerator completely divisible by the denominator math.sin() Returns the sine of a number math.sinh() Returns the hyperbolic sine of a number math.sqrt() Returns the square root of a number math.tan() Returns the tangent of a number math.tanh() Returns the hyperbolic tangent of a number math.trunc() Returns the truncated integer parts of a number Math Constants Constant Description math.e Returns Euler's number (2.7182...) math.inf Returns a floating-point positive infinity math.nan Returns a floating-point NaN (Not a Number) value math.pi Returns PI (3.1415...) math.tau Returns tau (6.2831...)
  • 80. cmath Module 80 Method Description cmath.acos(x) Returns the arc cosine value of x cmath.acosh(x) Returns the hyperbolic arc cosine of x cmath.asin(x) Returns the arc sine of x cmath.asinh(x) Returns the hyperbolic arc sine of x cmath.atan(x) Returns the arc tangent value of x cmath.atanh(x) Returns the hyperbolic arctangent value of x cmath.cos(x) Returns the cosine of x cmath.cosh(x) Returns the hyperbolic cosine of x cmath.exp(x) Returns the value of E x , where E is Euler's number (approximately 2.718281...), and x is the number passed to it cmath.isclose() Checks whether two values are close, or not cmath.isfinite(x) Checks whether x is a finite number cmath.isinf(x) Check whether x is a positive or negative infinty cmath.isnan(x) Checks whether x is NaN (not a number) cmath.log(x[, base]) Returns the logarithm of x to the base cmath.log10(x) Returns the base-10 logarithm of x
  • 81. cmath Module 81 cmath.phase() Return the phase of a complex number cmath.polar() Convert a complex number to polar coordinates cmath.rect() Convert polar coordinates to rectangular form cmath.sin(x) Returns the sine of x cmath.sinh(x) Returns the hyperbolic sine of x cmath.sqrt(x) Returns the square root of x cmath.tan(x) Returns the tangent of x cmath.tanh(x) Returns the hyperbolic tangent of x cMath Constants Constant Description cmath.e Returns Euler's number (2.7182...) cmath.inf Returns a floating-point positive infinity value cmath.infj Returns a complex infinity value cmath.nan Returns floating-point NaN (Not a Number) value cmath.nanj Returns coplext NaN (Not a Number) value cmath.pi Returns PI (3.1415...) cmath.tau Returns tau (6.2831...)
  • 82. Creating a Function -recap 82 • A function is a block of code which only runs when it is called. • You can pass data, known as parameters, into a function. • A function can return data as a result. In Python a function is defined using the def keyword: def my_function(): print("Hello from a function") Calling a Function my_function()
  • 83. Creating a Function -recap 83 Arguments • Information can be passed into functions as 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: def my_function(fname): print(fname + “ Keep doing") my_function(“John") my_function(“SAM") my_function(“Raj")
  • 84. Creating a Function -recap 84 Parameters or Arguments? The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the 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. If you try to call the function with 1 or 3 arguments, you will get an error: def my_function(fname, lname): print(fname + " " + lname) my_function("Samuel", "Abhishek")
  • 85. Creating a Function -recap 85 Arbitrary Arguments, *args • 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 of arguments, and can access the items accordingly: def my_function(*kids): print("The youngest child is " + kids[2]) my_function(“John", “SAM", “Raj") Keyword Arguments You can also send arguments with the key = value syntax. This way the order of the arguments does not matter. def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = “John", child2 = “SAM", child3 = “Raj")
  • 86. Creating a Function -recap 86 Arbitrary Keyword Arguments, **kwargs 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 of arguments, and can access the items accordingly: def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = “John", lname = “Sam") Default Parameter Value The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value: def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil")
  • 87. Creating a Function -recap 87 Passing a List as an Argument You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. E.g. if you send a List as an argument, it will still be a List when it reaches the function: def my_function(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] my_function(fruits) Return Values To let a function return a value, use the return statement: def my_function(x): return 5 * x print(my_function(3)) print(my_function(5)) print(my_function(9))
  • 88. Creating a Function -recap 88 The pass Statement 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. 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.
  • 89. Creating a Function -recap 89 def tri_recursion(k): if(k > 0): result = k + tri_recursion(k - 1) print(result) else: result = 0 return result print("nnRecursion Example Results") tri_recursion(6) 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.
  • 90. How to include pandas & numpy? 90 import numpy as np import pandas as pd
  • 91. Fuction. def funName(): print("Hello from a function") funName() File Handling. a = open(‘pantech.txt’, ‘r’) print(a.read()) a.close()