Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

UNIT I - Introduction and Syntax of Python Program

Python is a dynamic, high-level and interpreted programming language that was created by Guido van Rossum in 1990. It supports object-oriented programming and is easy to learn due to its simple syntax and readability. Python code is executed line by line by the Python interpreter. Key building blocks of Python include identifiers, keywords, comments, indentation, variables and data types. Numbers, strings, lists, tuples, dictionaries and sets are the main data types in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

UNIT I - Introduction and Syntax of Python Program

Python is a dynamic, high-level and interpreted programming language that was created by Guido van Rossum in 1990. It supports object-oriented programming and is easy to learn due to its simple syntax and readability. Python code is executed line by line by the Python interpreter. Key building blocks of Python include identifiers, keywords, comments, indentation, variables and data types. Numbers, strings, lists, tuples, dictionaries and sets are the main data types in Python.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

UNIT 1

Introduction and Syntax of Python Program

08 Marks
INTRODUCTION
? Python is a general purpose, dynamic, high-level, and
interpreted programming language.
? It supports Object Oriented programming approach to
develop applications.
? It is simple and easy to learn and provides lots of high-level
data structures.
PYTHON HISTORY
? Python was invented by Guido van Rossum at National
Institute of Research for Mathematics and Computer
science in Netherlands in 1990.
? Guido van Rossum was a fan of the popular BBC comedy
show of that time, "Monty Python's Flying Circus". So
he decided to pick the name Python for his newly created
programming language.
PYTHON FEATURES

? Easy to Learn and Use:


⚫ Python is easy to learn as compared to other programming
languages.
⚫ Its syntax is straightforward and much the same as the English
language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block.
? Interpreted Language:
⚫ Python is an interpreted language; it means the Python program is
executed one line at a time.
⚫ The advantage of being interpreted language, it makes debugging
easy and portable.
? Interactive Language :
⚫ You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
PYTHON FEATURES

