“Python” or “CPython” is written in C/C+

Mukeshpanigrahy1 55 views 74 slides Jun 24, 2024
Slide 1
Slide 1 of 74
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74

About This Presentation

This Programming Language Python Tutorial is very well suited for beginners and also for experienced programmers. This specially designed free Python tutorial will help you learn Python programming most efficiently, with all topics from basics to advanced (like Web-scraping, Django, Learning, etc.) ...


Slide Content

Workshop On Python By V.Srikanth

Company uses Python

Jobs For Programming Languages 2018

Jobs For Programming Languages 2018

Why Python Python statements do not end in a semicolon In Python there are no Braces Python is interpretive that is you can just enter statements into the Python environment and they’ll execute

Basic Applications Of Python Web Development Djang o Flask Data Analysis matplotlib seaborn Machine Learning Scikit-learn TensorFlow Scripting Embedded Systems Raspberry Pi Game Development PyGame Desktop Applications Tkinter

INTRODUCTION Python is a high-level programming language Open source and community driven Source can be compiled or run just-in-time Python is an interpreted (checks the code line by line) Python is an object oriented language

INTRODUCTION “ Python ” or “ CPython ” is written in C/C++ - Version 2.7 came out in mid-2010 - Version 3.7 came out in early 2018 “ Jython ” is written in Java for the JVM “ IronPython ” is written in C# for the .Net environment

Python Interfaces IDLE – a cross-platform Python development environment Python Shell – running 'python' from the Command Line opens this interactive shell PyCharm Community – It is Integrated Development Environment (IDE) which provides code analysis a graphical debugger an integrated unit tester. Anaconda – It is open source distribution of python and R programming languages for large-scale data processing , predictive analytics and scientific computing.

Python commands Lines:- Statement separator is a semicolon , but is only needed when there is more than one statement on a line. Comments:- line starts with ‘#’ is ignored . Multiline comments are also possible, and are enclosed by triple double-quote symbols """ This is an example of a long comment that goes on and on and on. """

PRINT FUNCTION

PRINT FUNCTION

Numbers And Data Types Python supports three different numerical types :- 1. Integers 2. Float 3. Complex The Type function is used to see the type of Data Example >>> type ( -75) <type ’ int ’> >>> type (5.0) <type ’float ’> >>> type (12345678901) <type ’long ’> >>> type ( -1+2j) <type ’complex’>

Strings Strings are sequences of characters enclosed in single or double quotes: >>> " This is a string " ’ This is a string ’ str = 'Hello World! print ( str ) # Prints complete string >>> Hello World! print ( str [0]) # Prints first character of the string >>> H Print ( str [2:5]) # Prints characters starting from 3rd to 5 th >>> llo

Strings print ( str [2:]) # Prints string starting from 3rd character >>> llo World! print ( str * 2) # Prints string two times >>> Hello World! Hello World! print ( str + "TEST ") # Prints concatenated string >>> Hello World!TEST

