Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

UNIT I

INTRODUCTION TO PYTHON:

Python is a general-purpose interpreted, interactive, object-oriented, and high- level programming


language.
It was created by Guido van Rossum during 1985- 1990.
Python got its name from “Monty Python’s flying circus”. Python was released in theyear 2000.
❖ Python is interpreted: Python is processed at runtime by the interpreter. Youdo not need to compile
your program before executing it.
❖ Python is Interactive: You can actually sit at a Python prompt and interact withthe interpreter directly
to write your programs.
❖ Python is Object-Oriented: Python supports Object-Oriented style or techniqueof programming that
encapsulates code within objects.
❖ Python is a Beginner's Language: Python is a great language for the beginner-
level programmers and supports the development of a wide range of
applications.
Python Features:
❖ Easy-to-learn: Python is clearly defined and easily readable. The structure of
the program is very simple. It uses few keywords.
❖ Easy-to-maintain: Python's source code is fairly easy-to-maintain.
❖ Portable: Python can run on a wide variety of hardware platforms and has thesame interface on all
platforms.
❖ Interpreted: Python is processed at runtime by the interpreter. So, there is noneed to compile a
program before executing it. You can simply run the program.
❖ Extensible: Programmers can embed python within their C,C++,Javascript,ActiveX, etc.
❖ Free and Open Source: Anyone can freely distribute it, read the source code, andedit it.
❖ High Level Language: When writing programs, programmers concentrate onsolutions of the
current problem, no need to worry about the low level details.
❖ Scalable: Python provides a better structure and support for large programsthan shell scripting.
Applications:
❖ Bit Torrent file sharing
❖ Google search engine, Youtube
❖ Intel, Cisco, HP, IBM
❖ i–Robot
❖ NASA
❖ Facebook, Drop box

STRUCTURE OF A PYTHON PROGRAM

Python Statements
In general, the interpreter reads and executes the statements line by line i.e sequentially. Though, there are
some statements that can alter this behavior like conditional statements. Mostly, python statements are
written in such a format that one statement is only written in a single line. The interpreter considers the ‘new
line character’ as the terminator of one instruction. But, writing multiple statements per line is also possible
that you can find below.

# Example 1
print('Welcome to Class ')
Multiple Statements per Line We can also write multiple statements per line, but it is not a good practice as
it reduces the readability of the code. Try to avoid writing multiplestatements in a single line. But, still you can
write multiple lines by terminating one statement with the help of ‘;’. ‘;’ is used as the terminator of one
statementinthiscase.

For Example, consider the following code.

# Example

a = 10; b = 20; c = b + a

print(a); print(b); print(c)

Python interpreter:

Interpreter: To execute a program in a high-level language by translating it one line ata time.
Compiler: To translate a program written in a high-level language into a low-levellanguage all at once, in
preparation for later execution.

Compiler Interpreter
Interpreter Takes Single instruction asinput
Compiler Takes Entire program as input

No Intermediate Object Code


Intermediate Object Code is Generated is Generated
Conditional Control Statements are Conditional Control Statements are
Executes faster Executes slower
Memory Requirement is More(Since Object
Memory Requirement is Less
Code is Generated)
Every time higher level program is
Program need not be compiled every time converted into lower level program
Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
Example : C Compiler Example : PYTHON

MODES OF PYTHON INTERPRETER:


Python Interpreter is a program that reads and executes Python code. It uses 2 modesof Execution.
1. Interactive mode
2. Script mode
Interactive mode:
❖ Interactive Mode, as the name suggests, allows us to interact with OS.
❖ When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or explore.
❖ Working in interactive mode is convenient for beginners and for testing smallpieces of code.
Drawback:
❖ We cannot save the statements and have to retype all the statements once again to re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for youto enter code. If
you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case,the result is the words.
Script mode:
• In script mode, we type python program in a file and then use interpreter toexecute the content of
the file.
• Scripts can be saved to disk for future use. Python scripts have the
extension .py, meaning that the filename ends with .py
• Save the code with filename.py and run the interpreter in script mode to executethe script.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter toread and
typing commands and expressions at theprompt. execute statements in a script.

Cant save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for furtheruse and we we can save the statements for further useand we no
have to retype need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

Integrated Development Learning Environment (IDLE):


• Is a graphical user interface which is completely written in Python.
• It is bundled with the default implementation of the python language and alsocomes with optional part
of the Python packaging.
Features of IDLE:
• Multi-window text editor with syntax highlighting. Auto completion with smart indentation.
• Python shell to display output with syntax highlighting.

UNDERSTANDING PYTHON SHELL

