0% found this document useful (0 votes)
2 views

Chapter-3

The document provides an introduction to Python programming, covering its basic concepts such as statements, functions, and the differences between Python 2.x and 3.x. It discusses elements of the Python language including identifiers, keywords, literals, and data types, as well as collection types like lists, tuples, and dictionaries. Additionally, it explains operations, type conversions, input/output statements, and string formatting in Python.

Uploaded by

cse klepolymlp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter-3

The document provides an introduction to Python programming, covering its basic concepts such as statements, functions, and the differences between Python 2.x and 3.x. It discusses elements of the Python language including identifiers, keywords, literals, and data types, as well as collection types like lists, tuples, and dictionaries. Additionally, it explains operations, type conversions, input/output statements, and string formatting in Python.

Uploaded by

cse klepolymlp
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Introduction to Python

What is Python?
• A Python program is a script, which is vaguely a short program that
can be executed in Python interactive script.
• A statement is a line of code or command or instruction for
computers to perform initialize a number, perform some
computations, and do some control flow.
• A Function is a collection of statements that perform an intended
action and returns a Value.
• There are two types of statements: Simple and Compound.
Simple Statement: Performs a single simple task. For Ex., Expressions
and Assignment Statements.
• Compound Statements: This is a group of statements that spans multiple
lines and that control the execution of other statements of that program.
• For example, if, while and function are examples of the compound
statement.
• Example: Illustration of swapping of variables in Interactive mode
>>> x = 10
>>> y = 20
>>> t = x
>>> x = y
>>> y = t
>>> x, y
(20, 10)
>>>
Differences Between Python 2.x and 3.x
No Python 2.x Python 3.x

1. Old version of Python. New and updated language

2. The syntax of the print statement is print The syntax of Python 3. x print is changed.
"hello" Print is a function and it should be
print("Hello").

3. Uses ASCII as default for string Uses UNICODE (UTF-8) to represent


representation. strings. So foreign languages and more
characters are supported.
4. Python 2.x is not forward compatible. Python 3.x is compatible compared with
Python 2.x.

5. The division is awkward in Python 2.x. The division of 7 by 2 results in 3.5; hence,
Division of 7/2 gives 3. calculations are more predictable.
Elements of Python Language
• The set of valid characters that a programming language can recognize is called the character set of the
language. Two types of character sets are
• Source Characters. ( Alphabets uppercase and lowercase, underscore, Special characters blank –(+,-
,*,/,^,~,%,!,&,|,(),{},[] ?’, ;, \), blank(“”))
• The Token is the smallest lexical unit in a program. The Types of tokens are listed below.

1. Identifiers
2. Keywords
3. Literals
4. Punctuations
Identifiers

• Identifiers- In Python, all variables, objects, and functions are given a


name. These names are called identifiers.
• Certain rules govern how a name can be given. The guidelines are
given below.
1) Every identifier must start with a letter or underscore ("_")
2) The letter or underscore can be followed by any sequence of letters,
digits, or underscores.
3) Identifier cannot have a space
4) Identifiers are space sensitive. So the names celsius, Celsius, and
CELSIUS are different
Keywords
• Python has many inbuilt functions like input(). So Python does not
allow a program to use these function names liberally.
Keywords in Python:

and as assert del for False break class finally is

return None continue def del else if in global not

local except in raise with or else import True Float


