0% found this document useful (0 votes)
5 views45 pages

Python Chap1 (1)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 45

Chapter :1

An Introduction to
Python
Simple

Easy to Learn

Free and Open Source

High-level Language

Portable

Dynamically Typed

Features Platform Independent


Procedure and Object Oriented

of Python Embeddable
Extensive Libraries

Interpreted

Extensible

Scripting Language

Database Connectivity

Scalable
Build Process of Python Application
Python is an object oriented programming language like Java.

Python is called an interpreted language.

Python uses code modules that are interchangeable instead of a single long list of instructions that was standard for functional
programming languages.
Python doesn’t convert its code into machine code, something that hardware can understand.

It actually converts it into something called byte code.

So within python, compilation happens, but it’s just not into a machine language.

It is into byte code and this byte code can’t be understood by CPU.

So we need actually an interpreter called the python virtual machine, The python virtual machine executes the byte codes.

So we need actually an interpreter called the python virtual machine

The python virtual machine executes the byte codes.


Python Applications
Python supports cross-platform operating systems which makes building applications with it
all the more convenient.

Web Development

Game Development

Machine Learning and Artificial Intelligence

Data Science and Data Visualization

Desktop GUI
Python Keywords/Reserve words and Identifiers
• In this topic we will learn about keywords (reserved words in Python) and
identifiers (names given to variables, functions, etc.).
• Python Keywords/Reserve words
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other
identifier. They are used to define the syntax and structure of the Python
language.
In Python, keywords are case sensitive.
There are 33 keywords in Python 3.7. This number can vary slightly over the
course of time.
All the keywords except True, False and None are in lowercase and they must
be written as they are.
List of Reserve Words / Key words

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


