0% found this document useful (0 votes)
10 views29 pages

Python UnitI

Python is a versatile, high-level programming language created by Guido van Rossum between 1985 and 1990, known for its ease of learning and dynamic typing. It has evolved through various versions, with significant updates like Python 3.0 aimed at addressing fundamental flaws. Python is widely used across multiple domains including web development, data science, and artificial intelligence, and features a rich standard library and support for various programming paradigms.

Uploaded by

joyshc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views29 pages

Python UnitI

Python is a versatile, high-level programming language created by Guido van Rossum between 1985 and 1990, known for its ease of learning and dynamic typing. It has evolved through various versions, with significant updates like Python 3.0 aimed at addressing fundamental flaws. Python is widely used across multiple domains including web development, data science, and artificial intelligence, and features a rich standard library and support for various programming paradigms.

Uploaded by

joyshc
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT I

INTRODUCTION TO PYTHON
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
Python is dynamically-typed and garbage-collected programming language. It was created by
Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the
GNU General Public License (GPL).

Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.

Python History and Versions


o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
[Link].
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Why the Name Python?

There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.

The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, e

Where is Python used?/ Applications of python


Python is a general-purpose, popular programming language and it is used in almost every
technical field. The various areas of Python use are given below.

o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions

LANGUAGE FEATURES

 Interpreted
o There are no separate compilation and execution steps like C and C++.
o Directly run the program from the source code.
o Internally, Python converts the source code into an intermediate form called
bytecodes which is then translated into native language of specific computer to
run it.
o No need to worry about linking and loading with libraries, etc.

 Platform Independent
o Python programs can be developed and executed on multiple operating system
platforms.
o Python can be used on Linux, Windows, Macintosh, Solaris and many more.
 Free and Open Source; Redistributable
 High-level Language
o In Python, no need to take care about low-level details such as managing the
memory used by the program.
 Simple
o Closer to English language;Easy to Learn
o More emphasis on the solution to the problem rather than the syntax
 Embeddable
o Python can be used within C/C++ program to give scripting capabilities for the
program‟s users.
 Robust:
o Exceptional handling features
o Memory management techniques in built
 Rich Library Support
o The Python Standard Library is very vast.
o Known as the “batteries included” philosophy of Python ;It can help do
various things involving regular expressions, documentation generation, unit
testing, threading, databases, web browsers, CGI, email, XML, HTML, WAV
files, cryptography, GUI and many more.
o Besides the standard library, there are various other high-quality libraries such
as the Python Imaging Library which is an amazingly simple image
manipulation library.

Python vs JAVA

Python Java

Statically Typed
Dynamically Typed  All variable names (along with their types)
 No need to declare anything. An must be explicitly declared. Attempting to
assignment statement binds a name to an assign an object of the wrong type to a
object, and the object can be of any type. variable name triggers a type exception.
 No type casting is required when using  Type casting is required when using
container objects container objects.

Concise Express much in limited words Verbose Contains more words

Compact Less Compact

Uses Indentation for structuring code Uses braces for structuring code

Advantages and Disadvantages of Python


IDENTIFIERS
Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore.

Rules for writing Identifiers in Python


1. The identifier is a combination of character digits and underscore and the character includes
letters in lowercase (a-z), letters in uppercase (A-Z), digits (0-9), and an underscore (_).
2. An identifier cannot begin with a digit. If an identifier starts with a digit, it will give a Syntax
error.
3. In Python, keywords are the reserved names that are built-in to Python, so a keyword cannot
be used as an identifier - they have a special meaning and we cannot use them as identifier
names.
4. Special symbols like !, @, #, $, %, etc. are not allowed in identifiers.
5. Python identifiers cannot only contain digits.
6. There is no restriction on the length of identifiers.
7. Identifier names are case-sensitive.
Python Valid Identifiers Example
 abc123
 abc_de
 _abc
 ABC
 abc

Python Invalid Identifiers Example


 123abc
 abc@
 123
 for
Python Identifier Naming Best Practices
1. Only class names are started with capital letters (Student, Employee).
2. Multiple words in a variable are separated by an underscore (is_valid()).
3. If an identifier begins with an underscore, it means it is a private identifier. This does not
make the variable private. It is only for the ease of the programmer to easily distinguish between
private variables and public variables.
4. Python built-in magic methods use double underscores around the names (__len__).
Therefore, double underscores are used only when you are dealing with mangling in Python.
5. Using longer name than one character is always preferred (index = 1 is better than i = 1).
6. Camel case are used while naming the variables (studentAddress, studentId). Camel case use
a capital letter to begin the second word in a compound name or phrase, when it is not separated
from the first word by a space.