Python is an interpreter language. It means it executes the code line by line. Python provides a Python Shell,
which is used to execute a single Python command and display the result.
It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the command,
prints the result, and loop it back to read the command again.

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac,
write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown
below.

Now, you can enter a single statement and get the result. For example, enter a simple expression like 3 + 2,
press enter and it will display the result in the next line, as shown below.

Execute Python Script

As you have seen above, Python Shell executes a single statement. To execute multiple statements, create a
Python file with extension .py, and write Python scripts (multiple statements).
For example, enter the following statement in a text editor such as Notepad.

Example: myPythonScript.py
Copy
print ("This is Python Script.")
print ("Welcome to Python Tutorial by TutorialsTeacher.com")

Save it as myPythonScript.py, navigate the command prompt to the folder where you have saved this file and
execute the python myPythonScript.py command, as shown below. It will display the result.

Thus, you can execute Python expressions and commands using Python REPL to quickly execute Python code.

VALUES AND DATA TYPES

Value:
Value can be any letter ,number or string.
Eg, Values are 2, 42.0, and 'Hello, World!'. (These values belong to differentdatatypes.)
Data type:
Every value in Python has a data type.
It is a set of values, and the allowable operations on those values.
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
Python has four standard data types:

Numeric
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.
• 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
EXAMPLE

# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store
multiple values in an organized and efficient fashion. There are several sequence types in Python –
• String
• List
• Tuple

String
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 double quotes or even triple quotes.

EXAMPLE:

# Python Program for


# Creation of String

# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks For Life'''
print("\nCreating a multiline String: ")
print(String1)
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.

EXAMPLE

# Python Program to Access


# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

List
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[].

# Python program to demonstrate


# Creation of List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Accessing elements of 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.

EXAMPLE:

# Python program to demonstrate


# Creation of List

# Creating a List
List = []
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)

Accessing elements of 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.

EXAMPLE

# Python program to demonstrate


# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])

Tuple
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 number of elements and of any datatype
(like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.

EXAMPLE:

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
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.
# Python program to
# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])

Boolean

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.

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))

print(type(true))

Set
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 also be passed to the set.

# Python program to demonstrate


# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

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.

EXAMPLE

# Python program to demonstrate


# Accessing of elements in a set

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
for i in set1:
print(i, end =" ")

# Checking the element


# using in keyword
print("Geeks" in set1)

Dictionary

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’.

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{}.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

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 will also help in accessing the element from a dictionary.

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")

Literals in Python

Generally, literals are a notation for representing a fixed value in source code. They can also be defined as
raw values or data given in variables or constants. Python has different types of literal such as:
1. String literals
2. Numeric literals
3. Boolean literals
4. Literal Collections
5. Special literals

What is String literals


A string literal can be created by writing a text(a group of Characters ) surrounded by a single(”), double(“”), or
triple quotes. By using triple quotes we can write multi-line strings or display them in the desired way.
EXAMPLE:

# string literals

# in single quote
s = 'geekforgeeks'

# in double quotes
t = "geekforgeeks"

# multi-line String
m = '''geek
for
geeks'''

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

What is Character literal


It is also a type of string literal where a single character is surrounded by single or double quotes.
EXAMPLE:

# character literal in single quote


v = 'n'

# character literal in double quotes


w = "a"

print(v)
print(w)

What is Numeric literal


hey are immutable and there are three types of numeric literal:
1. Integer
2. Float python
3. Complex.
Integer:
Both positive and negative numbers including 0. There should not be any fractional part.
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.

# integer literal

# Binary Literals
a = 0b10100

# Decimal Literal
b = 50

# Octal Literal
c = 0o320

# Hexadecimal Literal
d = 0x12b

print(a, b, c, d)

Float
These are real numbers having both integer and fractional parts.
EXAMPLE

Float Literal
e = 24.8
f = 45.0

print(e, f)

Complex
The numerals will be in the form of a + bj, where ‘a‘ is the real part and ‘b‘ is the complex part.

EXAMPLE:

z = 7 + 5j

# real part is 0 here.


k = 7j

print(z, k)

Escape Characters

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double quotes

Other escape characters used in Python:

Code Result

\' Single Quote

\\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed
\ooo Octal value

\xhh Hex value

Python String Concatenation

InPython, Strings arearrays of bytes representing Unicode characters.However, Python does not have a character
data type, a single character is simply a string with a length of 1. Square brackets [] can be used to access elements
of the string.

# Assign variable var1 & var 2


var1 = "Welcome"
var2 = "statistics"

# print the result