Python Identifiers
• An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from another.
• Rules for writing identifiers
• Identifiers can be a combination of letters in lowercase (a to
z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.
• Names like myClass, var_1 and print_this_to_screen, all are
valid example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is a valid name.
• Keywords cannot be used as identifiers
• We cannot use special symbols like !, @, #, $, % etc. in our
identifier
• An identifier can be of any length.
•The implementation of
•Python laid its foundation Python was started in the
in the late 1980s. December 1989 by Guido
History Van Rossum .

•In 1994, Python 1.0 was


•In February 1991, van
released with new features
Rossum published the code
like: lambda, map, filter, and
(labeled version 0.9.0).
reduce.

•On December 3, 2008,


•Python 2.0 added new Python 3.0 (also called
features like: list "Py3K") was released. It was
comprehensions, garbage designed to rectify
collection system. fundamental flaw of the
language.
Like mathematicians, programmers
frequently name values so that they can use
them later.

A name that refers to a value is called a


variable.

Variables :
In Python, variable names can use letters,
digits, and the underscore symbol (but they
can’t start with a digit).

Variables are called variables because their


values can vary as the program executes.
Variables
• A variable is a named location used to store data in the memory. It
is helpful to think of variables as a container that holds data that
can be changed later in the program
• You create a new variable by assigning it a value:
>>> degrees_celsius = 26.0
• This statement is called an assignment statement; we say that
degrees_celsius is assigned the value 26.0.
• We can use variables anywhere we can use values.
• Whenever Python sees a variable in an expression, it substitutes
the value to which the variable refers
• Assigning a value to a variable that already exists doesn’t create a
second variable. Instead, the existing variable is reused, which
means that the variable no longer refers to its old value.
Constants
• A constant is a type of variable whose value cannot be changed. It is helpful to
think of constants as containers that hold information which cannot be changed
later. You can think of constants as a bag to store some books which cannot be
replaced once placed inside the bag.
• Rules and Naming Convention for Variables and constants
 Constant and variable names should have a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For
example: snake_case , MACRO_CASE , camelCase CapWords
 Create a name that makes sense. For example, vowel makes more sense than v.
 If you want to create a variable name having two words, use underscore to
separate them. For example: my_name , current_salary
 Use capital letters possible to declare a constant. For example: PI , TEMP
 Never use special symbols like !, @, #, $, %, etc.
 Don't start a variable name with a digit.
Python Operators
• Python divides the operators
in the following groups:

Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators
Operator Name Example

+ Addition x+y

Arithmetic operators are - Subtraction x-y


used with numeric values
to perform common * Multiplication x*y
mathematical operations
/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
Operator Example Same As
= x=5 x=5
Assignment += x += 3 x=x+3
operators
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
Assignment operators are
%= x %= 3 x=x%3
used to assign values to
variables //= 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
Operato Name Exampl
Comparison r e
operators == Equal x == y

Comparison operators != Not equal x != y


are used to compare two
values > Greater than x>y

< Less than x<y

>= Greater than or x >= y


equal to

<= Less than or x <= y


equal to
Operator Description Example
Logical operators
and Returns True if x < 5 and x <
both 10
statements are
true
Logical operators are
used to combine or Returns True if x < 5 or x < 4
conditional statements one of the
statements is
true

not Reverse the not(x < 5 and


result, returns x < 10)
False if the
result is true
Operator Description Example
Identity operators
is Returns True if x is y
Identity operators are used both variables
are the same
to compare the objects, not object
if they are equal, but if they
are actually the same
object, with the same
memory location is not Returns True if x is not y
both variables
are not the same
object
Operator Description Example
Membership operators
in Returns True if a x in y
sequence with the
specified value is
present in the
Membership operators are object
used to test if a sequence is
presented in an object not in Returns True if a x not in y
sequence with the
specified value is
not present in the
object
Operator Name Description
Bitwise operators
& 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
Bitwise operators are used to
compare (binary) numbers
~ NOT Inverts all the bits

<< Zero fill Shift left by pushing zeros in from the


left right and let the leftmost bits fall off
shift

>> Signed Shift right by pushing copies of the


right leftmost bit in from the left, and let the
shift rightmost bits fall off
Python Data Types

Data types are the classification or categorization of data items.

It represents the kind of value that tells what operations can be


performed on a particular data.

Since everything is an object in Python programming, data types are


actually classes and variables are instance (object) of these classes.
• Every variable in python holds an instance of an
object.
• There are two types of objects in python
Mutable i.e. Mutable and Immutable objects.
And • Whenever an object is instantiated, it is assigned
a unique object id.
Immutable • The type of the object is defined at the runtime
Objects and it can’t be changed afterwards.

in Python • However, it’s state can be changed if it is a


mutable object.
• To summarise the difference, mutable objects can
change their state or contents and immutable
objects can’t change their state or content.
Understanding Muttable And Immutable

• To get started, it’s important to understand that every object in Python has
an ID (or identity), a type, and a value, as shown in the following snippet:

Click to add text


• Once created, the ID of an object never changes.
• It is a unique identifier for it, and it is used behind
the scenes by Python to retrieve the object when
we want to use it.
• The type also never changes. The type tells what
Mutable..... operations are supported by the object and the
possible values that can be assigned to it.
• The value can either change or not.
• If it can, the object is said to be mutable, while
when it cannot, the object is said to be
immutable.
• Let’s take a look at an example:

Immutable...
Immutable...

• Has the value of age changed? Well, no. 42 is an integer number, of the
type int, which is immutable. So, what happened is really that on the
first line, age is a name that is set to point to an int object, whose
value is 42.
• When we type age = 43, what happens is that another object is
created, of the type int and value 43 (also, the id will be different),
and the name age is set to point to it. So, we didn’t change
that 42 to 43. We actually just pointed age to a different location.
• As you can see from printing id(age) before and after the second
object named age was created, they are different.
• Mutable Data Types
• Mutable sequences can be changed after
creation. Some of Python’s mutable data
Categorization types are: lists, byte arrays, sets,
Mutable And and dictionaries.
Immutable Data • Immutable Data Types
Types • Immutable data types differ from their
mutable counterparts in that they can not be
changed after creation. Some immutable
types include numeric data
types, strings, bytes, frozen sets, and tuples.
Standard Numeric
or built-in Sequence Type
Boolean
data type Set
of Python Dictionary
• In Python, numeric data type represent the data which has
numeric value. Numeric value can be integer, floating number
or even complex numbers.
• These values are defined as int, float and complex class
in Python.
• Integers – This value is represented by int class. It contains
positive or negative whole numbers (without fraction or
decimal). In Python there is no limit to how long an integer
value can be.
Numeric • Float – This value is represented by float class. It is a real
number with floating point representation. It is specified by a
decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify
scientific notation.
• Complex Numbers – Complex number is represented by
complex class. It is specified as (real part) + (imaginary part)j.
For example – 2+3j
 In Python, Strings are arrays of bytes representing Unicode
characters.
 A string is a collection of one or more characters put in a
single quote, double-quote or triple quote.
 In python there is no character data type, a character is a
string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or
String double quotes or even triple quotes.
Accessing elements of String
In Python, individual characters of a String can be accessed
by using the method of Indexing. Indexing allows negative
address references to access characters from the back of the
String, e.g. -1 refers to the last character, -2 refers to the
second last character and so on.
• Lists are just like the arrays, declared in other languages
which is a ordered collection of data. It is very flexible as
the items in a list do not need to be of the same type.

 Creating List
Lists in Python can be created by just placing the sequence
inside the square brackets[].
Accessing elements of List
List In order to access the list items refer to the index number.
Use the index operator [ ] to access an item in a list. In
Python, negative sequence indexes represent positions from
the end of the array. Instead of having to compute the offset
as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to
the last item, -2 refers to the second-last item, etc.
• Just like list, tuple is also an ordered collection of Python
objects. The only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it
is created. It is represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses
for grouping of the data sequence. Tuples can contain any
Tuple number of elements and of any datatype (like strings,
integers, list, etc.).
Accessing elements of Tuple
In order to access the tuple items refer to the index number.
Use the index operator [ ] to access an item in a tuple. The
index must be an integer. Nested tuples are accessed using
nested indexing.
• Data type with one of the two built-in values,
True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False
are falsy (false).
• But non-Boolean objects can be evaluated in
Boolean context as well and determined to be
true or false. It is denoted by the class bool.
Boolean • Note – True and False with capital ‘T’ and ‘F’ are
valid booleans otherwise python will throw an
error.
• In Python, Set is an unordered collection of data type that is
iterable, mutable and has no duplicate elements. The order of
elements in a set is undefined though it may consist of
various elements.
Creating Sets
• Sets can be created by using the built-in set() function with an
iterable object or a sequence by placing the sequence inside
curly braces, separated by ‘comma’. Type of elements in a set
need not be the same, various mixed-up data type values can
Set also be passed to the set.
Accessing elements of Sets
• Set items cannot be accessed by referring to an index, since
sets are unordered the items has no index. But you can loop
through the set items using a for loop, or ask if a specified
value is present in a set, by using the in keyword.
• Dictionary in Python is an unordered collection of data
values, used to store data values like a map, which unlike
other Data Types that hold only single value as an
element,
• Dictionary holds key:value pair. Key-value is provided in
the dictionary to make it more optimized. Each key-value
pair in a Dictionary is separated by a colon :, whereas each
key is separated by a ‘comma’.
Dictionary
Creating Dictionary
• In Python, a Dictionary can be created by placing
a sequence of elements within curly {} braces, separated
by ‘comma’. Values in a dictionary can be of any
datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable. Dictionary can also be
created by the built-in function dict(). An empty dictionary
can be created by just placing it to curly braces{}.
• Note – Dictionary keys are case sensitive, same
name but different cases of Key will be
treated distinctly.
Accessing elements of Dictionary
• In order to access the items of a dictionary refer
to its key name. Key can be used inside square
brackets. There is also a method called get() that
Dictionary will also help in accessing the element from a
dictionary.
…..
• Comments in Python are the lines in the code that are
ignored by the compiler during the execution of the
program. Comments enhance the readability of the
code and help the programmers to understand the
code very carefully.
• Single-Line Comments
Python single line comment starts with the hashtag
symbol (#) with no white spaces and lasts till the end of
Comments the line.
• Multi-Line Comments
in Python Python does not provide the option for
multiline comments
We can multiple hashtags (#) to write multiline
comments in Python. Each and every line will be
considered as a single line comment.
• Sometimes a developer might want to take user input at
some point in the program. To do this Python provides an
input() function.
• Syntax
Var = input('prompt')
• where prompt is an optional string that is displayed on
Input the string at the time of taking input for prompting user.
stateme • EX1 : name = input("Enter your name:
")
nts • Note: Python takes all the input as a string input by
default. To convert it to any other data type we have to
convert the input explicitly.
• Taking input from the user as integer
EX2 : num = int(input("Enter a number:
"))
• Python provides the print() function to display output to the
standard output devices.
• Syntax:
print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
• Parameters:
value(s) : Any value, and as many as you like. Will be
Output converted to string before printed
statem sep=’separator’ : (Optional) Specify how to separate the
objects, if there is more than one.Default :’ ‘
ent end=’end’: (Optional) Specify what to print at the
end.Default : ‘\n’
file : (Optional) An object with a write method.
Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed
(True) or buffered (False). Default: False
• Returns: It returns output to the screen.
1. print("GFG")
2. print('G', 'F', 'G')
Output :
GFG
G F G
3. print("GFG", end = "@")
Print 4. print('G', 'F', 'G', sep="#")
statement Output :

Examples GFG@G#F#G
• Formatting output in Python can be done in many
ways. Let’s discuss them below

1. Using formatted string literals


• We can use formatted string literals, by starting a
string with f or F before opening quotation marks or
triple quotation marks. In this string, we can write
Python expressions between { and } that can refer to a
Formatting variable or any literal value.
Output • Example
1.name = "Gfg"
2. print(f'Hello {name}! How are
you?')
Output : Hello Gfg! How are you?
2. Using format()
We can also use format() function to format our output to make it look presentable. The curly braces { } work as
placeholders. We can specify the order in which variables occur in the output.
a = 20
b = 10
sum = a + b
sub = a- b
print('The value of a is {} and b is {}'.format(a,b))
print('{2} is the sum of {0} and {1}'.format(a,b,sum))

print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a


,
value_b =
b,
sub_value =
Formatting Output
3. Using % Operator
• We can use ‘%’ operator. % values are replaced with zero or more value of elements. The formatting using %
is similar to that of ‘printf’ in the C programming language.
• %d – integer
• %f – float
• %s – string
• %x – hexadecimal
• %o – octal
• Example :
1.num = int(input("Enter a value: "))
2.add = num + 5
3.print("The sum is %d" %add)
• # Output
• Enter a value: 50
The sum is 55

You might also like