KEYWORDS
Keywords are some predefined and reserved words in python that have special meanings.
Keywords are used to define the syntax of the coding.
The keyword cannot be used as an identifier, function, and variable name. All the keywords in
python are written in lower case except True and False. There are 33 keywords in Python 3.7.
Python Keywords List

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

LITERALS
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string literals, Boolean
literals, and more.
1. String literals
2. Character literal
3. Numeric literals
4. Boolean literals
5. Literal Collections
6. Special literals

String Literals
A string is literal and can be created by writing a text(a group of Characters ) surrounded by a
single(”), double(“), or triple quotes. We can write multi-line strings or display them in the
desired way by using triple quotes. Here geekforgeeks is a string literal that is assigned to a
variable(s). Here is an example of a Python string literal.

Example:
s = 'geekforgeeks'
t = "geekforgeeks"
m = '''geek
for
geeks'''

print(s)
print(t)
print(m)

Numeric Literals in Python

Numerical literals in Python are those literals that contain digits only and are immutable.
They are immutable and there are three types of numeric literal:
 Integer
 Float
 Complex

Integer
Both positive and negative numbers including 0. There should not be any fractional part. In
this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different variables.
Here, „a„ is a binary literal, „b’ is a decimal literal, „c„ is an octal literal, and „d„ is a
hexadecimal literal. But on using the print function to display a value or to get the output they
were converted into decimal.

Example
# Binary Literals
a = 0b10100
# Decimal Literal
b = 50
# Octal Literal
c = 0o320
# Hexadecimal Literal
d = 0x12b
print(a, b, c, d)

Output
20 50 208 299

Float
These are real numbers having both integer and fractional parts. In this example, 24.8 and 45.0
are floating-point literals because both 24.8 and 45.0 are floating-point numbers.

# Float Literal
e = 24.8
f = 45.0
print(e, f)

Output
24.8 45.0

Complex
The numerals will be in the form of a + bj, where „a’ is the real part and „b„ is the complex
part. Numeric literal [ Complex ]

z = 7 + 5j
# real part is 0 here.
k = 7j
print(z, k)

Output
(7+5j) 7j

Boolean literal
There are only two Boolean literals in Python. They are true and false. In
Python, True represents the value as 1, and False represents the value as 0. In this example „a„
is True and „b„ is False because 1 is equal to True.

Example
a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7

print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)

Output
a is True
b is False
c: 4
d: 7

Python literal collections


Python provides four different types of literal collections:
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals

List literal
The list contains items of different data types. The values stored in the List are separated by a
comma (,) and enclosed within square brackets([]). We can store different types of data in a
List. Lists are mutable.

number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)

Output
[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]

Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses „()„ and each
element is separated by the comma(,). It is immutable.
even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)
print(even_number)
print(odd_number)

Output
(2, 4, 6, 8)
(1, 3, 5, 7)

Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly braces „{}„ and each
pair is separated by the commas(,). We can store different types of data in a dictionary.
Dictionaries are mutable.

Example
alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}
information = {'name': 'amit', 'age': 20, 'ID': 20}
print(alphabets)
print(information)

Output
{'a': 'apple', 'b': 'ball', 'c': 'cat'}
{'name': 'amit', 'age': 20, 'ID': 20}

Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each element is
separated by the comma(,).

vowels = {'a', 'e', 'i', 'o', 'u'}


fruits = {"apple", "banana", "cherry"}
print(vowels)
print(fruits)

Output
{'o', 'e', 'a', 'u', 'i'}
{'apple', 'banana', 'cherry'}

EXPRESSIONS

A combination of operands and operators is called an expression.


An expression is a combination of operators and operands that is interpreted to produce some
other value. In any programming language, an expression is evaluated as per the precedence of
its operators.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a numeric
value. The operators used in these expressions are arithmetic operators like addition,
subtraction, etc. Here are some arithmetic operators in Python:

Operators Syntax Functioning

+ x+y Addition

– x–y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation
Example:
# Arithmetic Expressions
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)

Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5