print(f"{var1} {var2}")

String Concatenation in Python


String Concatenation is the technique of combining two strings. String Concatenation can be done using many
ways.
1. Using + operator
2. Using join () method
3. Using % operator
4. Using format () function
5. Using, (comma)

Method 1: String Concatenation using + Operator

It’s very easy to use the + operator for string concatenation. This operator can be used to add multiple strings
together. However, the arguments must be a string. Here, The + Operator combines the string that is stored in
the var1 and var2 and stores in another variable var3.

# Defining strings
var1 = "Hello "
var2 = "World"

# + Operator is used to combine strings


var3 = var1 + var2
print(var3)

Method 2: String Concatenation using join() Method

The join() method is a string method and returns a string in which the elements of the sequence have been joined
by str separator. This method combines the string that is stored in the var1 and var2. It accepts only the list as its
argument and list size can be anything.

var1 = "Hello"
var2 = "World"

# join() method is used to combine the strings


print("".join([var1, var2]))

# join() method is used here to combine


# the string with a separator Space(" ")
var3 = " ".join([var1, var2])
print(var3)

Method 3: String Concatenation using % Operator

We can use the % operator for string formatting, it can also be used for string concatenation. It’s useful when we
want to concatenate strings and perform simple formatting. The %s denotes string data type. The value in both
the variable is passed to the string %s and becomes “Hello World”.

var1 = "Hello"
var2 = "World"

# % Operator is used here to combine the string


print("% s % s" % (var1, var2))

Method 4: String Concatenation using format() function

str.format() is one of the string formatting methods in Python, which allows multiple substitutions and value
formatting. It concatenate elements within a string through positional formatting. The curly braces {} are used to
set the position of strings. The first variable stores in the first curly braces and the second variable stores in the
second curly braces. Finally, it prints the value “Hello World”.
var1 = "Hello"
var2 = "World"

# format function is used here to


# combine the string
print("{} {}".format(var1, var2))

# store the result in another variable


var3 = "{} {}".format(var1, var2)

print(var3)

Method 5: String Concatenation using (, comma)

“,” is a great alternative to string concatenation using “+”. when you want to include single whitespace. Use a
comma when you want to combine data types with single whitespace in between.
var1 = "Hello"
var2 = "World"

# , to combine data types with a single whitespace.


print(var1, var2)

“HelloWorld”
Python Variables

Python Variable is containers which store values. Python is not “statically typed”. We do not need to declare
variables before using them or declare their type. A variable is created the moment we first assign a value to it. A
Python variable is a name given to a memory location. It is the basic unit of storage in a program.

Example of Python Variables

Var = "Geeksforgeeks"
print(Var)

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)
Declare the Variable
Let’s see how to declare the variable and print the variable.
# declaring the var
Number = 100

# display
print( Number)
Re-declare the Variable
We can re-declare the python variable once we have declared the variable already.
# declaring the var
Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)


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)

Assigning different values to multiple variables


Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)
print(b)
print(c)

Global and Local Python Variables


Local variables are the ones that are defined and declared inside a function. We cannot call this variable outside
the function.

# This function uses global variable s


def f():
s = "Welcome geeks"
print(s)
f()

Global variables are the ones that are defined and declared outside a function, and we need to use them inside a
function.

# This function has a variable with


# name same as s.
def f():
print(s)

# Global scope
s = "python Programming"
f()

Variable type in Python


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.
Following are the standard or built-in data type of Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary

# numberic
var = 123
print("Numeric data : ", var)

# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Boolean
print(type(True))
print(type(False))

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

PROGRAM COMMENTS AND DOC STRINGS

Python documentation strings (or docstrings) provide a convenient way of associating documentation
with Python modules, functions, classes, and methods. It's specified in source code that is used, like a
comment, to document a specific segment of code.

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:

Example:
Let’s see an exemplar code of arithmetic expressions in Python :
# 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)

Python For Loops

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned
to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned
to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
For Loops Syntax
for var in iterable:
# statements

Example

for letter in 'Python': # First Example


print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango

Control Flow in Python

There comes situations in real life when we need to make some decisions and based on these decisions, we
decide what should we do next. Similar situations arise in programming also where we need to make some
decisions and based on these decisions we will execute the next block of code. Decision-making statements
in programming languages decide the direction of the flow of program execution.

if statement
if statement is the most simple decision-making statement. It is used to decide whether a certain statement or
block of statements will be executed or not i.e if a certain condition is true then a block of statement is
executed otherwise not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts boolean values –
if the value is true then it will execute the block of statements below it otherwise not. We can
use condition with bracket ‘(‘ ‘)’ also.
As we know, python uses indentation to identify a block. So the block under an if statement will be
identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Flowchart of Python if statement