? Object-Oriented Language:
⚫ Python supports object-oriented language and concepts of classes
and objects come into existence.
⚫ It supports inheritance, polymorphism, and encapsulation, etc.
? Free and Open Source:
⚫ Python is freely available for everyone. It is freely available on its
official website www.python.org
? Platform-Independent:
⚫ Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a
portable language.
APPLICATIONS OF PYTHON :
? GUI based desktop applications
? Graphic design, image processing applications, Games,
and Scientific/ computational Applications
? Web frameworks and applications
? Enterprise and Business applications
? Operating Systems
? Education
? Database Access
? Language Development
? Prototyping
? Software Development
PYTHON BUILDING BLOCKS
? Identifier :Variable name is known as identifier. An identifier is a
name given to entities like class, functions, variables, etc. It helps
to differentiate one entity from another.
? The rules to name an identifier are given below.
✔ The first character of the variable must be an alphabet or
underscore ( _ ).
✔ All the characters except the first character may be an alphabet of
lower-case(a-z), upper-case (A-Z), underscore or digit (0-9).
✔ Identifier name must not contain any white-space, or special
character (!, @, #, %, ^, &, *).
✔ Identifier name must not be similar to any keyword defined in the
language.
✔ Identifier names are case sensitive for example my name, and
MyName is not the same.
✔ Examples of valid identifiers : a123, _n, n_9, etc. o Examples of
invalid identifiers: 1a, n%4, n 9, etc.
PYTHON BUILDING BLOCKS
? Keywords:
⚫ Python Keywords are special reserved words that convey a
special meaning to the compiler/interpreter. Each keyword has a
special meaning and a specific operation. These keywords can't
be used as a variable.
PYTHON BUILDING BLOCKS
? Python Comments:
⚫ Comments are generally used to explain the code.
⚫ Single-line Python Comment: To apply the comment in the code
we use the hash(#) at the beginning of the statement or code.
Ex:
# This is the print statement
print("Hello Python")
⚫ Multiline Python Comment: We must use the hash(#) at the
beginning of every line of code to apply the multiline Python
comment.
⚫ Multiline comments can be declared using two ways. You can
specify these comments using ''' (Triple single quotes) or """
(Triple double quotes). The quotes are mentioned at the beginning
and at the end of the comments.
? Ex: """This is also a
perfect example of multi-line comments"""
PYTHON BUILDING BLOCKS
? Indentation :
⚫ Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted
by line indentation, which is compulsory.
⚫ The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
⚫ For example −
if True:
print "True"
else:
print "False"
⚫ Thus, in Python all the continuous lines indented with same
number of spaces would form a block.
⚫ Indentation can be ignored in line continuation. But it's a good
idea to always indent. It makes the code more readable.
PYTHON BUILDING BLOCKS
? Variables:
⚫ Variables are used to store data, they take memory space based on
the type of value we assigning to them. Creating variables in Python
is simple, you just have write the variable name on the left side of =
and the value on the right side.
⚫ Example
num = 100
str = "BeginnersBook“
print(num)
print(str)

⚫ We can assign multiple variables in a single statement like this in


Python.
x = y = z = 99
print(x)
print(y)
print(z)
PYTHON BUILDING BLOCKS
? Another example of multiple assignments
a, b, c = 5, 6, 7
print(a)
print(b)
print(c)

❑Plus and concatenation operation on the variables


x = 10
y = 20
print(x + y)

----------------------------------------------------------------------------------------
p = "Hello"
q = "World"
print(p + " " + q)
PYTHON ENVIRONMENT SETUP-
INSTALLATION AND WORKING OF IDE
? To install Python on your operating system, Visit the
link https://www.python.org/downloads/ to download the
latest release of Python
? Step - 1: Select the Python's version to download.
⚫ Click on the download button.
? Step - 2: Click on the Install Now
⚫ Double-click the executable file, which is downloaded; it will
open new window. Select Customize installation and proceed.
⚫ Click on the Add Path check box, it will set the Python path
automatically.
🞆 Step - 3 Installation in Process
? Step- 4 After Successful Installation Click on close Button
⚫ We are ready to work with the Python.
RUNNING SIMPLE PYTHON SCRIPTS TO
DISPLAY ‘WELCOME’ MESSAGE
? Python provides us the two ways to run a program:
⚫ Using Interactive interpreter prompt mode
⚫ Using a script mode
USING INTERACTIVE INTERPRETER PROMPT
? In the interactive mode as we enter a command and press
enter, the very next step we get the output.
? To run python in command prompt type “python”. Then
simply type the Python statement on >>> prompt. As we type
and press enter we can see the output in the very next line.

# Python program to display "Hello GFG"


>>>print("Hello GFG")
? Output: Hello GFG

? The interpreter prompt is best to run the single-line statements


of the code. However, we cannot write the code every-time on
the terminal. It is not suitable to write multiple lines of code.
Script Mode
? In the script mode, a python program can be written in a file.
This file can then be saved and executed using the command
prompt.
? How to run python code in script mode?

In order to run a code in script mode follow the following


steps.
Step 1: Make a file using a text editor. You can use any text
editor of your choice(Here I use notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory
to the one where your file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
SCRIPT MODE EXAMPLE :
? In order to execute “Hello gfg” using script mode we
first make a file and save it.

? Now we use the command prompt to execute this file.


DISPLAY MESSAGE ON SCREEN USING PYTHON
SCRIPT ON IDE.
EXECUTION OF PYTHON CODE BY
INTERPRETER
EXECUTION OF PYTHON CODE BY
INTERPRETER
? Python source code goes through compiler which compiles
the source code into bytecode.
? As soon as source code gets converted to bytecode ,it is fed
into Python Virtual Machine(PVM).
? PVM is run time engine of Python and is the component that
truly runs the script.
PYTHON DATA TYPES
? A data type defines the type of data,
for example 123 is an integer data while “hello” is a
String type of data.
? The data types in Python are divided in two categories:
1.Immutable data types – Values cannot be changed.
2. Mutable data types – Values can be changed
? Immutable data types in Python are:
⚫ 1. Numbers 2. String 3. Tuple
? Mutable data types in Python are:
⚫ 1. List 2. Dictionaries 3. Sets
DECLARATION AND USE OF DATATYPE
? Numbers:
⚫ Numbers are fairly straightforward.
⚫ Python’s core objects set includes the usual suspects: integers
(numbers without a fractional part),
⚫ Floating point numbers (roughly, numbers with a decimal point in
them),
⚫ and more exotic numeric types (complex numbers with imaginary
parts, fixed precision decimals, rational fractions with numerator
and denominator, and full-featured sets).
NUMBERS:
? Numbers in Python support the normal mathematical
operations.
? For instance, the plus sign (+) performs addition, a star (*) is
used for multiplication, and two stars (**) are used for
exponentiation.
>>> 123 + 222 # Integer addition 345
>>> 1.5 * 4 # Floating-point multiplication 6.0 >>> 2
** 100 # 2 to the power 100
1267650600228229401496703205376
? Python 3.0’s integer type automatically provides extra
precision for large numbers like this when needed
NUMBERS:
? Examples:
>>> 3.1415 * 2 # repr: as code 6.2830000000000004
>>> print(3.1415 * 2) # str: user-friendly 6.283
Two ways to print every object: with full precision (as in the
first result shown here), and in a user-friendly form (as in the
second).
o Besides expressions, there are a handful of useful numeric

modules that ship with Python—modules are just packages of


additional tools that we import to use:
>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871
STRINGS :
• To create string literals, enclose them in single, double, or
triple quotes as follows:
a = "Hello World"
b = 'Python is groovy'
c = """Computer says 'No'"""
• The same type of quote used to start a string must be used to
terminate it.
Triple quoted strings capture all the text that appears prior to
the terminating triple quote, as opposed to single- and double-
quoted strings, which must be specified on one logical line.
STRINGS :
? Triple-quoted strings are useful when the contents of a string
literal span multiplelines of text such as the following:
print '''Content-type: text/html
<h1> Hello World </h1>
Click <a href="http://www.python.org">here</a>. '''

Strings are stored as sequences of characters indexed by integers, starting at


zero.
❑ To extract a single character, use the indexing operator s[i]
like this:
a = "Hello World“
b = a[4] # b = 'o'
STRINGS :

? To extract a substring, use the slicing operator s[i:j].


? This extracts all characters from s whose index k is in the
range i <= k < j.
? If either index is omitted, the beginning or end of the string is
assumed, respectively:
c = a[:5] # c = "Hello"
d = a[6:] # d = "World”
e = a[3:8] # e = "loWo"
STRINGS :
? Strings are concatenated with the plus (+) operator:
g = a + " This is a test"
• Python never implicitly interprets the contents of a string as
numerical data
For example, + always concatenates strings:
x = "37“
y = "42"
z=x+y # z = "3742" (String Concatenation)
STRINGS :
? To perform mathematical calculations, strings first have to be
converted into a numeric value using a function such as int()
or float().
? For example:
⚫ z = int(x) + int(y) # z = 79 (Integer +)
⚫ Non-string values can be converted into a string representation by
using the str(), repr(), or format() function.
⚫ Here’s an example:
s = "The value of x is " + str(x)
s = "The value of x is " + repr(x)
s = "The value of x is " + format(x,"4d")
• Although str() and repr() both create strings, their output is usually slightly
different
LISTS:
? Lists are sequences of arbitrary objects. You create a list by
enclosing values in square brackets, as follows: names =
[ "Dave", "Mark", "Ann", "Phil" ]
? Lists are indexed by integers, starting with zero. Use the
indexing operator to access and modify individual items of
the list:
a = names[2] # Returns the third item of the list, "Ann"
names[0] = "Jeff" # Changes the first item to "Jeff"
To append new items to the end of a list, use the append() method
and extend() method to add several items:
names.append("Paula")
To insert an item into the middle of a list, use the insert() method:
names.insert(2, "Thomas")
LISTS:
? You can extract or reassign a portion of a list by using the
slicing operator:
b = names[0:2] # Returns [ "Jeff", "Mark" ]
c = names[2:] # Returns [ "Thomas", "Ann", "Phil",
"Paula" ]
names[1] = 'Jeff' # Replace the 2nd item in names with
'Jeff'
names[0:2] = ['Dave','Mark','Jeff'] # Replace the first two
items of the list with the list on the right.
? Use the plus (+) operator to concatenate lists:
a = [1,2,3] + [4,5] # Result is [1,2,3,4,5]
? An empty list is created in one of two ways:
names = [] # An empty list
names = list() # An empty list
LISTS:
? Lists can contain any kind of Python object, including other
lists, as in the following Example:

a = [1,"Dave",3.14, ["Mark", 7, 9, [100,101]], 10]


? Items contained in nested lists are accessed by applying
more than one indexing operation, as follows:
a[1] # Returns "Dave"
a[3][2] # Returns 9
a[3][3][1] # Returns 101
DIFFERENT LIST METHODS -
? list(s)-> Converts s to a list.
? s.append(x) -> Appends a new element, x, to the end of s.
? s.extend(t) -> Appends a new list, t, to the end of s.
? s.count(x) -> Counts occurrences of x in s.
? s.insert(i,x) -> Inserts x at index i.
? s.pop([i]) -> Returns the element i and removes it from the
list. If i is omitted, the last element is returned.
? s.remove(x) -> Searches for x and removes it from s.
? s.reverse() -> Reverses items of s in place.
TUPLES:
? To create simple data structures, you can pack a collection
of values together into a single object using a tuple.
? You create a tuple by enclosing a group of values in
parentheses like this:
stock = (‘XYZ', 100, 490.10)
address = ('www.python.org', 80)
person = (first_name, last_name, phone)
o Python often recognizes that a tuple is intended even if the
parentheses are missing:
stock = ‘XYZ', 100, 490.10
address = 'www.python.org',80
person = first_name, last_name, phone
TUPLES:
? For completeness, 0- and 1-element tuples can be defined,
but have special syntax:
a = () # 0-tuple (empty tuple)
b = (item,) # 1-tuple (note the trailing comma)
c = item, # 1-tuple (note the trailing comma)
? The values in a tuple can be extracted by numerical index
just like a list.
TUPLES:
? Although tuples support most of the same operations as lists
(such as indexing, slicing, and concatenation), the contents of
a tuple cannot be modified after creation (that is, you cannot
replace, delete, or append new elements to an existing tuple).
? This reflects the fact that a tuple is best viewed as a single
object consisting of several parts, not as a collection of distinct
objects to which you might insert or remove items.
TUPLES:
? Because there is so much overlap between tuples and lists,
some programmers are inclined to ignore tuples altogether and
simply use lists because they seem to be more flexible.
? Although this works, it wastes memory if your program is
going to create a large number of small lists (that is, each
containing fewer than a dozen items).
? This is because lists slightly over allocate memory to optimize
the performance of operations that add new items.
? Because tuples are immutable, they use a more compact
representation where there is no extra space.
DICTIONARIES:
? A dictionary is an associative array or hash table that
contains objects indexed by keys.
? You create a dictionary by enclosing the values in curly
braces ({ }), like this:
stock = {
"name" : “KLPT",
"shares" : 100,
"price" : 490.10
}
• To access members of a dictionary, use the key-indexing
operator as follows:
name = stock["name"]
value = stock["shares"] * shares["price"]
DICTIONARIES:
? Inserting or modifying objects works like this: stock["shares"]
= 75
stock["date"] = "June 7, 2007”
? A dictionary is a useful way to define an object that consists
of named fields.
? However, dictionaries are also used as a container for
performing fast lookups on unordered data.
? For example, here’s a dictionary of stock prices:

prices = { “KLPT" : 490.10, "AAPL" : 123.50, "IBM" : 91.50,


"MSFT" : 52.13 }
DICTIONARIES:
? An empty dictionary is created in one of two ways:
prices = {} # An empty dict
prices = dict() # An empty dict
? Dictionary membership is tested with the in operator, as in the
following example:
if "SCOT" in prices:
p = prices["SCOT"]
else:
p = 0.0
? This particular sequence of steps can also be performed more
compactly as follows:
p = prices.get("SCOT",0.0)
DICTIONARIES:
? To obtain a list of dictionary keys, convert a dictionary to a
list:
syms = list(prices) # syms = ["AAPL", "MSFT", "IBM",
“KLPT"]
? Use the del statement to remove an element of a dictionary:
del prices["MSFT"]
? Dictionaries are probably the most finely tuned data type in
the Python interpreter.
SET
? A Python set is the collection of the unordered items. Each
element in the set must be unique, immutable, and the sets
remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
? Unordered means that the items in a set do not have a defined
order.
? Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.
? Set items are unchangeable, meaning that we cannot change
the items after the set has been created.
? Sets cannot have two items with the same value.
CREATING A SET

? The set can be created by enclosing the comma-separated


immutable items with the curly braces {}.
? Example:
Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Fr
iday", "Saturday", "Sunday"}
? Python also provides the set() method, which can be used to
create the set by the passed sequence.
? Example:
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"])
SET
? # Empty curly braces will create dictionary
set1 = {}
print(type(set1))

? # Empty set using set() function


set2 = set()
print(type(set2))

You might also like