c=a/b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on
both sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated
first, and then compared as per relational operator and produce a boolean output in the end.
These expressions are also called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)

Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It
basically specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal
to 9. As we know it is not correct, so it will return False. Studying logical expressions, we also
come across some logical operators which can be seen in logical expressions most often. Here
are some logical operators in Python:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:

P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q
T = not P

print(R)
print(S)
print(T)

Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)

Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single
expression, and that will be termed as combinational expressions.

Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)

VARIABLES
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
Rules for creating variables in Python
 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_ ).
 Variable names are case-sensitive (name, Name and NAME are three different variables).
 The reserved words(keywords) cannot be used naming the variable.

Example
# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:
45
1456.8
John
Declare the Variable
# declaring the var
Number = 100

# display
print( Number)
Output:
100

Assigning a single value to multiple variables


Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Assigning different values to multiple variables
Python allows adding different values in a single line with “,”operators.
Example
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks
Can we use the same name for different types?
If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "GeeksforGeeks"
print(a)
Output:
GeeksforGeeks

PYTHON OPERATORS
Operators are used to perform operations on variables and values.
 OPERATORS: Are the special symbols. Eg- + , * , /, etc.
 OPERAND: It is the value on which the operator is applied.
Python divides the operators in the following groups:

Types of Python Operators


Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Arithmetic Operators
Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Expoents and
Floor Division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

Example
a = 21
b = 10
print ("a + b : ", a + b)
print ("a - b : ", a - b)
print ("a * b : ", a * b)
print ("a / b : ", a / b)
print ("a % b : ", a % b)
print ("a ** b : ", a ** b)
print ("a // b : ", a // b)
Output
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2

Comparison Operators

Python comparison operators compare the values on either sides of them and decide the relation
among them. They are also called relational operators. These operators are equal, not equal,
greater than, less than, greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.


!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Example
a=4
b=5
print ("a == b : ", a == b)
print ("a != b : ", a != b)
print ("a > b : ", a > b)
print ("a < b : ", a < b)
print ("a >= b : ", a >= b)
print ("a <= b : ", a <= b)
Output
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True

Assignment Operators

Python assignment operators are used to assign values to variables. These operators include
simple assignment operator, addition assign, subtraction assign, multiplication assign, division
and assign operators etc.

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)


Example
a = 10
a += 5
print("a += 5 : ", a)
a -= 5
print("a -= 5 : ", a)
a *= 5
print("a *= 5 : ", a)
a /= 5
print("a /= 5 : ",a)
a %= 3
print ("a %= 3 : ", a)
a **= 2
print ("a **= 2 : ", a)
a //= 3
print ("a //= 3 : ", a)
Output
a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0

Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following
table lists out the bitwise operators supported by Python language with an example each in those,
we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)

There are following Bitwise operators supported by Python language

Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1


^ Binary XOR Sets each bit to 1 if only one of two bits is 1

~ Binary Ones Inverts all the bits


Complement

<< Binary Left Shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off

>> Binary Right Shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off

Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101

# Binary AND
c=a&b # 12 = 0000 1100
print ("a & b : ", c)

# Binary OR
c=a|b # 61 = 0011 1101
print ("a | b : ", c)

# Binary XOR
c=a^b # 49 = 0011 0001
print ("a ^ b : ", c)

# Binary Ones Complement


c = ~a; # -61 = 1100 0011
print ("~a : ", c)
# Binary Left Shift
c = a << 2; # 240 = 1111 0000
print ("a << 2 : ", c)

# Binary Right Shift


c = a >> 2; # 15 = 0000 1111
print ("a >> 2 : ", c)
Output
a & b : 12
a | b : 61
a ^ b : 49
~a : -61
a >> 2 : 240
a >> 2 : 15

Logical Operators

There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then
Operator Description Example

and Logical If both the operands are true then condition becomes (a and b) is true.
AND true.

or Logical OR If any of the two operands are non-zero then condition (a or b) is true.
becomes true.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b) is
false.
Example

a=1
b=6
print((a > 2) and (b >= 6))
print((a>2) or (b>=6))
print(not a)

Output
False
True
False

Membership Operators
Python‟s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is


specified sequence and false otherwise. a member of sequence y.

not in Evaluates to true if it does not finds a variable x not in y, here not in results in a
in the specified sequence and false otherwise. 1 if x is not a member of sequence
y.