Example
# python program to illustrate If statement

i = 10

if (i > 15):
print("10 is less than 15")
print("I am Not in if")

if-else
The if statement alone tells us that if a condition is true it will execute a block of statements and if the
condition is false it won’t. But what if we want to do something else if the condition is false. Here comes
the else statement. We can use the else statement with if statement to execute a block of code when the
condition is false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

FlowChart of Python if-else statement

Example

# python program to illustrate If else statement


#!/usr/bin/python

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
nested-if
A nested if is an if statement that is the target of another if statement. Nested if statements mean an if
statement inside another if statement. Yes, Python allows us to nest if statements within if statements. i.e,
we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart of Python Nested if Statement

# python program to illustrate nested If statement


#!/usr/bin/python
i = 10
if (i == 10):

# First if statement
if (i < 15):
print("i is smaller than 15")

# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed from the top down. As
soon as one of the conditions controlling the if is true, the statement associated with that if is executed,
and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed.
Syntax:
if (condition):
statement
elif (condition):
statement.
else:
statement
FlowChart of Python if else elif statements

Example: Python if else elif statements

# Python program to illustrate if-elif-else ladder


#!/usr/bin/python

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block then shorthand if can be
used. The statement can be put on the same line as the if statement.
Syntax:
if condition: statement
Example: Python if shorthand
# Python program to illustrate short hand if
i = 10
if i < 15:
print("i is less than 15")

Short Hand if-else statement


This can be used to write the if-else statements in a single line where there is only one statement to be
executed in both if and else block.
Syntax:
statement_when_True if condition else statement_when_False
# Python program to illustrate short hand if-else
i = 10
print(True) if i < 15 else print(False)

Python While Loop

Until a specified criterion is true, a block of statements will be continuously executed in a Python while
loop. And the line in the program that follows the loop is run when the condition changes to false.

Syntax of Python While

while expression:
statement(s)

Example
# prints Hello Geek 3 Times
count = 0
while (count < 3):
count = count+1
print("Hello Geek")
Continue Statement
Python Continue Statement returns the control to the beginning of the loop.

Python while loop with continue statement


# Prints all letters except 'e' and 's'
i=0
a = 'geeksforgeeks'

while i < len(a):


if a[i] == 'e' or a[i] == 's':
i += 1
continue

print('Current Letter :', a[i])


i += 1

Break Statement
Python Break Statement brings control out of the loop.

Example: Python while loop with a break statement


# break the loop as soon it sees 'e'
# or 's'
i=0
a = 'geeksforgeeks'

while i < len(a):


if a[i] == 'e' or a[i] == 's':
i += 1
break

print('Current Letter :', a[i])


i += 1

Pass Statement
The Python pass statement to write empty loops. Pass is also used for empty control statements, functions, and
classes.

Example: Python while loop with a pass statement

# An empty loop
a = 'geeksforgeeks'
i=0

while i < len(a):


i += 1
pass

print('Value of i :', i)
While loop with else

As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes
false, the statement immediately after the loop is executed. The else clause is only executed when your while
condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
# Python program to demonstrate
# while-else loop

i=0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")

i=0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")

Sentinel Controlled Statement


In this, we don’t use any counter variable because we don’t know that how many times the loop will execute. Here
user decides that how many times he wants to execute the loop. For this, we use a sentinel value. A sentinel value
is a value that is used to terminate a loop whenever a user enters it, generally, the sentinel value is -1.
Example: Python while loop with user input
a = int(input('Enter a number (-1 to quit): '))

while a != -1:
a = int(input('Enter a number (-1 to quit): '))
4.OPERATORS:
❖ Operators are the constructs which can manipulate the value of operands.
❖ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + iscalled operator
❖ Types of 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:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Assume, a=10 and b=5

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand a – b = -10


operand.

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder

** Exponent Performs exponential (power) calculation on a**b =10 to the


operators power 20

// Floor Division - The division of operands where the result is the 5//2=2
quotient in which the digits after the decimal point are removed

