Learn about Python power point presentation

omsumukh85 104 views 68 slides Oct 20, 2024
Slide 1
Slide 1 of 68
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

About This Presentation

.


Slide Content

What is Python? Python is a popular programming language. It was created by Guido van Rossum , and released in 1991.

Python can be used on a server to create web applications . Python can be used alongside software to create workflows . Python can connect to database systems. It can also read and modify files . Python can be used to handle big data and perform complex mathematics . Python can be used for rapid prototyping, or for production-ready software development. What can Python do?

Python Syntax compared to other programming languages Python was designed for readability, and has some similarities to the English language with influence from mathematics . Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses . Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Python Syntax for Execution As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line: >>> print("Hello, World!") Hello, World! Or by creating a python file on the server, using the . py file extension, and running it in the Command Line: C:\Users\ Your Name >python myfile.py

Python Indentation 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 . Example 1 if  5 > 2:    print ("Five is greater than two!")

Example 2 Syntax Error: 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:

Python  Comments Comments can be used to explain Python code . Comments can be used to make the code more readable . Comments can be used to prevent execution when testing code . Comments starts with a #, and Python will ignore them: 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 : print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code: Example #print("Hello, World !") print ("Cheers, Mate!") print (" Cheers # Mate !") Here the # symbol is not treated as comment, rather it is part of the text to be displayed.

Variables Variables are containers for storing data values. Creating Variables: Python has no command for declaring a variable. A variable is created the moment you first assign a value to it . Example x = 5 y = "John" print(x) print(y)

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 _ ) Variable names are case-sensitive (age, Age and AGE are three different variables)

Legal variable names: myvar = "John" my_var = "John" _ my_var = "John" myVar = "John" MYVAR = "John" myvar2 = " John“ Illegal variable names: 2myvar = "John" my- var = "John" my var = "John"

Many Values to Multiple Variables Python allows you to assign values to multiple variables in one line: Example x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z)

Output Variables The Python print statement is often used to output variables. To combine both text and a variable, Python uses the + character: Example x = "awesome" print("Python is " + x)

Global Variables Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside. Example Create a variable outside of a function, and use it inside the function x = "awesome" def   myfunc ():   print("Python is " + x) myfunc ()

Built-in Data Types In programming, data type is an important concept . 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: Python Data Types

Text Type: str Numeric Types: int , float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set,  frozenset Boolean Type: bool Binary Types: bytes,  bytearray ,  memoryview

Getting the Data Type You can get the data type of any object by using the type()  function Example Print the data type of the variable x: x = 5 print(type(x))

Setting the Data Type In Python, the data type is set when you assign a value to a variable : Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset ({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello " bytes x = bytearray (5) bytearray x = memoryview (bytes(5)) memoryview

Python Numbers There are three numeric types in Python: int float complex Variables of numeric types are created when you assign a value to them : Example x = 1    # int y = 2.8  # float z = 1j   # complex To verify the type of any object in Python, use the type() function : Example print(type(x)) print(type(y)) print(type(z))

Python Casting There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions: int () - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) str () - constructs a string from a wide variety of data types, including strings, integer literals and float literals Example Integers: x =  int (1)   # x will be 1 y =  int (2.8) # y will be 2 z =  int ("3") # z will be 3

Python Data Types Data type  defines the type of the variable, whether it is an integer variable, string variable, tuple, dictionary, list etc. Python data types are divided in two categories, mutable data types and immutable data types. Immutable Data types in Python Numeric String Tuple Mutable Data types in Python List Dictionary Set and immutable data types .

Immutable Data types in Python Numeric Data Type in Python Integer  – In Python 3, there is no upper bound on the integer number which means we can have the value as large as our system memory allows . # Integer numbernum = 100 print( num ) print ("Data Type of variable num is", type( num )) Output :

Immutable Data types in Python Long  – Long data type is deprecated in Python 3 because there is no need for it, since the integer has no upper limit, there is no point in having a data type that allows larger upper limit than integers. Float  – Values with decimal points are the float values, there is no need to specify the data type in Python. It is automatically inferred based on the value we are assigning to a variable. For example here fnum is a float data type . # float numberfnum = 34.45 print( fnum ) print ("Data Type of variable fnum is", type( fnum )) Output :

Immutable Data types in Python Complex Number  – Numbers with real and imaginary parts are known as complex numbers. Unlike other programming language such as Java, Python is able to identify these complex numbers with the values. In the following example when we print the type of the variable cnum , it prints as complex number . # complex numbercnum = 3 + 4j print( cnum ) print ("Data Type of variable cnum is", type( cnum )) Output :

Immutable Data types in Python Binary, Octal and Hexadecimal numbers In Python we can print decimal equivalent of binary, octal and hexadecimal numbers using the prefixes. 0b(zero + ‘b’) and 0B(zero + ‘B’) –  Binary Number 0o(zero + ‘o’) and 0O(zero + ‘O’) –  Octal Number 0x(zero + ‘x’) and 0X(zero + ‘X’) –  Hexadecimal Number # integer equivalent of binary number 101 num = 0b101 print( num )  Output : # integer equivalent of Octal number 32 num2 = 0o32 print(num2 )  # integer equivalent of Hexadecimal number FF num3 = 0xFF print(num3)

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 print () function: Example 1 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 2 a = " Hello" print(a) Strings

You can assign a multiline string to a variable by using three quotes: Example 1 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 2 a = ''' Lorem ipsum dolor sit amet , consectetur adipiscing elit , sed do eiusmod tempor incididunt ut labore et dolore magna aliqua .''' print(a) Multiline Strings

Booleans represent one of two values: True or False. Boolean Values In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer: Example print(10 > 9) print(10 == 9) print(10 < 9) Python Booleans

When you run a condition in an if statement, Python returns True or False: Example Print a message based on whether the condition is True or False: a = 200 b = 33 if b > a:   print("b is greater than a") else:   print("b is not greater than a ")

Most Values are True Almost any value is evaluated to True if it has some sort of content. Any string is True, except empty strings. Any number is True, except 0. Any list, tuple, set, and dictionary are True, except empty ones. Example The following will return True: bool (" abc ") bool (123) bool (["apple", "cherry", "banana"])

Some Values are False In fact, there are not many values that evaluate to False, except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to False. Example The following will return False: bool (False) bool (None) bool (0) bool ("") bool (()) bool ([]) bool ({})

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 Operators

Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y // Floor division x // y Python Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations:

Python Assignment Operators Assignment operators are used to assign 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 &= 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

Python Comparison Operators Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y

Python Logical Operators Logical operators are used to combine conditional statements: Operator Description Example and  Returns True if both statements are true x < 5 and  x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)

Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example is  Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y

Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example in  Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y

