Python Chap1 (1)
Python Chap1 (1)
Python Chap1 (1)
An Introduction to
Python
Simple
Easy to Learn
High-level Language
Portable
Dynamically Typed
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 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.
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.
Web Development
Game Development
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
Variables :
In Python, variable names can use letters,
digits, and the underscore symbol (but they
can’t start with a digit).
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators
Operator Name Example
+ Addition 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
• 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:
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