Examples Output:
a=10 a+b= 15
b=5 print("a+b=",a+b) a-b= 5
print("a-b=",a-b) a*b= 50
print("a*b=",a*b) a/b= 2.0
print("a/b=",a/b) a%b= 0
print("a%b=",a%b) a//b= 2
print("a//b=",a//b) a**b= 100000
print("a**b=",a**b)

Comparison (Relational) Operators:


• Comparison operators are used to compare values.
• It either returns True or False according to the condition. Assume, a=10 and b=5

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is


becomes true. not true.

!= If values of two operands are not equal, then conditionbecomes true. (a!=b) is
true

> If the value of left operand is greater than the value of rightoperand, then (a > b) is not
condition becomes true. true.

< If the value of left operand is less than the value of rightoperand, then (a < b) istrue.
condition becomes true.

>= If the value of left operand is greater than or equal to thevalue of right (a >= b) is
operand, then condition becomes true. not true.

<= If the value of left operand is less than or equal to the valueof right operand, (a <= b) is
then condition becomes true. true.

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

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left sideoperand c = a + b


assigns value
of a +b into c

+= Add AND It adds right operand to the left operand and assignthe result to left c += a is
operand equivalent to c
=c+a

-= Subtract It subtracts right operand from the left operand andassign the result c -= a is
AND to left operand equivalent to c
=c-a
*= Multiply It multiplies right operand with the left operand andassign the result c *= a is
AND to left operand equivalent to c
=c*a

/= Divide It divides left operand with the right operand andassign the result to c /= a is
AND left operand equivalent to c
= c / ac
/= a is
equivalent to c
=c/a

%= Modulus It takes modulus using two operands and assign theresult to left c %= a is
AND operand equivalent to c
=c%a

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left operand equivalent to c
= c ** a

//= Floor It performs floor division on operators and assignvalue to the left c //= a is
Division operand equivalent to c
= c // a

Example Output
a = 21 Line 1 - Value of c is 31 Line 2 -
b = 10 Value of c is 52 Line 3 - Value
c=0 of c is 1092Line 4 - Value of c
c=a+b is 52.0 Line 5 - Value of c is 2
print("Line 1 - Value of c is ", c)c += a Line 6 - Value of c is 2097152Line 7
print("Line 2 - Value of c is ", c)c *= a - Value of c is 99864
print("Line 3 - Value of c is ", c)c /= a
print("Line 4 - Value of c is ", c)c = 2
c %= a
print("Line 5 - Value of c is ", c)c **=
a
print("Line 6 - Value of c is ", c)c //= a
print("Line 7 - Value of c is ", c)
Logical Operators:
-Logical operators are the and, or, not operators.

Example a Output
= True b = x and y is Falsex or
False y is True not x is
print('a and b is',a and b) False
print('a or b is',a or b)
print('not a is',not a)

Bitwise Operators:
• A bitwise operation operates on one or more bit patterns at the level of individualbits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example Output
a = 60 # 60 = 0011 1100 Line 1 - Value of c is 12 Line
b = 13 # 13 = 0000 1101 2 - Value of c is 61 Line 3 -
c=0 Value of c is 49 Line 4 - Value
c = a & b; # 12 = 0000 1100 of c is -61Line 5 - Value of c
print "Line 1 - Value of c is ", cc = a | is 240Line 6 - Value of c is 15
b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c c = a
^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c

Membership Operators:

❖ Evaluates to find a value or a variable is in the specified sequence of string, list,tuple, dictionary or
not.
❖ Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operatorsare used.

Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False

Identity Operators:
❖ They are used to check if two values (or variables) are located on the same part ofthe
memory.

Example
x=5 Output
y=5 False
x2 = 'Hello'y2 True
= 'Hello'
print(x1 is not y1)
print(x2 is y2)
5.OPERATOR PRECEDENCE:
When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (methodnames for the


last two are +@ and -@)

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

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'

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

<= < > >= Comparison operators

<> == != Equality operators

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

is is not Identity operators

in not in Membership operators

not or and Logical operators

-For mathematical operators, Python follows mathematical convention.


-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction) is a
useful way to remember the rules:
❖ Parentheses have the highest precedence and can be used to force an expression to evaluate in the order
you want. Since expressions in parentheses are evaluatedfirst, 2 * (3-1)is 4, and (1+1)**(5-2) is 8.
❖ You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
❖ Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and 2
*3**2 is 18, not 36.
❖ Multiplication and Division have higher precedence than Addition and Subtraction. So 2*3-1 is 5, not 4,
and 6+4/2 is 8, not 5.
❖ Operators with the same precedence are evaluated from left to right (except exponentiation).
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 A=6+4- m=-43||8&&0||-2 m=-
a=9-4+6-1 1+6 43||0||-2 m=1||-2
a=5+6-1 a=11- A=10-1+6 m=1
1 a=10 A=9+6
A=15

a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6a=15
d=1>1 d=2<12>1-1
d=0 d=2<12>0
d=1>0
d=1

You might also like