Example
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list

Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity operators
explained below

Operator Description Example

is Evaluates to true if the variables on either side of the


x is y, here is results in 1 if
operator point to the same object and false
id(x) equals id(y).
otherwise.

is not Evaluates to false if the variables on either side of


x is not y, here is not results in
the operator point to the same object and true
1 if id(x) is not equal to id(y).
otherwise.

Example
x=5
y=5
print(x is y)
id(x)
id(y)
Output
True

PYTHON OPERATORS PRECEDENCE

The following table lists all operators from highest precedence to lowest.

[Link]. Operator & Description

1 ** Exponentiation (raise to the power)

2 ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)

3 * / % // Multiply, divide, modulo and floor division

4 + - Addition and subtraction

5 >> << Right and left bitwise shift


6 & Bitwise 'AND'

7 ^| Bitwise exclusive `OR' and regular `OR'

8 <= < > >= Comparison operators

9 <> == != Equality operators

10 = %= /= //= -= += *= **= Assignment operators

11 is is not Identity operators

12 in not in Membership operators

13 not or and Logical operators

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.

Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable.

For example;
a=5
print("The type of a", type(a))
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.


1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

Example
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)

Output:
string using double quotes
A multiline
string

List

Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Example:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

Output
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Example:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type, whereas
value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Example:

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])

print ([Link]())
print ([Link]())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'.

Example:
print(type(True))
print(type(False))
print(false)

Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set()
Example:
# Creating Empty set
set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
[Link](10)
print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}

PYTHON INDENTATION
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Example
Syntax Error:

if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.

You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:

Example

Syntax Error:

if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

INPUT STATEMENTS IN PYTHON


In python, input( ) method is used for getting input from the user.

Syntax
Input(prompt)

Here, prompt is the string we wish to display on the screen. It is optional.


Example:

num = input('Enter a number: ')

print('You Entered:', num)

Output:
Enter a number: 10
You Entered: 10

Output Statement in Python

We can use print( ) method to display output to the user.

Example
print('Python is powerful')

Syntax

print(object= separator= end= file= flush=)

Here,

 object - value(s) to be printed


 sep (optional) - allows us to separate multiple objects inside print().
 end (optional) - allows us to add add specific values like new line "\n", tab "\t"
 file (optional) - where the values are printed. It's default value is [Link] (screen)
 flush (optional) - boolean specifying if the output is flushed or buffered. Default: False

Example

print('Good Morning!', end= ' ')

print('It is rainy today')

TYPE CONVERSION

Type conversion is the process of converting data of one type to another. For example:
converting int data to str.
There are two types of type conversion in Python.

 Implicit Conversion - automatic type conversion


 Explicit Conversion - manual type conversion

Implicit Type Conversion


In certain situations, Python automatically converts one data type to another. This is known as
implicit type conversion.
Example 1:
x = 10

print("x is of type:",type(x))

y = 10.6
print("y is of type:",type(y))

z=x+y

print(z)
print("z is of type:",type(z))

Output
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.

Converting integer to float


int(a, base): This function converts any data type to an integer. „Base‟ specifies the base in
which the string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.

Example:

s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Python Type conversion using ord(), hex(), oct()
ord(): This function is used to convert a character to an integer.
hex(): This function is to convert an integer to a hexadecimal string.
oct(): This function is to convert an integer to an octal string.

ARRAY IN PYTHON
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together.

Access the Elements of an Array

You refer to an array element by referring to the index number.

Example

Get the value of the first array item:

cars = ["Ford", "Volvo", "BMW"]

x = cars[0]

print(x)

Output:
Ford

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Example

Return the number of elements in the cars array:

x = len(cars)
Output:
3

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Example

Print each item in the cars array:

for x in cars:
print(x)

Output
Ford
Volvo
BMW

Adding Array Elements

You can use the append() method to add an element to an array.

Example

Add one more element to the cars array:

[Link]("Honda")

['Ford', 'Volvo', 'BMW', 'Honda']

Removing Array Elements

You can use the pop() method to remove an element from the array.

Example

Delete the second element of the cars array:

[Link](1)

['Ford', 'BMW']

You can also use the remove() method to remove an element from the array.

Example

Delete the element that has the value "Volvo":

[Link]("Volvo")
Output

['Ford', 'BMW']
ARRAY METHODS

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

You might also like