Literals
• Literal is one way of specifying data values. These will be the values
that never modify while the program is executing.
• Literals in Python are numbers, text, or other fixed data, unlike
variables whose values change during the action.
• Some of the literals are listed below:
1. String literals
2. Numerical literals
3. Boolean literals
Literals
• String Literals • Numerical Literals
>>> # string literals Example of handling constant as a variable
>>> # in single quote
>>> single_quote = ‘stringliterals’
>>> # in double quotes >>>
>>> double_quotes = "stringliterals" >>> PI = 3.14
>>> # multi-line string
>>> TEMPERATURE = 9.0
>>> multiline = ‘’’ string
... literals’’’
>>> print(single_quote)
stringliterals
>>> print(double_quotes)
stringliterals
>>> print(multiline)
string
literals
>>>
Python Block Structure
Illustration of Blocks in Python
x = 10 # Block 1 starts
if x% 2 == 0: # Block 1 continues
print("The number is even" ) # Block 2
else: # Block 1
print("The number is odd") # Block 2
print("Program Ends’) # Block 1 continues
Comments in Python
Block Comments illustration Inline comments illustration Multiple quotes illustration

>>> # This is a single-line comment >>> a = 10 # a is initialized to 10 >>> # Multiline Quote


>>> # This is a block comment >>> a = 10 # a is initialized to 10 >>> """
>>> # This is a block comment >>> b = 10 # b is initialized to 10 ... This is a multiline quote
>>> c = a + b # c = a + b ... using Triple quotes
>>> ... """
>>>
Variables and Assignment Statement
• In Python everything is an object, therefore a variable also is an
object. Thus, the rules for forming a variable are the same as the
identifiers.
Assignment Statement
• One of the most critical statements in Python is the assignment
statement. The syntax of the introductory assignment statement is
given as follows:

• An alternative form of an assignment statement is to assign/compute


several values simultaneously. The syntax of simultaneous is given as
follows:
Name Spaces
• Python interpreter uses a unique structure called namespace using
which it maintains a list of names and their associated values.
• Python updates the list when a new variable is created and it is
deleted in the namespace when the variable is deleted.
Python Objects

• In Python all are objects, variables, functions or even values.


An object is linked with three concepts-Identify, Zero or more names, and a set of attributes.
1. Identify the Object
When the object is assigned to a variable, some memory address is allocated to the object.
The Python function to get the memory address is called id() function.
Data Types in Python
• A data type indicates what values a variable can hold, and an operator indicates the kind of
operations performed on the values.
• Python supports numbers and floating numbers. Classification of data types as follows,
Collection data Types
• Two main kinds of collection types are sequence and another type
called mapping.
• A sequence in an ordered collection of values. These sequence types
are string, list and tuples.
1) A string is a sequence of characters
2) A list is a sequence of values
3) A tuple is a sequence of values like lists but a tuple is immutable
The string is an example of a sequence collection data type. It is a collection of characters delimited
by single, double, and triple quotes. It can include letters, numbers, punctuations, and many special/
unprintable characters.
Lists
A list is a set of items or elements. All these items are separated by commas and enclosed within
square brackets. In all aspects, lists are similar to arrays but can have non-homogenous content.
To create a list, one can just enclose the sequence of objects in square brackets.

Illustration of Slicing in Lists


Tuples
• A tuple is a collection of items or elements. A tuple is also a sort of list
but the main difference is that tuples are immutable compared to
mutable lists.
• The tuple items are enclosed in round brackets and separated by a
comma. The empty tuple is (). The tuple with a single element is
called a singleton.
• Some of the examples are,
Dictionary Sets/Frozen Sets
• A dictionary is an unordered collection of items in • A set is an unordered collection of zero or more
the form of keys and values A dictionary is called a elements with no duplicates. As in mathematics, a
mapping type. set is an unordered collection of items with no
duplicate items that use curly braces for sets- {}.
• A map type consists of a set of element pairs. The
first element of the pair is called a key, and the • The set is immutable and unique.
second element is called a value.
• To find the corresponding equivalent values, one
can search for a key or value.
Operations
• One of the other attributes of the objects is operations. Operations
are performed on operands. For example, in the expression, ‘a+b’, ‘a’
and ‘b’ are called operands, and ‘+’ is the operator. Operations
depend on the data type.
The classification of operators
Type Conversions
• There are certain limitations to the data types. For example, one cannot do 'Hello"+4, because one is a string
type and another is an integer. For example, input() returns a string, so one needs to convert that to an integer
to perform operators. This concept is called type conversion.
• There are two types of data conversion. They are
1) Implicit conversion (or Type Coercion)
2) Explicit conversion (or Type Casting)
Implicit conversion
Python implicitly converts a data type during compilation or runtime. Python automatically converts an integer
to a floating point to preserve the fractional part.
Explicit conversion
The explicit conversion of a value from one data type into another data type is called typecasting.
There are many built-in functions available for type conversion
Simple input/output Statements
• Reading Numbers from the Keyboard. – one can read the input from
the console using the input() function.
• The syntax of the statement is given as

• One can also accept a string using the input() function. The syntax is
given as
Illustration of Input Illustration of Type Error Illustration of input Illustration of eval
statement statement

>>> str = input("Enter >>> a = input("Enter >>> a = int(input("Enter >>> x = eval(input("Enter


String") Number ") Number ")) the number"))
Enter String Hello Enter Number 10 Enter Number 10 Enter the number10
>>> str >>> a = a + 10 >>> a = a + 10 >>> x = x + 10
‘Hello’ Traceback (most recent >>> print(a) >>> print(x)
call last): 20 20
File "<stdin>", line 1, in
<module>
TypeError: can only
concatenate str (not "int")
to str
>>>
Print() statement
The contents can be displayed on the screen using a print statement. A python print statement converts
all python objects into a string and writes it on in general i/o stream.

• Illustration of Print
Formatting using Print Statement
Many times a simple printing of values is not sufficient. Many projects may require fancy printing as per the requirements. It
is called formatting. All variables and constants need to be converted to string type for printing purposes.

• Built-in Methods
String Formatting
• String formatting is the second way of formatting; here, there will be a format string and arguments.
• The format of this string formatting is given as

• Formatting Illustration
Built-in functions

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy