Download presentation
Presentation is loading. Please wait.
1
Prof. K. Adisesha BE, MSc, M.Tech, NET, (Ph.D.)
Programing Prof. K. Adisesha BE, MSc, M.Tech, NET, (Ph.D.)
2
Python! Learning Objectives What is Python? Python Applications
Features of Python Installing Python IDE for Python Python Programming Basics Comments Variables Type Conversion Operators Data Types
3
Python Python is an interpreted, object-oriented, high-level programming language. As it is general-purpose, it has a wide range of applications Web development, Building desktop GUI Scientific and Mathematical computing. Created in 1991 by Guido van Rossum Named for Monty Python Used by: Google, Yahoo!, Youtube Many Linux distributions Games and apps (e.g. Eve Online)
4
Languages Some influential ones: FORTRAN COBOL LISP BASIC
science / engineering COBOL business data LISP logic and AI BASIC a simple language
5
Python Python Applications Web Development. Game Development.
Machine Learning and Artificial Intelligence. Data Science and Data Visualization. Desktop GUI. Web Scraping Applications. Business Applications. Audio and Video Applications. CAD Applications. Embedded Applications.
6
Python Features of Python Interpreted Object-Oriented
You run the program straight from the source code. Python program Bytecode a platforms native language You can just copy over your code to another system and it will auto-magically work! with python platform Object-Oriented Simple and additionally supports procedural programming Extensible – easily import other code Embeddable –easily place your code in non-python programs Extensive libraries (i.e. reg. expressions, doc generation, CGI, ftp, web browsers, ZIP, WAV, cryptography, etc...) (wxPython, Twisted, Python Imaging library)
7
Interpreted Languages
Not compiled like Java Code is written and then directly executed by an interpreter Type commands into interpreter and see immediate results Computer Runtime Environment Compiler Code Java: Interpreter Python:
8
Compiling and interpreting
Many languages require you to compile (translate) your program into a form that the machine understands. Python is instead directly interpreted into machine instructions. compile execute output source code Hello.java byte code Hello.class interpret output source code Hello.py
9
The Python Interpreter
Allows you to type commands one-at-a-time and see results A great way to explore Python's syntax Repeat previous command: Alt+P
10
Python Timeline/History
Python was conceived in the late 1980s. Guido van Rossum, born in Netherlands, was a big fan of Monty python’s Flying Circus named after. In 1991 python was first published. In January of 1994 python 1.0 was released Functional programming tools like lambda, map, filter, and reduce comp.lang.python formed, greatly increasing python’s userbase In 1995, python 1.2 was released.
11
python Timeline/History
By version 1.4 python had several new features Keyword arguments (similar to those of common lisp) Built-in support for complex numbers Basic form of data-hiding through name mangling (easily bypassed however) Computer Programming for Everybody (CP4E) initiative Make programming accessible to more people, with basic “literacy” similar to those required for English and math skills for some jobs. Project was funded by DARPA CP4E was inactive as of 2007, not so much a concern to get employees programming “literate”
12
python Timeline/History
In 2000, Python 2.0 was released. Introduced list comprehensions similar to Haskells Introduced garbage collection In 2001, Python 2.2 was released. Included unification of types and classes into one hierarchy, making pythons object model purely Object-oriented Generators were added(function-like iterator behavior) Standards
13
Installing Python Windows: Download Python from http://www.python.org
Install Python. Run Idle from the Start Menu. Mac OS X: Python is already installed. Open a terminal and run python or run Idle from Finder. Linux: Chances are you already have Python installed. To check, run python from the terminal. If not, install from your distribution's package system. Note: For step by step installation instructions, see the course web site.
14
Installing Python Installing Python On Windows
Step 1: Download the Python 3 Installer Open a browser window and navigate to the Download page for Windows at python.org. Underneath the heading at the top that says Python Releases for Windows, click on the link for the Latest Python 3 Release – Python 3.x.x. Scroll to the bottom and select either Windows x86-64 executable installer for 64-bit or Windows x86 executable installer for 32-bit. Step 2: Run the Installer Once you have chosen and downloaded an installer, simply run it by double-clicking on the downloaded file.
15
Installing Python
16
Installing Python
17
Python Documentation
18
IDE for Python IDE stands for Integrated Development Environment.
It is a GUI( Graphical User Interface) where programmers write their code and produce the final products. An IDE basically unifies all essential tools required for software development and testing, which in turn helps the programmer maximize his output. Some IDEs are generic, meaning they can support a number of languages. An IDE is also one of these projects created to bind together the tasks of: writing, debugging, testing and executing the code of the software.
19
IDE for Python Features of an IDE:
Code Editor: A code editor is provided to write and manipulate the source code Syntax Highlighting: This feature is provided to mark the syntax of the base language in different colors and fonts. Auto-completion Code: Designed to minimize time consumption. Debugger: A debugger is a tool that is required to test and debug the source code. Compiler: A compiler is a component that translates the source code from one language to another. Language Support: IDEs can either be language specific or may have support to multiple languages.
20
IDE for Python Top IDEs for Python PyCharm EdurekaSpyder PyDev Rodeo
Sublime Text Wing Eric Python Atom Thonny IDLE
21
IDE for Python Choose the best IDE for Python
Always keep the following points in mind while choosing the best IDE for Python: Level of expertise (beginner, professional) of the programmer The type of industry or sector where Python is being used Ability to buy commercial versions or stick to the free ones Kind of software being developed Need to integrate with other languages
22
IDLE for Python IDLE for Python
This IDE is considered to be extremely suitable for the education industry due to its simplicity. IDLE is written completely in Python and it comes as a default implementation along with Python. Its name is presumed to be in honor of Eric Idle who is one of the founding members of Monty Python. IDLE also provides some remarkable features such as: Availability of python shell with syntax highlighting A multi-window text editor Program animation or stepping Breakpoints are available to ease debugging Call stack is clearly visible
23
Python Programming Interactive mode Script mode
In Python, there are two options/modes for running code: Interactive mode Interactive mode is a command line shell which gives immediate output for each statement, while running previously fed statements in active memory. The >>> is Python's way of telling you that you are in interactive mode. As new lines are fed into the interpreter, the fed program is evaluated both in part and in whole. Script mode The normal mode is the mode where the scripted and finished .py files are run in the Python interpreter. In script mode, however, Python doesn't automatically display results. In order to see output from a Python script, we'll introduce the print statement.
24
Token 1.Keywords 2.Identifiers 3.Literals 4.Operators
Smallest individual unit in a program is known as token. 1.Keywords 2.Identifiers 3.Literals 4.Operators 5.Punctuators / Delimiters
25
Keywords Reserve word of the compiler/interpreter which can’t be used as identifier.
26
Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow special characters Identifier must not be a keyword of Python. Python is a case sensitive programming language. Thus, Rollnumber and rollnumber are two different identifiers in Python. Some valid identifiers :Mybook, file123, z2td, date_2, _no Some invalid identifier : 2rno,break,my.book,data-cs
27
Literals Literals in Python can be defined as number, text, or other data that represent values to be stored in variables. Example of String Literals in Python name = ‘Johni’ , fname=“johny” Example of Integer Literals in Python(numeric literal) age = 22 Example of Float Literals in Python(numeric literal) height = 6.2 Example of Special Literals in Python name = None
28
Operators Operators can be defined as symbols that are used to perform operations on operands. Types of Operators Arithmetic Operators. Relational Operators. Assignment Operators. Logical Operators. Bitwise Operators Membership Operators Identity Operators
29
Arithmetic Operators Arithmetic Operators are used to perform arithmetic operations like addition, multiplication, division etc.
30
Relational Operators Relational Operators are used to compare the values.
31
Assignment Operators Used to assign values to the variables.
32
Logical Operators Logical Operators are used to perform logical operations on the given two variables or values. Example: a=30 b=20 if(a==30andb==20): print('hello') Output :- hello
33
Membership Operators The membership operators in Python are used to validate whether a value is found within a sequence such as such as strings, lists, or tuples. Example: a = 22 list = [22,99,27,31] Ans1= a in list Ans2= a not in list print(Ans1) print(Ans2) Output :- True False
34
Identity Operators Identity operators in Python compare the memory locations of two objects. Example: a = 34 b=34 if (a is b): print('both a and b has same identity') else: print('a and b has different identity') Output :- both a and b has same identity
35
Operators Many logical expressions use relational operators:
Logical expressions can be combined with logical operators: Operator Meaning Example Result == equals 1 + 1 == 2 True != does not equal 3.2 != 2.5 < less than 10 < 5 False > greater than 10 > 5 <= less than or equal to 126 <= 100 >= greater than or equal to 5.0 >= 5.0 Operator Example Result and 9 != 6 and 2 < 3 True or 2 == 3 or -1 < 5 not not 7 > 0 False
36
Punctuators / Delimiters
Used to implement the grammatical and structure of a Syntax. Following are the python punctuators.
37
Our First Python Program
Python does not have a main method like Java The program's main code is just written directly in the file Python statements do not end with semicolons hello.py 1 print("Hello, world!")
38
Python program Comments Function Expression Statement
A python program contain the following components Comments Function Expression Statement Block & indentation
39
Python Comment Comments: which is readable for programmer but ignored by python interpreter Single line comment: Which begins with # sign. Syntax: # comment text (one line) Example # This is a comment b) Multi line comment (docstring): either write multiple line beginning with # sign or use triple quoted multiple line. E.g. ‘’’this is my first python multiline comment ‘’’
40
Math commands Python has useful commands for performing calculations.
To use many of these commands, you must write the following at the top of your Python program: from math import *
41
Expressions expression: A data value or set of operations to compute a value. Examples: * 3 42 Arithmetic operators we will use: + - * / addition, subtraction/negation, multiplication, division % modulus, a.k.a. remainder ** exponentiation precedence: Order in which operations are computed. * / % ** have a higher precedence than * 4 is 13 Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16
42
Integer division When we divide integers with / , the quotient is also an integer. 4 ) ) 1425 54 21 More examples: 35 / 5 is 7 84 / 10 is 8 156 / 100 is 1 The % operator computes the remainder from a division of integers. 4 ) ) 218 15 3 Dividing by 0 crashes the program.
43
Real numbers Python can also manipulate real numbers.
Examples: e17 The operators + - * / % ** ( ) all work for real numbers. The / produces an exact answer: 15.0 / 2.0 is 7.5 The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + - When integers and reals are mixed, the result is a real number. Example: 1 / 2.0 is 0.5 The conversion occurs on a per-operator basis. 7 / 3 * / 2 2 * / 2 / 2 3.4
44
Type conversion The process of converting the value of one data type (integer, string, float, etc.) to another data type is called type conversion. Python has two types of type conversion. Implicit Type Conversion Explicit Type Conversion
45
Type conversion Implicit Type Conversion:
InImplicittypeconversion,Pythonautomaticallyconvertsonedatatypetoanotherdatatype.Thisprocessdoesn'tneedanyuserinvolvement. Example: num_int=12 num_flo=10.23 num_new=num_int+num_flo print("datatypeofnum_int:",type(num_int)) print("datatypeofnum_flo:",type(num_flo)) print("Valueofnum_new:",num_new) print("datatypeofnum_new:",type(num_new)) OUTPUT ('datatypeof num_int:', <type 'int'>) ('datatypeof num_flo:', <type 'float'>) ('Value of num_new:', 22.23) ('datatypeof num_new:', <type 'float'>)
46
Type conversion Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int(),float(),str() etc. Example: print("Data type of the sum:",type(num_sum)) num_int= 12 num_str= "45" OUTPUT print("Data type of num_int:",type(num_int)) ('Data type of num_int:', <type 'int'>) print("Data type of num_strbefore Type Casting:",type(num_str)) ('Data type of num_strbefore Type Casting:', <type 'str'>) num_str= int(num_str) ('Data type of num_strafter Type Casting:', <type 'int'>) print("Data type of num_strafter Type Casting:",type(num_str)) ('Sum of num_intand num_str:', 57) num_sum= num_int+ num_str ('Data type of the sum:', <type 'int'>) print("Sum of num_intand num_str:",num_sum)
47
Variables variable: A named piece of memory that can store a value.
Usage: Compute an expression's result, store that result into a variable, and use that variable later in the program. assignment statement: Stores a value into a variable. Syntax: name = value Examples: x = 5 gpa = 3.14 A variable that has been given a value can be used in expressions. x + 4 is 9
48
Statement A statement in Python: is a logical instruction which Python interpreter can read and execute. In Python, it could be an: Assignment statement Multi-line statement
49
Assignment Statement Assignment statement
The assignment statement is fundamental to Python. It defines the way an expression creates objects and preserve them. a simple assignment, we create new variables, assign and change values. Syntax: variable = expression Example Var=10
50
Multi-line statement Multi-line statement
Python statement ends with a newline character. However, we can extend it over to multiple lines using the line continuation character (\). Python gives us two ways to enable multi-line statements in a program. Explicit line continuation Implicit line continuation
51
Multi-line statement a = 1 + 2 + 3 + \ 4 + 5 + 6 + \ 7 + 8 + 9
Explicit line continuation When you right away use the line continuation character (\) to split a statement into multiple lines. Example: a = \ \
52
Multi-line statement Implicit line continuation Example:
Implicit line continuation is when you split a statement using either of parentheses ( ), brackets [ ] and braces { }. Example: colors = ['red', 'blue', 'green']
53
Input Statement input : Reads a number from user input.
You can assign (store) the result of input into a variable. Example: age = input("How old are you? ") print "Your age is", age print "You have", 65 - age, "years until retirement" Output: How old are you? 53 Your age is 53 You have 12 years until retirement
54
print Statement print : Produces text output on the console. Syntax:
print ("Message“) print (Expression) Prints the given text message or expression value on the console, and moves the cursor down to the next line. print (Item1, Item2, ..., ItemN) Prints several messages and/or expressions on the same line. Examples: print ("Hello, world!“) age = 45 print ("You have", 65 - age, "years until retirement“) Output: Hello, world! You have 20 years until retirement
55
The print Statement print("text") print() (a blank line)
Escape sequences such as \" are the same as in Java Strings can also start/end with ' swallows.py 1 2 3 4 print("Hello, world!") print() print("Suppose two swallows \"carry\" it together.") print('African or "European" swallows?')
56
Python Indentation Python uses indentation to indicate blocks, instead of {} Makes the code simpler and more readable In Java, indenting is optional. In Python, you must indent. A code block which represents the body of a function or a loop begins with the indentation. Typically, we indent each line by four spaces (or by the same amount) in a block of code. hello3.py 1 2 3 4 5 6 7 8 # Prints a helpful message. def hello(): print("Hello, world!") print("How are you?") # main (calls hello twice) hello()
57
Data Types Prof. K. Adisesha
58
Data Types Data Type specifies which type of value a variable can store. type() function is used to determine a variable 's type in Python. Various data types supported by Python programs are:
59
Data Types Data Types In Python Booleans Numbers Strings Bytes Lists
Tuples Sets Dictionaries
60
Data Types Python Data objects are broadly categorized into
Immutable Type: Those that can never change values in place Number String Boolean Tuple Mutable Types: Those whose values can be changed in place. List Set Dictionary
61
Booleans A Boolean is such a data type that almost every programming language. Boolean In Python Boolean in Python can have two values – True or False. Example str="compsc" b=str.isupper() #test if string contain uppercase print(b) Output False
62
Numbers The numbers in Python are classified using the following keywords. Int, Float Complex. Python has a built-in function type() to determine the data type of a variable or the value. Another built-in function isinstance() is there for testing the type of an object. In Python, we can add a “j” or “J” after a number to make it imaginary or complex.
63
Numbers Number In Python It is used to store numeric values
Python has three numeric types: Integers Example: a = 10 The number ( a ) is of type <class 'int'> 2. Floating point numbers Example: b = The number ( b ) is of type <class 'float'> 3. Complex numbers Example: c=complex(101,23) Output :- (101+23j) The number (c) is of type <class 'complex'>
64
Strings String In Python
A sequence of one or more characters enclosed within either single quotes (‘ ')or double quotes (“ ”) is considered as String. Example: >>>str1='computer science' >>>str #print string Python also supports multi-line strings which require a triple quotation mark at the start and one at the end. Example >>> str2 = """A multiline string starts and ends with a triple quotation mark.""" >>> str2
65
Bytes Byte in Python The byte is an immutable type in Python.
It can store a sequence of bytes (each 8-bits) ranging from 0 to 255. Similar to an array, we can fetch the value of a single byte by using the index. But we can not modify the value. Differences between a byte and the string. Byte objects contain a sequence of bytes whereas the strings store sequence of characters. The bytes are machine-readable objects whereas the strings are just in human-readable form.
66
Lists List in Python It is a heterogeneous collection of items of varied data types. Lists in Python can be declared by placing elements inside square brackets separated by commas. It is very flexible and does not have a fixed size. Index in a list begins with zero in Python. List objects are mutable. Example: List1 = ['Learn', 'Python', '2']
67
Tuples Tuples in Python
A tuple is a heterogeneous collection of Python objects separated by commas. Define a tuple using enclosing parentheses () having its elements separated by commas inside. Tuples objects are immutable. Example: Tup1 = ('Learn', 'Python', '2‘)
68
Tuple & List Difference between Tuple & List
The tuple and a list are some what similar as they share the following traits. Both objects are an ordered sequence. They enable indexing and repetition. Nesting is allowed. They can store values of different types. Example of List: list=[6,9] list[0]=55 print(list[0]) print(list[1]) OUTPUT 55, 9 Example of tuple tup=(66,99) Tup[0]=3 # error message will be displayed print(tup[0]) print(tup[1]) OUTPUT 66, 9
69
Need for Tuple Why need a Tuple as one of the Python data types?
Here are a couple of thoughts in support of tuples. Python uses tuples to return multiple values from a function. Tuples are more lightweight than lists. It works as a single container to stuff multiple things. We can use them as a key in a dictionary.
70
Sets Set In Python Amongst all the Python data types, the set is one which supports mathematical operations like union, intersection, symmetric difference etc. A set is an unordered collection of unique and immutable objects. Its definition starts with enclosing braces { } having its items separated by commas inside. To create a set, call the built-in set() function with a sequence or any inerrable object. Example: set1={11,22,33,22} print(set1) Output {33, 11, 22}
71
Dictionaries Dictionary In Python
A dictionary in Python is an unordered collection of key-value pairs. It’s a built-in mapping type in Python where keys map to values. Python syntax for creating dictionaries use braces {} where each item appears as a pair of keys and values. Example: dict= {'Subject': 'comp sc', 'class': '11'} print(dict) Output {'Subject': 'comp sc', 'class': '11'}
72
Repetition (loops) and Selection (if/else)
Prof. K. Adisesha
73
if Statement if statement: Executes a group of statements only if a certain condition is true. Otherwise, the statements are skipped. Syntax: if condition: statements Example: gpa = 3.4 if gpa > 2.0: print "Your application is accepted."
74
if/else if/else statement: Executes one block of statements if a certain condition is True, and a second block of statements if it is False. Syntax: if condition: statements else: Example: gpa = 1.4 if gpa > 2.0: print "Welcome to University!" print "Your application is denied." Multiple conditions can be chained with elif ("else if"): elif condition:
75
Short Hand If ... Else Output: equ
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") Output: B We have multiple else statements on the same line: Example: One line if else statement, with 3 conditions: a = 330 Print("A") if a > b else print(“equ") if a == b else print("B") Output: equ
76
while Syntax: Example:
while loop: Executes a group of statements as long as a condition is True. good for indefinite loops (repeat an unknown number of times) Syntax: while condition: statements Example: number = 1 while number < 200: print number, number = number * 2 Output:
77
The for loop for loop: A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Repeats a set of statements over a group of values. Syntax: for variableName in groupOfValues: statements We indent the statements to be repeated with tabs or spaces. variableName gives a name to each value, so you can refer to it in the statements. groupOfValues can be a range of integers, specified with the range function. Example: for x in range(1, 6): print x, "squared is", x * x Output: 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16 5 squared is 25
78
range The range function specifies a range of integers: 3 2 1
range(start, stop) - the integers between start (inclusive) and stop (exclusive) It can also accept a third value specifying the change between values. range(start, stop, step) - the integers between start (inclusive) and stop (exclusive) by step Example: for x in range(5, 0, -1): print(x) print "Blastoff!" Output: 5 4 3 2 1 Blastoff!
79
Cumulative loops Some loops incrementally compute a value that is initialized outside the loop. This is sometimes called a cumulative sum. sum = 0 for i in range(1, 11): sum = sum + (i * i) print "sum of first 10 squares is", sum Output: sum of first 10 squares is 385
80
The break Statement With the break statement we can stop the loop before it has looped through all the items Example: Exit loop when x is “banana” fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break Output: apple banana Example: Do not print banana fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x) Output: apple
81
continue Statement With the continue statement we can stop the current iteration of the loop, and continue with the next Example: Do not print banana fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) Output: apple cherry
82
Thank you Prof. K. Adisesha
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.