Python Bitwise Operators Bitwise operators are used to compare (binary) numbers: Operator Name Description &  AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1  ^ XOR Sets each bit to 1 if only one of two bits is 1 ~  NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

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 re 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. List Items

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 ) Changeable

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 ))

It is also possible to use the list() constructor when creating a new list. Example Using the list() constructor to make a List: thislist = list(("apple", "banana", "cherry"))  # note the double round-brackets print( thislist ) The list() Constructor

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are  List, Set, and  Dicionary , all with different qualities and usage. A tuple is a collection which is ordered and  unchangeable . Tuples are written with round brackets. Example Create a Tuple: thistuple = ("apple", "banana", "cherry") print( thistuple ) Python Tuples

Tuple Items Tuple items are ordered, unchangeable, and allow duplicate values. Tuple items are indexed, the first item has index [0], the second item has index [1] etc. Ordered 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 ))

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) 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 )

Set Items are unordered, unchangeable, and do not allow duplicate values. Once a set is created, you cannot change its items, but you can add new items. Example Duplicate values will be ignored: thisset = {"apple", "banana", "cherry", "apple"} print( thisset )

Get the Length of a Set To determine how many items a set has, use the  len () method. Example Get the number of items in a set: thisset = {"apple", "banana", "cherry"} print( len ( thisset )) Set Items - Data Types Set items can be of any data type: Example String, int and boolean data types: set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False}

The set() Constructor It is also possible to use the set() constructor to make a set. Example Using the set() constructor to make a set: thisset = set(("apple", "banana", "cherry "))  # note the double round-brackets print( thisset )

Python Dictionaries thisdict = {   "brand": "Ford",   "model": "Mustang",   "year": 1964 } 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"])

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 )) Dictionary Items - Data Types The values in dictionary items can be of any data type: Example String, int , boolean , and list data types: thisdict = {   "brand": "Ford",   "electric": False,   "year": 1964,   "colors": ["red", "white", "blue"] }

Python supports the usual logical conditions from mathematics: Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword. Python If ... Else

Example If statement: a = 33 b = 200 if b > a:   print("b is greater than a") In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".

Indentation Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. Example If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error

Elif The  elif  keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Example a = 33 b = 33 if b > a:   print("b is greater than a") elif  a == b:   print("a and b are equal")

Else The else keyword catches anything which isn't caught by the preceding conditions. Example a = 200 b = 33 if b > a:   print("b is greater than a") elif  a == b:   print("a and b are equal") else:   print("a is greater than b")

If you have only one statement to execute, you can put it on the same line as the if statement. Example One line if statement: if a > b: print("a is greater than b“ Short Hand If ... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example One line if else statement: a = 2 b = 330 print("A") if a > b else print("B") Short Hand If

And The and keyword is a logical operator, and is used to combine conditional statements: Example Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a:   print("Both conditions are True")

Or The or keyword is a logical operator, and is used to combine conditional statements:The pass Statement if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example a = 33 b = 200 if b > a:   pass Example Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c:   print("At least one of the conditions is True")

Python Loops Python has two primitive loop commands: while loops for loops The while Loop With the while loop we can execute a set of statements as long as a condition is true. Example Print i as long as i is less than 6: i = 1 while  i < 6:   print( i )    i += 1

The break Statement With the break statement we can stop the loop even if the while condition is true: Example Exit the loop when i is 3: i = 1 while  i < 6:   print( i )   if  i == 3:     break    i += 1

The continue Statement With the continue statement we can stop the current iteration, and continue with the next: Example Continue to the next iteration if i is 3: i = 0 while  i < 6:    i += 1   if  i == 3:     continue   print( i )
Tags