Lists And Tuples Lists A list contains items separated by commas and enclosed within square brackets ( [ ] ). To some extent, lists are similar to arrays in C. One of the differences between them is that all the items belonging to a list can be of different data type . Example list = [ ‘VITAM' , 519 , 2.23, “python”, -0.1 ] print (list) # Prints complete list >>> VITAM , 519 , 2.23, python, -0.1 List[2]=111 >>> VITAM , 111 , 2.23, python, -0.1

Lists And Tuples print (list[0]) # Prints first element of the list >>> VITAM print (list[1:3]) # Prints elements starting from 2nd till 3 rd >>> 519 , 2.23 print (list[2:]) # Prints elements starting from 3rd element >>> 2.23, “python”, -0.1 print (list * 2) # Prints list two times >>> VITAM , 519 , 2.23, python, -0.1 VITAM , 519 , 2.23, python, -0.1

Lists And Tuples Tuples A tuple is sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parenthesis ( ) . The main difference between list and tuples are in lists the elements and size can be changed where as in tuples cannot be updated these are read only lists.

Used to perform conversions between the built-in types To convert between types, you simply use the type-name as a function. Example float(x) # Converts x to a floating-point number. str (x) # Converts object x to a string chr (x) # Converts an integer to a character. Data Type Conversion

Range function Used to create lists of integers. Range(n) produces a list of numbers 0, 1, 2, . . . , n − 1 starting with and ending with n − 1 . Example >>> range(4) [ 0 1 2 3] >>> range (1 ,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range ( -6 ,0) [-6, -5, -4, -3, -2, -1] >>> range (1 ,10 ,2) [1, 3, 5, 7, 9] >>> range (10 ,0 , -2) [10 , 8, 6, 4, 2]

Operators in Python The different Operators used in Python are:- Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Bitwise Operators Identity Operators Membership Operators

Arithmetic Operators ‘ + ’ :- Add two operands {2+2=4} ‘ - ’ :- Subtract two operands {2-1=3} ‘ * ’ :- Multiply two operands {2*3=6} ‘ / ’ :- Divide left with right operand {5/2=2.5} ‘ ** ’ :- Exponential {3**2=9} ‘ % ’ :- Remainder of the division {7%2=1} ‘ // ’ :- Floor Division where decimal is removed after division {5//2=2}

Assignment Operators ‘ = ’ :- Assigns values from right side operands to left side operand. >>> c= a + b ‘ += ’ :- It adds right to the left operand and assign the result to left. >>> c += a { c = c + a } ‘ - = ’ :- It subtracts right from the left operand and assign the result >>> c -= a { c = c - a } ‘ / = ’ :- It divides left operand with the right and assign the result >>> c /= a { c = c / a } ‘ % = ’ :- It takes modulus using two operands and assign the result. >>> c %= a { c = c % a } ‘ **= ’ :- Performs exponential (power) calculation on operators and assign value to the left operand >>> c **= a { c = c ** a }

Comparison Operators “ == “ :- If the values of two operands are equal, then the condition becomes true. “ != “ :- If values of two operands are not equal, then condition becomes true. “ > “ :- If the value of left operand is greater than the value of right operand, then condition becomes true. “ < “ :- If the value of left operand is less than the value of right operand, then condition becomes true. “ >= “ :- If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. “ <= “ :- If the value of left operand is less than or equal to the value of right operand, then condition becomes true.

Logical Operators AND : - If both the operands are true then condition becomes true. OR :- If any of the two operands are non-zero then condition becomes true. NOT:- Used to reverse the logical state of its operand

Bitwise Operators Bitwise operator works on bits and performs bit-by-bit operation Example If a = 0011 1100 b = 0000 1101 Binary AND “&” >>> a & b = 0000 1100 Binary OR “ |” >>> a | b = 0011 1101 Binary XOR “^” >>> a ^ b =0011 0001 Binary Complement “ ~ ” >>> (~a)= 1100 0011

Identity Operators Is :- Evaluates to true if the variables on either side of the operator point to the same object and false otherwise . Is not :- Evaluates to false if the variables on either side of the operator point to the same object and true otherwise Example

Membership Operators In :- Evaluates to true, if it finds a variable in the specified sequence and false otherwise. not in:- Evaluates to true, if it does not find a variable in the specified sequence and false otherwise. Example if a=5 b=8 odd=[1, 3 ,5, 7, 9] if ( a in list ): print ("Line 1 - a is available in the given list") else: print ("Line 1 - a is not available in the given list")

Decision Making IF Statement The if statement contains a logical expression using which the data is compared and a decision is made based on the result of the comparison. Syntax if expression: statement(s) Example value1=10;value2=0 if value1: print(‘statement1 is true’) if value2: print(‘statement2 is true’) Output :- statement1 is true

IF...ELIF...ELSE Statements An else statement can be combined with an if statement. An else statement contains a block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. Syntax if expression: statement(s) else: statement(s) Example ldr =0 if ldr ==1: print (“turn off light”) else: print (“turn on light”) Output :- turn on light

The elif Statement Syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)

The elif Statement Example a= int (input("enter the number:")) if (8<=a<=10): print ('first') elif (5<=a<=7): print('second') elif a<5: print('third') else: print ('invalid cgpa ') enter the number:9 first

Loop 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. While Loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body. Syntax while expression: statement(s)

Example count = 0 while (count < 3): print ('The count is:', count) count = count + 1 print ("Good bye!") Output:- The count is: 0 The count is: 1 The count is: 2 Good bye!

The Infinite Loop A loop becomes infinite loop if a condition never becomes FALSE. An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required. Example var = 1 while var == 1 : num = int (input("Enter a number :")) print ("You entered: ", num) print ("Good bye!")

Using else Statement with Loops else statement is used with a while loop, the else statement is executed when the condition becomes false. Example count = 0 while count < 3: print (count, " is less than 3") count = count + 1 else: print (count, " is not less than 3")

For Loop The for statement in Python has the ability to iterate over the items of any sequence, such as a list or a string Syntax for iterating_var in sequence: statements(s) Example for i in range (1,5): print ( i ) Output:- 1 2 3 4

For Loop Example for i in range (1,10,3): print ( i ) Output:- 1 4 7 c=0 for i in range (1,10,3): c=c+1 print (c) print ( "loop closed" ) Output:- 1 2 3 loop closed

For Loop list=[ "one" , "two" , "three" , 'four' , 'five' ] for i in list: print ( i ) print ( "loop closed" ) Output:- one two three four five loop closed

For Loop How to use break statements in For Loop Breakpoint is a unique function in For Loop that allows you to break or terminate the execution of the for loop Example for i in range(5,20): if ( i ==10): break print ( i ) print ( "loop closed" ) Output:- 5 6 7 8 9 loop closed

For Loop How to use "continue statement" in For Loop Continue function, will terminate the current iteration of the for loop BUT will continue execution of the remaining iterations. Example for i in range(1,10): if (i%2 ==0) : continue print ( i ) print ( "loop closed" ) Output:- 1 3 5 7 9 loop closed

For Loop How to use "enumerate" function for "For Loop“ Enumerate function returns the index number for the member and the member of the collection that we are looking at. Example list=[ "one" , "two" , "three" , 'four' , 'five' ] for i,l in enumerate (list): print( i,l ) Output:- 0 one 1 two 2 three 3 four 4 five

Mathematical Functions Python have different functions for mathematical calculations 1. abs( ):- returns the absolute value of x i.e the positive distance between x and zero. Syntax abs(x) Example x= int ( input(“enter the number”)) print (“The absolute value of x is:”, abs(x)) Output enter the number -36 The absolute value of x is: 36

Mathematical Functions 2. ceil():- This method returns the ceiling value of x i.e. the smallest integer not less than x. Syntax import math math.ceil ( x ) Example import math x= float(input( "enter the number" )) print( "The ceil value of x is:" , math.ceil (x)) Output enter the number123.25 The ceil value of x is: 124

Mathematical Functions 3. exp():- The exp() method returns exponential of x: e x . Syntax import math math.exp( x ) Example import math x= float(input( "enter the number" )) print( "The exp value of x is:" , math.exp(x)) Output enter the number0 The exp value of x is: 1.0

Mathematical Functions 4. floor():- This method returns the floor of x i.e. the largest integer not greater than x. Syntax import math math.floor ( x ) Example import math x= float(input( "enter the number" )) print( "The floor value of x is:" , math.floor (x)) Output enter the number134.4 The floor value of x is: 134

Mathematical Functions 5. log():- The log() method returns the natural logarithm of x, for x > 0. Syntax import math math.log( x ) Example import math x= float(input( "enter the number" )) print( "The log value of x is:" , math.log(x)) Output enter the number10 The log value of x is: 2.302585092994046

Mathematical Functions 6. max( ):- The max() method returns the largest of its arguments i.e. the value closest to positive infinity. Syntax max(x, y, z, .... ) Example print( "the maximum value" ,max (10,15,-20)) Output the maximum value 15

Mathematical Functions 7. min():- The method min() returns the smallest of its arguments i.e. the value closest to negative infinity. Syntax min(x, y, z, .... ) Example print( "the minimum value" ,min (10,15,-20)) Output the maximum value -20

Mathematical Functions 8. sqrt ():- The sqrt () method returns the square root of x for x > 0. Syntax import math math.sqrt ( x ) Example import math x= float(input( "enter the number" )) print( "The square root value of x is:" , math.sqrt (x)) Output enter the number4 The square root value of x is: 2.0

Mathematical Functions 9. pow ():- This method returns the value of x y . Syntax import math math.pow( x ) Example import math x= float(input( "enter the number :" )) y= float(input( "enter the number :" )) print( "x to the power y is:" , math.pow( x,y )) Output enter the number :5 enter the number : 2 x to the power y is: 25.0

Mathematical Functions 9. pow ():- This method returns the value of x y . Syntax import math math.pow( x ) Example import math x= float(input( "enter the number :" )) y= float(input( "enter the number :" )) print( "x to the power y is:" , math.pow( x,y )) Output enter the number :5 enter the number : 2 x to the power y is: 25.0

Random Number Functions 10. randrange():- The randrange() method returns a randomly selected element from range(start, stop, step). Syntax Import random randrange ([start,] stop [,step]) Example import random print( "the random value" ,random.randrange(1,7,1)) Output the random value 4

Date and Time Function Date formats is a common chore for computers. Python's time and calendar modules help track dates and times Syntax Import time time.localtime () Example import time localtime = time.localtime () print ( "Local current time :" , localtime ) Output

Date and Time Function Time in a readable format is asctime () − Syntax Import time time.asctime () Example import time localtime = time.asctime () print ( "Local current time :" , localtime ) Output Local current time : Tue Dec 19 23:36:20 2017

Getting calendar for a month Example import calendar cal = calendar.month (2018, 1) print ( "Here is the calendar:" ) print (cal) Output Here is the calendar: January 2018 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Functions Functions in Python are used to utilize the code in more than one place in a program, sometimes also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions. Function in Python is defined by the "def " statement followed by the function name and parentheses “ ( ) ”. Syntax def function name( parameters ): "function_docstring" function_suite return [expression]

Functions Example1 def func1(): print( "VITAM" ) func1() Output VITAM Example2

Functions Example3 age= int (input( "enter the Age:" )) name=input( "enter the Name:" ) def printinfo( name, age ): print ( "Name: " , name) print ( "Age: " , age) return printinfo( age, name ) Output enter the Age:30 enter the Name:srikanth Name: 30 Age : srikanth

How Function Return Value? Return command in Python specifies what value to give back to the caller of the function Example def square(x): return x*x print(“The square of the number is:”,square(12)) Output The square of the number is: 144

Example def printinfo(arg1, *vartuple ): print( "Output is: " ) print(arg1) for var in vartuple: print( var ) return printinfo(10) printinfo(70, 60, 50) Output Output is: 10 Output is: 70 60 50

Design a Die Rolling Simulator using python from random import randrange def show_die (num): print( "DIE NUMBER IS" ) print( " " ) if num==1: print( "| |" ) print( "| * |" ) print( "| |" ) elif num==2: print( "|* |" ) print( "| |" ) print( "| *|" ) elif num==3: print( "|* |" ) print( "| * |" ) print( "| *|" )

elif num == 4: print( "|* *|" ) print( "| |" ) print( "|* *|" ) elif num == 5: print( "|* *|" ) print( "| * |" ) print( "|* *|" ) elif num == 6: print( "|* * *|" ) print( "| |" ) print( "|* * *|" ) else : print( "error in die value" ) def roll(): return randrange(1,7) def main(): show_die (roll()) main()

Design a calculator def help_screen (): print( "Add: Adds two numbers" ) print( "Subtract: Subtracts two numbers" ) print( "Print: Displays the result of the latest operation" ) print( "Help: Displays this help screen" ) print( "Quit: Exits the program" ) def menu(): return input( "=== A) dd S) ubtract P) rint H) elp Q) uit ===" ) def main(): result = 0.0 done = False ;

while not done: choice = menu() if choice == "A" or choice == "a" : arg1 = float(input( "Enter arg 1: " )) arg2 = float(input( "Enter arg 2: " )) result = arg1 + arg2 print(result) elif choice == "S" or choice == "s" : arg1 = float(input( "Enter arg 1: " )) arg2 = float(input( "Enter arg 2: " )) result = arg1 - arg2 print(result) elif choice == "P" or choice == "p" : # Print print(result) elif choice == "H" or choice == "h" : # Help help_screen () elif choice == "Q" or choice == "q" : # Quit done = True main()

Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module can define functions, classes and variables. A module can also include run able code. A module is an object. A module (object) can be shared. A specific module is imported only once in a single run. This means that a single module object is shared by all the modules that import it.

The import Statement You can use any Python source file as a module by executing an import statement in some other Python source file The modules are imported from other modules using the import command Example: def print_func ( par ): print ( "Hello : " , par) return Save the program with file name support.py import support support.print_func ( " vitam " ) Save the program with file name vitam.py Output: Hello : vitam

The from...import Statement Python's from statement lets you import specific attributes from a module into the current namespace. Syntax from modulename import name1 Example from math import cos print( cos (0)) Output 1.0

The from...import * Statement: It is also possible to import all the names from a module into the current namespace Syntax from modname import * Example from tkinter import * root= Tk () Executing Modules as Scripts: Within a module, the module’s name is available as the value of the global variable __name__. The code in the module will be executed, just as if you imported it but with the __name__ set to "__main__".

Example: import support def main(): support.print_func ( " vitam " ) if __name__ == '__main__' : main() Output Hello : vitam

Class & Objects Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. In Python, classes are defined by the "Class" keyword. class myClass (): The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. Python adds the self argument to the list and do not need to include it when you call the methods.

Class & Objects def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1
Tags