SlideShare a Scribd company logo
Introduction to Python
History of Python
• Python is a language that’s focused on simplicity and ease of use.
It’s multiparadigm, allowing programmers to write code in object-
oriented, structural, or functional programming styles.
• Today, it’s widely used in multiple fields, such as machine learning
(frameworks like TensorFlow and Keras) and web development.
After JavaScript, it is the most used programming language in the
world.
• Like today’s most popular languages such as C and Java, Python has
a long history behind it.
• The main person accompanying us on our journey will be Guido van
Rossum.
• Guido is the main creator of the language.
History of Python
• Source: https://exyte.com/blog/a-brief-history-of-python
• In 1989, Van Rossum was working on Amoeba, a microkernel-based
distributed system, for which he was developing system utilities.
• While working on them, Guido realized that developing in C takes too
much time. He decided to spend his free time building a language
that would help him accomplish his work faster.
• He had an idea of a scripting language that would be somewhere
between C and a shell script: interpreted, but much more easily
programmable and readable than shell scripts.
• As you probably have guessed, that language turned out to be
Python.
• A fun fact: Python is not named after the snake species, but after the
British surreal comedy troupe Monty Python.
History of Python
• In February 1991, Van Rossum published the source code of Python’s
interpreter to alt.sources, a Usenet group for open-source code.
While this may seem to be a regular thing—nowadays, basically all
the programming languages are open-source and on GitHub—back
then, it was still unclear what would be the business model of people
developing the languages.
• For example, there were proprietary languages, but it was hard for
those to become popular.
• Guido has said that open-sourcing Python was one of the things that
significantly helped it succeed at that time.
• The first release (0.9.0) had features such as classes, exception
handling, functions, and the core datatypes like list, dict, str, and so
on.
• It was heavily inspired by ABC, a language that Guido spent some
time implementing at CWI. While creating Python, his goal was to
take the good parts of ABC while fixing the rest.
History of Python
• In January 1994, version 1.0 was released, and a separate Usenet
group for it was created, marking a milestone in the history of
Python.
• Around that time, multiple other dynamically typed and interpreted
languages similar to Python were created, such as Perl and Ruby,
which shows that the need for such a language was definitely in the
air.
• In 1994, Guido was invited to the USA by NIST, the US National
Institute for Standards and Technology.
• NIST was interested in using Python for several standards-related
projects and needed somebody to boost their Python skills.
Obviously, the creator of language was a great choice.
• With NIST support, Guido was able to run workshops and participate
in conferences, spreading Python and attracting key contributors that
would later be very important for the future of the language.
History of Python
• This resulted in a job offer to Guido by CNRI, a non-profit research
lab.
• This position helped Guido create a team of Python enthusiasts and
have support for releasing Python versions 1.3-1.6 and building
infrastructure like Python’s website and mailing list.
• In 1994, Python 1.0 was released with new features like lambda,
map, filter, and reduce.
• Python 2.0 added new features such as list comprehensions, garbage
collection systems.
• On December 3, 2008, Python 3.0 (also called "Py3K") was released.
It was designed to rectify the fundamental flaw of the language.
History of Python
Features of Python
• Python provides many useful features which make it popular and
valuable from the other programming languages. It supports object-
oriented programming, procedural programming approaches and
provides dynamic memory allocation. We have listed below a few
essential features.
1) Easy to Learn and Use
• Python is easy to learn as compared to other programming
languages. Its syntax is straightforward and much the same as the
English language. There is no use of the semicolon or curly-bracket,
the indentation defines the code block. It is the recommended
programming language for beginners.
2) Expressive Language
• Python can perform complex tasks using a few lines of code. A simple
example, the hello world program you simply type print("Hello
World"). It will take only one line to execute, while Java or C takes
multiple lines.
Features of Python
3) Interpreted Language
• Python is an interpreted language; it means the Python program is
executed one line at a time. The advantage of being interpreted
language, it makes debugging easy and portable.
4) Cross-platform Language
• Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a
portable language. It enables programmers to develop the software
for several competing platforms by writing a program only once.
5) Free and Open Source
• Python is freely available for everyone. It is freely available on its
official website www.python.org. It has a large community across the
world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python
community. The open-source means, "Anyone can download its
source code without paying any penny."
Features of Python
6) Object-Oriented Language
• Python supports object-oriented language and concepts of classes and
objects come into existence. It supports inheritance, polymorphism,
and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less
code.
7) Extensible
• It implies that other languages such as C/C++ can be used to compile
the code and thus it can be used further in our Python code. It
converts the program into byte code, and any platform can use that
byte code.
8) Large Standard Library
• It provides a vast range of libraries for the various fields such as
machine learning, web developer, and also for the scripting. There are
various machine learning libraries, such as Tensor flow, Pandas,
Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the
Features of Python
9) GUI Programming Support
• Graphical User Interface is used for the developing Desktop
application. PyQT5, Tkinter, Kivy are the libraries which are used for
developing the web application.
10) Integrated
• It can be easily integrated with languages like C, C++, and JAVA, etc.
Python runs code line by line like C,C++ Java. It makes easy to debug
the code.
11. Embeddable
• The code of the other programming language can use in the Python
source code. We can use Python source code in another programming
language as well. It can embed other language into our code.
12. Dynamic Memory Allocation
• In Python, we don't need to specify the data-type of the variable.
When we assign some value to the variable, it automatically allocates
the memory to the variable at run time.
Advantages of Python
1. Easy to Read, Learn and Write
• Python is a high-level programming language that has English-like
syntax. This makes it easier to read and understand the code.
• Python is really easy to pick up and learn, that is why a lot of people
recommend Python to beginners. You need less lines of code to
perform the same task as compared to other major languages
like C/C++ and Java.
2. Improved Productivity
• Python is a very productive language. Due to the simplicity of Python,
developers can focus on solving the problem. They don’t need to
spend too much time in understanding the syntax or behavior of the
programming language. You write less code and get more things done.
3. Interpreted Language
• Python is an interpreted language which means that Python
directly executes the code line by line. In case of any error, it stops
further execution and reports back the error which has occurred.
Advantages of Python
• Python shows only one error even if the program has multiple errors.
This makes debugging easier.
4. Dynamically Typed
• Python doesn’t know the type of variable until we run the code. It
automatically assigns the data type during execution. The
programmer doesn’t need to worry about declaring variables and their
data types.
5. Free and Open-Source
• Python comes under the OSI approved open-source license. This
makes it free to use and distribute. You can download the source
code, modify it and even distribute your version of Python. This is
useful for organizations that want to modify some specific behavior
and use their version for development.
Advantages of Python
6. Vast Libraries Support
• The standard library of Python is huge, you can find almost all the
functions needed for your task. So, you don’t have to depend on
external libraries.
• But even if you do, a Python package manager (pip) makes things
easier to import other great packages from the Python package index
(PyPi). It consists of over 200,000 packages.
7. Portability
• In many languages like C/C++, you need to change your code to run
the program on different platforms. That is not the same with Python.
You only write once and run it anywhere.
• However, you should be careful not to include any system-dependent
features.
Applications of Python
• GUI-based desktop applications
• Graphic design, image processing applications, Games, and Scientific/
computational Applications
• Web frameworks and applications
• Enterprise and Business applications
• Operating Systems
• Education
• Database Access
• Language Development
• Prototyping
• Software Development
Syntax of Python
• When we run a Python program, first it is read by a parser.
• The parser will only understand the Python code if it is according to
the predefined rules of Python programming otherwise it will give you
syntax errors.
• That is why it is important to understand the syntax of the language.
• Example of Python Syntax
• #Simple Python Program that compares two numbers.
print("Enter first integer value")
first_value = int(input())
print("Enter second integer value")
second_value = int(input())
if(first_value > second_value):
print(“First value is greater than second”)
else:
print(“Second value is greater than first”)
Types of Syntax Structures in Python
1. Python Line Structure
• A Python program is divided into logical lines where each line
comprises one or more physical lines of code. The Python interpreter
ignores the blank lines, which are the lines that only contain white
spaces.
Code:
• Msg = “Hi! Welcome to the python syntax article”
• print(Msg)
2. Multiline Statements
• If you have studied another language like C/C++ or Java then you are
used to writing semicolons after every statement.
• In Python, we don’t use semicolons instead of them we
use newlines for separating statements. Sometimes when you want
to write a long code in a single line we can break the statement into
multiple lines using the backslash character().
Types of Syntax Structures in Python
Code:
• print(“Hi! 
• How are you today? 
• What are you planning this Sunday? 
• ”)
3. Multiple Statements in One Line
• Python also allows you to write multiple statements in a single line.
For this purpose, we use semicolons to separate statements within the
same line.
• This can reduce the readability of code so only use this if it is
appropriate in the situation.
Code:
num1 = 10 ; num2 = 20 ; print(“Sum of numbers = ”, num1+num2)
Types of Syntax Structures in Python
4. Comments in Python
• Writing comments for our code is useful for programmers to
add notes or explanations of the code. Comments are just
for reading and Python interpreter ignores whatever we write in
comments. Comments can be either single-line or multiline
comments.
a. Single-Line Comments
• The symbol (#) indicates the starting of the comment and everything
written after the # is considered as comment.
b. Multiline Comments
• When the comment is large, we can use the triple-double quotes
(“””) to write comments in multiple lines.
Types of Syntax Structures in Python
5. Python Indentation
• The indentation is quite unique syntax of Python. Other languages like
C/C++, Java and JavaScript use curly braces ‘{}’ to indicate block of
codes.
• Python uses white spaces (space or tabs) to define the block of
functions, flow control and codes of class. It is mandatory to use a
consistent amount of spaces for blocks throughout the code.
Code:
name = “Vinod”
if name == “Vinod”:
print(“We know this person”)
else:
print(“We don’t know this person”)
Note: Here, the amount of space should be consistent otherwise you
will get an error.
Types of Syntax Structures in Python
Code:
name = “Vinod”
if name == “Vinod”:
print(“We know this person”)
print(“Unequal spaces in indentation”)
else:
print(“We don’t know this person”)
Output:
TabError: inconsistent use of tabs and spaces in indentation
Types of Syntax Structures in Python
6. Python Quotations
• The Python string literals can be enclosed in two ways.
• We can write strings between single quotes(’) or double quotes
(“) and they can be used interchangeably.
• message1 = “Hey”
• message2 = ‘Hey’
• When we want to use quotes inside the string then we
can combine them.
• print(“ Hey ‘Anna’ ”)
7. Python Identifier
• A program
contains variables, functions, classes, modules, packages etc.
• Identifier is the name given to these programming elements. There
are some rules which we have to keep in mind for creating an
identifier.
Types of Syntax Structures in Python
• Let’s see them one by one.
• Identifier can only begin with characters starting from A-Z (Uppercase
letters), a-z (lowercase letters) or _ (underscore).
• They can be then followed by any number of letters, digits or
underscores.
• Python is case sensitive language so the identifiers ‘count’ and ‘Count’
are two different identifiers.
• Python Reserved keywords like for, global, continue, break, etc. cannot
be used as identifiers.
• Examples of Valid Identifiers:
• Name , _3name6, get_all_names, YES
• Examples of Invalid Identifiers:
• 1name, name$, get-score
Types of Syntax Structures in Python
8. Getting Users Input
• To get the input from the user, Python has input() function in the
Python’s core library. It reads the input given by the user as
a string and we can store the input in a variable.
Code:
• Msg = input()
• print(Msg)
• When the interpreter reaches the input() function, it will wait for an
input from the user.
• The user can give input, for example, here we can type “Hello” and
then after pressing enter, the code will execute in which we store the
input in Msg variable and print it afterwards.
Types of Syntax Structures in Python
• One important thing to note is that even when you give a number as
input, Python will treat it as a string.
• So, when we want to work with numbers, we can use type conversion
methods with input() function to convert strings into numbers.
Code:
• num = int( input())
• num = num + 10
• print(num)
9. Python String-Formatters
• String-formatters are very useful for displaying strings in the format
we want. Let’s see the different ways of formatting string:
a. % operator
• With the % operator, we can format a string to contain
both text and values of identifiers. We use %s where we want our
value to appear.
Types of Syntax Structures in Python
• After the string, we put the % symbol and then mention the identifiers
in parameters.
Code:
• rollNo= 1
• subject= “Maths”
• print(“ The roll no. %s studies %s subject” % (rollNo, subject) )
Output:
• The roll no. 1 studies Maths subject
b. format Method
• The format method is similar to the above method but instead of %s
we put 0,1,2… values or identifiers in curly braces and then use
format method on the string.
Code:
• rollNo= 1 ; subject= “Maths”
• print(“ The roll no. {0} studies {1} subject”. format(rollNo, subject) )
Types of Syntax Structures in Python
• print((“ The roll no. {rollNo} studies {subject} subject”.format(rollNo=10,
subject=”Science”))
Output:
• The roll no. 1 studies Maths subject
The roll no. 10 studies Science subject
c. f-strings
• F-strings are easier to work with. You just need to put ‘f’ as
a prefix before string and then you can put the identifier in curly
braces within the string.
Code:
• rollNo= 5 ; subject= “Biology”
• print( f“The roll no. {rollNo} studies {subject} subject” )
Output:
• The roll no. 5 studies Biology subject
Data Types of Python
• Variables can hold values, and every value has a data-type.
• Python is a dynamically typed language; hence we do not need to
define the type of the variable while declaring it.
• The interpreter implicitly binds the value with its type.
• Python enables us to check the type of the variable used in the
program. Python provides us the type() function, which returns the
type of the variable passed.
• Consider the following example to define the values of different data
types and checking its type.
• a=10
• b="Hi Python"
• c = 10.5
• print(type(a))
• print(type(b))
• print(type(c))
Data Types of Python
• Python provides various standard data types that define the storage
method on each of them.
• The data types defined in Python are given below.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary
Data Types of Python
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.
• Let's see a simple example of the tuple.
• tup = ("hi", "Python", 2)
• print (type(tup)) # Checking type of tup
• print (tup) #Printing the tuple
• print (tup[1:]) # Tuple slicing
• print (tup[0:1])
• print (tup + tup) # Tuple concatenation using + operator
• print (tup * 3) # Tuple repeatation using * operator
• t[2] = "hi" # Adding value to tup. It will throw an error.
Data Types of Python
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 {}.
• Consider the following example.
• d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
• print (d) # Printing dictionary
• print("1st name is "+d[1]) # Accesing value using keys
• print("2nd name is "+ d[4])
• print (d.keys())
• print (d.values())
Data Types of Python
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'.
• Consider the following example.
• # Python program to check the boolean type
• print(type(True))
• print(type(False))
• print(false)
Data Types of Python
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(), or a sequence of elements is passed in the curly braces
and separated by the comma. It can contain various types of values.
Consider the following example.
• set1 = set() # Creating Empty set
• set2 = {'James', 2, 3,'Python'}
• print(set2) #Printing Set value
• # Adding element to the set
• set2.add(10)
• print(set2)
• set2.remove(2) #Removing element from the set
• print(set2)
Console input and output
• Programs often need to obtain data from the user, usually by way of
input from the keyboard.
• One way to accomplish this in Python is with input():
• input([<prompt>])
• Reads a line from the keyboard.
• The input() function pauses program execution to allow the user to
type in a line of input from the keyboard.
• Once the user presses the Enter key, all characters typed are read and
returned as a string.
• You can display program data to the console in Python with print().
• To display objects to the console, pass them as a comma-separated list
of arguments to print().
• print(<obj>, ..., <obj>)
• Displays a string representation of each <obj> to the console.
Console input and output
• input() always returns a string. If you want a numeric type, then you
need to convert the string to the appropriate type with the built-
in int(), float(), or complex() function:
• Example:
• number = input("Enter a number: ")
• Enter a number: 50
• print(number + 100)
• Traceback (most recent call last):
• File "<stdin>", line 1, in <module>
• TypeError: must be str, not int
• number = int(input("Enter a number: "))
• Enter a number: 50
• print(number + 100)
• 150
Control Structure
• Decision making is the most important aspect of almost all the
programming languages. As the name implies, decision making allows
us to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions.
Condition checking is the backbone of decision making.
• In python, decision making is performed by the following statements.
Statement Description
If Statement The if statement is used to test a specific condition. If the
condition is true, a block of code (if-block) will be executed.
If - else Statement The if-else statement is similar to if statement except the fact
that, it also provides the block of the code for the false case of
the condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.
Nested if
Statement
Nested if statements enable us to use if ? else statement inside
an outer if statement.
Control Structure
Indentation in Python
• For the ease of programming and to achieve simplicity, python doesn't
allow the use of parentheses for the block level code.
• In Python, indentation is used to declare a block. If two statements are
at the same indentation level, then they are the part of the same
block.
• Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
• Indentation is the most used part of the python language since it
declares the block of code.
• All the statements of one block are intended at the same level
indentation.
• We will see how the actual indentation takes place in decision making
and other stuff in python.
Control Structure
The if statement
• The if statement is used to test a particular condition and if the
condition is true, it executes a block of code known as if-block. The
condition of if statement can be any valid logical expression which can
be either evaluated to true or false.
Example : Program to print the largest of the three numbers.
• a = int(input("Enter a? "));
• b = int(input("Enter b? "));
• c = int(input("Enter c? "));
• if a>b and a>c:
• print("a is largest");
• if b>a and b>c:
• print("b is largest");
• if c>a and c>b:
• print("c is largest");
Control Structure
The if-else statement
• The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
• If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
• Example: Program to check whether a number is even or not.
• num = int(input("enter the number?"))
• if num%2 == 0:
• print("Number is even...")
• else:
• print("Number is odd...")
Control Structure
The elif statement
• The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the true
condition among them. We can have any number of elif statements in
our program depending upon our need. However, using elif is
optional.
• The elif statement works like an if-else-if ladder statement in C. It must
be succeeded by an if statement.
• Example:
• number = int(input("Enter the number?"))
• if number==10:
• print("number is equals to 10")
• elif number==50:
• print("number is equal to 50");
• else:
• print("number is not equal to 10, 50 or 100");
Control Structure: loops
• The flow of the programs written in any programming language is
sequential by default. Sometimes we may need to alter the flow of the
program. The execution of a specific code may need to be repeated
several numbers of times.
• For this purpose, The programming languages provide various types of
loops which are capable of repeating some specific code several
numbers of times.
Loop
Statement
Description
for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested loop. It
is better to use for loop if the number of iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
do-while
loop
The do-while loop continues until a given condition satisfies. It is also called post
tested loop. It is used when it is necessary to execute the loop at least once (mostly
menu driven programs).
Control Structure: loops
• In Python, the for loop is often used to iterate over iterable objects
such as lists, tuples, or strings.
• Traversal is the process of iterating across a series. If we have a section
of code that we would like to repeat a certain number of times, we
employ for loops.
• The for-loop is usually used on an iterable object such as a list or the
in-built range function.
• The for statement in Python traverses through the elements of a
series, running the block of code each time.
Syntax of for Loop
• for value in sequence:
• {loop body}
On each iteration, the value is the parameter that gets the element's
value within the iterable sequence. If an expression statement is present in
a sequence, it is processed first. The iterating variable iterating_variable is
then allocated to the first element in the sequence. After that, the intended
Control Structure: loops
• Example:
• # Code to find the sum of squares of each element of the list using for
loop
• # creating the list of numbers
• numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
• # initializing a variable that will store the sum
• sum_ = 0
• # using for loop to iterate over the list
• for num in numbers:
• sum_ = sum_ + num ** 2
print("The sum of squares is: ", sum_)
Control Structure: loops
The range() Function
• Because the "range" function appears so frequently in for loops, we
might mistakenly believe the range is a component of the syntax of for
loop. It isn't: it's a Python built-in method that provides a series that
follows a specified pattern (usually serial integers), fulfilling the criteria
of giving a series for the for expression to run over. There is no
necessity to count because for can act straight on sequences most of
the time. If they're coming from some other language with distinctive
loop syntax, this is a frequent novice construct:
• Code
• my_list = [3, 5, 6, 8, 4]
• for iter_var in range( len( my_list ) ):
my_list.append(my_list[iter_var] + 2)
print( my_list )
• Output:
[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]
Control Structure: loops
Iterating by Using Index of Sequence
• Another method of iterating through every item is to use an index
offset within the sequence. Here's a simple illustration:
• Code
• # Code to find the sum of squares of each element of the list using for
loop
• # creating the list of numbers
• numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
• # initializing a variable that will store the sum
• sum_ = 0
• # using for loop to iterate over list
• for num in range( len(numbers) ):
• sum_ = sum_ + numbers[num] ** 2
print("The sum of squares is: ", sum_)
Control Structure: loops
Nested Loops
• If we have a piece of script that we want to run a number of times and
then another piece of script inside that script that we want to run B
number of times, we employ a "nested loop." When working with an
iterable in the lists, these are widely utilized in Python.
• Code
• import random
• numbers = [ ]
• for val in range(0, 11):
• numbers.append( random.randint( 0, 11 ) )
• for num in range( 0, 11 ):
• for i in numbers:
• if num == i:
• print( num, end = " " )
Control Structure: loops
Python While loop
• The Python while loop allows a part of the code to be executed until
the given condition returns false. It is also known as a pre-tested loop.
• It can be viewed as a repeating if statement. When we don't know the
number of iterations then the while loop is most effective to use.
• The syntax is given below.
• while expression:
• statements
• Here, the statements can be a single statement or a group of
statements. The expression should be any valid Python expression
resulting in true or false. The true is any non-zero value and false is 0.
• Python offers the following control statement to use within the while
loop.
• 1. Continue Statement - When the continue statement is
encountered, the control transfer to the beginning of the loop. Let's
understand the following example.
Control Structure: loops
Example:
• # prints all letters except 'a' and 't'
• i = 0
• str1 = 'javatpoint'
•
• while i < len(str1):
• if str1[i] == 'a' or str1[i] == 't':
• i += 1
• continue
• print('Current Letter :', a[i])
• i += 1
Control Structure: loops
2. Break Statement - When the break statement is encountered, it
brings control out of the loop.
Example:
• # The control transfer is transfered
• # when break statement soon it sees t
• i = 0
• str1 = 'javatpoint'
•
• while i < len(str1):
• if str1[i] == 't':
• i += 1
• break
• print('Current Letter :', str1[i])
• i += 1
Control Structure: loops
3. Pass Statement - The pass statement is used to declare the empty
loop. It is also used to define empty class, function, and control
statement. Let's understand the following example.
Example -
• # An empty loop
• str1 = 'javatpoint'
• i = 0
•
• while i < len(str1):
• i += 1
• pass
• print('Value of i :', i)
Control Structure: loops
Infinite while loop
• If the condition is given in the while loop never becomes false, then
the while loop will never terminate, and it turns into the infinite while
loop.
• Any non-zero value in the while loop indicates an always-
true condition, whereas zero indicates the always-false condition. This
type of approach is useful if we want our program to run continuously
in the loop without any disturbance.
Example
• while (1):
• print("Hi! we are inside the infinite while loop")
Control Structure: loops
Using else with while loop
• Python allows us to use the else statement with the while loop also.
The else block is executed when the condition given in the while
statement becomes false. Like for loop, if the while loop is broken
using break statement, then the else block will not be executed, and
the statement present after else block will be executed. The else
statement is optional to use with the while loop. Consider the
following example.
Example
• i=1
• while(i<=5):
• print(i)
• i=i+1
• else:
• print("The while loop exhausted")
•
Control Structure: loops
Continue vs. Pass
• Usually, there is some confusion in the pass and continue keywords.
So here are the differences between these two.
Headings continue pass
Definition The continue statement is utilized to skip
the current loop's remaining statements, go
to the following iteration, and return control
to the beginning.
The pass keyword is used when a phrase is
necessary syntactically to be placed but not to
be executed.
Action It takes the control back to the start of the
loop.
Nothing happens if the Python interpreter
encounters the pass statement.
Application It works with both the Python while and
Python for loops.
It performs nothing; hence it is a null operation.
Syntax It has the following syntax: -: continue Its syntax is as follows:- pass
Interpretation It's mostly utilized within a loop's condition. During the byte-compile stage, the pass
keyword is removed.
Disadvantages of Python
1. Slow Speed
• We discussed above that Python is an interpreted language
and dynamically-typed language. The line by line execution of code
often leads to slow execution.
• The dynamic nature of Python is also responsible for the slow
speed of Python because it has to do the extra work while executing
code. So, Python is not used for purposes where speed is an important
aspect of the project.
2. Not Memory Efficient
• To provide simplicity to the developer, Python has to do a little
tradeoff.
• The Python programming language uses a large amount of memory.
This can be a disadvantage while building applications when we prefer
memory optimization.
Disadvantages of Python
3. Weak in Mobile Computing
• Python is generally used in server-side programming. We don’t get to
see Python on the client-side or mobile applications because of the
following reasons. Python is not memory efficient and it has slow
processing power as compared to other languages.
4. Database Access
• Programming in Python is easy and stress-free. But when we are
interacting with the database, it lacks behind.
• The Python’s database access layer is primitive and underdeveloped in
comparison to the popular technologies like JDBC and ODBC.
• Huge enterprises need smooth interaction of complex legacy data and
Python is thus rarely used in enterprises.
Disadvantages of Python
5. Runtime Errors
• As we know Python is a dynamically typed language so the data type
of a variable can change anytime. A variable containing integer
number may hold a string in the future, which can lead to Runtime
Errors.
• Therefore Python programmers need to perform thorough testing of
the applications.
Conclusion
• https://www.softwaretestinghelp.com/python/
• https://techvidvan.com/tutorials/python-advantages-and-
disadvantages/
• https://www.javatpoint.com/python-data-types
• https://www.programiz.com/python-programming/first-program
• https://www.learnpython.org/
• https://www.studytonight.com/python/introduction-to-idle

More Related Content

PPT
Python Programming Language
PPTX
introduction to Python (for beginners)
PDF
Python final ppt
PDF
Investigatory project on fertilizer
PPT
Function overloading(c++)
PPTX
Phython Programming Language
DOCX
IP Final project 12th
DOCX
Hindi project FILE CBSE class 12
Python Programming Language
introduction to Python (for beginners)
Python final ppt
Investigatory project on fertilizer
Function overloading(c++)
Phython Programming Language
IP Final project 12th
Hindi project FILE CBSE class 12

What's hot (20)

PDF
Learn 90% of Python in 90 Minutes
PPTX
Python and its Applications
PPT
Maths Project 11 class(SETS)
DOCX
Computer Science Practical File class XII
PDF
Python and MySQL Linking Class 12th Project File 23-24
DOC
Final project report format
PPTX
Computer System Overview Class XI CS
PPTX
Number System
PPTX
Introduction to python
PPTX
Deque and its applications
PPTX
Looping statement in python
PPT
1.python interpreter and interactive mode
PDF
HCL Experience Letter
PDF
Physics Practical File - with Readings | Class 12 CBSE
PPTX
Python
PPT
c++ programming language Lecture 1-3.ppt
PPTX
Introduction to python for Beginners
PPTX
Preprocessor directives in c language
Learn 90% of Python in 90 Minutes
Python and its Applications
Maths Project 11 class(SETS)
Computer Science Practical File class XII
Python and MySQL Linking Class 12th Project File 23-24
Final project report format
Computer System Overview Class XI CS
Number System
Introduction to python
Deque and its applications
Looping statement in python
1.python interpreter and interactive mode
HCL Experience Letter
Physics Practical File - with Readings | Class 12 CBSE
Python
c++ programming language Lecture 1-3.ppt
Introduction to python for Beginners
Preprocessor directives in c language
Ad

Similar to Python.pptx (20)

PPTX
Introduction to python
PPTX
Introduction to Python.pptx
PPTX
PYTHON UNIT 1
PPTX
Python programming ppt.pptx
PPTX
Introduction to Python Programming Basics
PPTX
Features of python.pptx
PPTX
Python Course in Delhi and its Applications.pptx
PPTX
Python programming
PPT
Python Programming Unit1_Aditya College of Engg & Tech
PDF
What is Python ? Why its important ? Institute for Python Course.
DOCX
Python Applications by The Knowledge Academy.docx
PPTX
Python Way of Program is a topic for beginners
PPTX
Python Way of Program is a topic for beginners
PDF
COMPUTER 8 Grade 8 - Intro to Python.pdf
PPT
Python Introduction.ppt
PDF
Presentation (1).pdf
DOCX
Python notes for beginners - in simple sentences
PPTX
PYTHON TUTORIALS.pptx
PDF
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
PPTX
Introduction to python
Introduction to Python.pptx
PYTHON UNIT 1
Python programming ppt.pptx
Introduction to Python Programming Basics
Features of python.pptx
Python Course in Delhi and its Applications.pptx
Python programming
Python Programming Unit1_Aditya College of Engg & Tech
What is Python ? Why its important ? Institute for Python Course.
Python Applications by The Knowledge Academy.docx
Python Way of Program is a topic for beginners
Python Way of Program is a topic for beginners
COMPUTER 8 Grade 8 - Intro to Python.pdf
Python Introduction.ppt
Presentation (1).pdf
Python notes for beginners - in simple sentences
PYTHON TUTORIALS.pptx
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Ad

Recently uploaded (20)

PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Pre independence Education in Inndia.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Business Ethics Teaching Materials for college
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Microbial disease of the cardiovascular and lymphatic systems
FourierSeries-QuestionsWithAnswers(Part-A).pdf
human mycosis Human fungal infections are called human mycosis..pptx
Open Quiz Monsoon Mind Game Prelims.pptx
Cardiovascular Pharmacology for pharmacy students.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
01-Introduction-to-Information-Management.pdf
PPH.pptx obstetrics and gynecology in nursing
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Abdominal Access Techniques with Prof. Dr. R K Mishra
Pre independence Education in Inndia.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
TR - Agricultural Crops Production NC III.pdf
The Final Stretch: How to Release a Game and Not Die in the Process.
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Business Ethics Teaching Materials for college
Renaissance Architecture: A Journey from Faith to Humanism
Microbial disease of the cardiovascular and lymphatic systems

Python.pptx

  • 2. History of Python • Python is a language that’s focused on simplicity and ease of use. It’s multiparadigm, allowing programmers to write code in object- oriented, structural, or functional programming styles. • Today, it’s widely used in multiple fields, such as machine learning (frameworks like TensorFlow and Keras) and web development. After JavaScript, it is the most used programming language in the world. • Like today’s most popular languages such as C and Java, Python has a long history behind it. • The main person accompanying us on our journey will be Guido van Rossum. • Guido is the main creator of the language.
  • 3. History of Python • Source: https://exyte.com/blog/a-brief-history-of-python
  • 4. • In 1989, Van Rossum was working on Amoeba, a microkernel-based distributed system, for which he was developing system utilities. • While working on them, Guido realized that developing in C takes too much time. He decided to spend his free time building a language that would help him accomplish his work faster. • He had an idea of a scripting language that would be somewhere between C and a shell script: interpreted, but much more easily programmable and readable than shell scripts. • As you probably have guessed, that language turned out to be Python. • A fun fact: Python is not named after the snake species, but after the British surreal comedy troupe Monty Python. History of Python
  • 5. • In February 1991, Van Rossum published the source code of Python’s interpreter to alt.sources, a Usenet group for open-source code. While this may seem to be a regular thing—nowadays, basically all the programming languages are open-source and on GitHub—back then, it was still unclear what would be the business model of people developing the languages. • For example, there were proprietary languages, but it was hard for those to become popular. • Guido has said that open-sourcing Python was one of the things that significantly helped it succeed at that time. • The first release (0.9.0) had features such as classes, exception handling, functions, and the core datatypes like list, dict, str, and so on. • It was heavily inspired by ABC, a language that Guido spent some time implementing at CWI. While creating Python, his goal was to take the good parts of ABC while fixing the rest. History of Python
  • 6. • In January 1994, version 1.0 was released, and a separate Usenet group for it was created, marking a milestone in the history of Python. • Around that time, multiple other dynamically typed and interpreted languages similar to Python were created, such as Perl and Ruby, which shows that the need for such a language was definitely in the air. • In 1994, Guido was invited to the USA by NIST, the US National Institute for Standards and Technology. • NIST was interested in using Python for several standards-related projects and needed somebody to boost their Python skills. Obviously, the creator of language was a great choice. • With NIST support, Guido was able to run workshops and participate in conferences, spreading Python and attracting key contributors that would later be very important for the future of the language. History of Python
  • 7. • This resulted in a job offer to Guido by CNRI, a non-profit research lab. • This position helped Guido create a team of Python enthusiasts and have support for releasing Python versions 1.3-1.6 and building infrastructure like Python’s website and mailing list. • In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce. • Python 2.0 added new features such as list comprehensions, garbage collection systems. • On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental flaw of the language. History of Python
  • 8. Features of Python • Python provides many useful features which make it popular and valuable from the other programming languages. It supports object- oriented programming, procedural programming approaches and provides dynamic memory allocation. We have listed below a few essential features. 1) Easy to Learn and Use • Python is easy to learn as compared to other programming languages. Its syntax is straightforward and much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended programming language for beginners. 2) Expressive Language • Python can perform complex tasks using a few lines of code. A simple example, the hello world program you simply type print("Hello World"). It will take only one line to execute, while Java or C takes multiple lines.
  • 9. Features of Python 3) Interpreted Language • Python is an interpreted language; it means the Python program is executed one line at a time. The advantage of being interpreted language, it makes debugging easy and portable. 4) Cross-platform Language • Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables programmers to develop the software for several competing platforms by writing a program only once. 5) Free and Open Source • Python is freely available for everyone. It is freely available on its official website www.python.org. It has a large community across the world that is dedicatedly working towards make new python modules and functions. Anyone can contribute to the Python community. The open-source means, "Anyone can download its source code without paying any penny."
  • 10. Features of Python 6) Object-Oriented Language • Python supports object-oriented language and concepts of classes and objects come into existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to programmer to write reusable code and develop applications in less code. 7) Extensible • It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further in our Python code. It converts the program into byte code, and any platform can use that byte code. 8) Large Standard Library • It provides a vast range of libraries for the various fields such as machine learning, web developer, and also for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the
  • 11. Features of Python 9) GUI Programming Support • Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for developing the web application. 10) Integrated • It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to debug the code. 11. Embeddable • The code of the other programming language can use in the Python source code. We can use Python source code in another programming language as well. It can embed other language into our code. 12. Dynamic Memory Allocation • In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable, it automatically allocates the memory to the variable at run time.
  • 12. Advantages of Python 1. Easy to Read, Learn and Write • Python is a high-level programming language that has English-like syntax. This makes it easier to read and understand the code. • Python is really easy to pick up and learn, that is why a lot of people recommend Python to beginners. You need less lines of code to perform the same task as compared to other major languages like C/C++ and Java. 2. Improved Productivity • Python is a very productive language. Due to the simplicity of Python, developers can focus on solving the problem. They don’t need to spend too much time in understanding the syntax or behavior of the programming language. You write less code and get more things done. 3. Interpreted Language • Python is an interpreted language which means that Python directly executes the code line by line. In case of any error, it stops further execution and reports back the error which has occurred.
  • 13. Advantages of Python • Python shows only one error even if the program has multiple errors. This makes debugging easier. 4. Dynamically Typed • Python doesn’t know the type of variable until we run the code. It automatically assigns the data type during execution. The programmer doesn’t need to worry about declaring variables and their data types. 5. Free and Open-Source • Python comes under the OSI approved open-source license. This makes it free to use and distribute. You can download the source code, modify it and even distribute your version of Python. This is useful for organizations that want to modify some specific behavior and use their version for development.
  • 14. Advantages of Python 6. Vast Libraries Support • The standard library of Python is huge, you can find almost all the functions needed for your task. So, you don’t have to depend on external libraries. • But even if you do, a Python package manager (pip) makes things easier to import other great packages from the Python package index (PyPi). It consists of over 200,000 packages. 7. Portability • In many languages like C/C++, you need to change your code to run the program on different platforms. That is not the same with Python. You only write once and run it anywhere. • However, you should be careful not to include any system-dependent features.
  • 15. Applications of Python • GUI-based desktop applications • Graphic design, image processing applications, Games, and Scientific/ computational Applications • Web frameworks and applications • Enterprise and Business applications • Operating Systems • Education • Database Access • Language Development • Prototyping • Software Development
  • 16. Syntax of Python • When we run a Python program, first it is read by a parser. • The parser will only understand the Python code if it is according to the predefined rules of Python programming otherwise it will give you syntax errors. • That is why it is important to understand the syntax of the language. • Example of Python Syntax • #Simple Python Program that compares two numbers. print("Enter first integer value") first_value = int(input()) print("Enter second integer value") second_value = int(input()) if(first_value > second_value): print(“First value is greater than second”) else: print(“Second value is greater than first”)
  • 17. Types of Syntax Structures in Python 1. Python Line Structure • A Python program is divided into logical lines where each line comprises one or more physical lines of code. The Python interpreter ignores the blank lines, which are the lines that only contain white spaces. Code: • Msg = “Hi! Welcome to the python syntax article” • print(Msg) 2. Multiline Statements • If you have studied another language like C/C++ or Java then you are used to writing semicolons after every statement. • In Python, we don’t use semicolons instead of them we use newlines for separating statements. Sometimes when you want to write a long code in a single line we can break the statement into multiple lines using the backslash character().
  • 18. Types of Syntax Structures in Python Code: • print(“Hi! • How are you today? • What are you planning this Sunday? • ”) 3. Multiple Statements in One Line • Python also allows you to write multiple statements in a single line. For this purpose, we use semicolons to separate statements within the same line. • This can reduce the readability of code so only use this if it is appropriate in the situation. Code: num1 = 10 ; num2 = 20 ; print(“Sum of numbers = ”, num1+num2)
  • 19. Types of Syntax Structures in Python 4. Comments in Python • Writing comments for our code is useful for programmers to add notes or explanations of the code. Comments are just for reading and Python interpreter ignores whatever we write in comments. Comments can be either single-line or multiline comments. a. Single-Line Comments • The symbol (#) indicates the starting of the comment and everything written after the # is considered as comment. b. Multiline Comments • When the comment is large, we can use the triple-double quotes (“””) to write comments in multiple lines.
  • 20. Types of Syntax Structures in Python 5. Python Indentation • The indentation is quite unique syntax of Python. Other languages like C/C++, Java and JavaScript use curly braces ‘{}’ to indicate block of codes. • Python uses white spaces (space or tabs) to define the block of functions, flow control and codes of class. It is mandatory to use a consistent amount of spaces for blocks throughout the code. Code: name = “Vinod” if name == “Vinod”: print(“We know this person”) else: print(“We don’t know this person”) Note: Here, the amount of space should be consistent otherwise you will get an error.
  • 21. Types of Syntax Structures in Python Code: name = “Vinod” if name == “Vinod”: print(“We know this person”) print(“Unequal spaces in indentation”) else: print(“We don’t know this person”) Output: TabError: inconsistent use of tabs and spaces in indentation
  • 22. Types of Syntax Structures in Python 6. Python Quotations • The Python string literals can be enclosed in two ways. • We can write strings between single quotes(’) or double quotes (“) and they can be used interchangeably. • message1 = “Hey” • message2 = ‘Hey’ • When we want to use quotes inside the string then we can combine them. • print(“ Hey ‘Anna’ ”) 7. Python Identifier • A program contains variables, functions, classes, modules, packages etc. • Identifier is the name given to these programming elements. There are some rules which we have to keep in mind for creating an identifier.
  • 23. Types of Syntax Structures in Python • Let’s see them one by one. • Identifier can only begin with characters starting from A-Z (Uppercase letters), a-z (lowercase letters) or _ (underscore). • They can be then followed by any number of letters, digits or underscores. • Python is case sensitive language so the identifiers ‘count’ and ‘Count’ are two different identifiers. • Python Reserved keywords like for, global, continue, break, etc. cannot be used as identifiers. • Examples of Valid Identifiers: • Name , _3name6, get_all_names, YES • Examples of Invalid Identifiers: • 1name, name$, get-score
  • 24. Types of Syntax Structures in Python 8. Getting Users Input • To get the input from the user, Python has input() function in the Python’s core library. It reads the input given by the user as a string and we can store the input in a variable. Code: • Msg = input() • print(Msg) • When the interpreter reaches the input() function, it will wait for an input from the user. • The user can give input, for example, here we can type “Hello” and then after pressing enter, the code will execute in which we store the input in Msg variable and print it afterwards.
  • 25. Types of Syntax Structures in Python • One important thing to note is that even when you give a number as input, Python will treat it as a string. • So, when we want to work with numbers, we can use type conversion methods with input() function to convert strings into numbers. Code: • num = int( input()) • num = num + 10 • print(num) 9. Python String-Formatters • String-formatters are very useful for displaying strings in the format we want. Let’s see the different ways of formatting string: a. % operator • With the % operator, we can format a string to contain both text and values of identifiers. We use %s where we want our value to appear.
  • 26. Types of Syntax Structures in Python • After the string, we put the % symbol and then mention the identifiers in parameters. Code: • rollNo= 1 • subject= “Maths” • print(“ The roll no. %s studies %s subject” % (rollNo, subject) ) Output: • The roll no. 1 studies Maths subject b. format Method • The format method is similar to the above method but instead of %s we put 0,1,2… values or identifiers in curly braces and then use format method on the string. Code: • rollNo= 1 ; subject= “Maths” • print(“ The roll no. {0} studies {1} subject”. format(rollNo, subject) )
  • 27. Types of Syntax Structures in Python • print((“ The roll no. {rollNo} studies {subject} subject”.format(rollNo=10, subject=”Science”)) Output: • The roll no. 1 studies Maths subject The roll no. 10 studies Science subject c. f-strings • F-strings are easier to work with. You just need to put ‘f’ as a prefix before string and then you can put the identifier in curly braces within the string. Code: • rollNo= 5 ; subject= “Biology” • print( f“The roll no. {rollNo} studies {subject} subject” ) Output: • The roll no. 5 studies Biology subject
  • 28. Data Types of Python • Variables can hold values, and every value has a data-type. • Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. • The interpreter implicitly binds the value with its type. • Python enables us to check the type of the variable used in the program. Python provides us the type() function, which returns the type of the variable passed. • Consider the following example to define the values of different data types and checking its type. • a=10 • b="Hi Python" • c = 10.5 • print(type(a)) • print(type(b)) • print(type(c))
  • 29. Data Types of Python • Python provides various standard data types that define the storage method on each of them. • The data types defined in Python are given below. • Numbers • Sequence Type • Boolean • Set • Dictionary
  • 30. Data Types of Python 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. • Let's see a simple example of the tuple. • tup = ("hi", "Python", 2) • print (type(tup)) # Checking type of tup • print (tup) #Printing the tuple • print (tup[1:]) # Tuple slicing • print (tup[0:1]) • print (tup + tup) # Tuple concatenation using + operator • print (tup * 3) # Tuple repeatation using * operator • t[2] = "hi" # Adding value to tup. It will throw an error.
  • 31. Data Types of Python 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 {}. • Consider the following example. • d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'} • print (d) # Printing dictionary • print("1st name is "+d[1]) # Accesing value using keys • print("2nd name is "+ d[4]) • print (d.keys()) • print (d.values())
  • 32. Data Types of Python 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'. • Consider the following example. • # Python program to check the boolean type • print(type(True)) • print(type(False)) • print(false)
  • 33. Data Types of Python 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(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various types of values. Consider the following example. • set1 = set() # Creating Empty set • set2 = {'James', 2, 3,'Python'} • print(set2) #Printing Set value • # Adding element to the set • set2.add(10) • print(set2) • set2.remove(2) #Removing element from the set • print(set2)
  • 34. Console input and output • Programs often need to obtain data from the user, usually by way of input from the keyboard. • One way to accomplish this in Python is with input(): • input([<prompt>]) • Reads a line from the keyboard. • The input() function pauses program execution to allow the user to type in a line of input from the keyboard. • Once the user presses the Enter key, all characters typed are read and returned as a string. • You can display program data to the console in Python with print(). • To display objects to the console, pass them as a comma-separated list of arguments to print(). • print(<obj>, ..., <obj>) • Displays a string representation of each <obj> to the console.
  • 35. Console input and output • input() always returns a string. If you want a numeric type, then you need to convert the string to the appropriate type with the built- in int(), float(), or complex() function: • Example: • number = input("Enter a number: ") • Enter a number: 50 • print(number + 100) • Traceback (most recent call last): • File "<stdin>", line 1, in <module> • TypeError: must be str, not int • number = int(input("Enter a number: ")) • Enter a number: 50 • print(number + 100) • 150
  • 36. Control Structure • Decision making is the most important aspect of almost all the programming languages. As the name implies, decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made on the validity of the particular conditions. Condition checking is the backbone of decision making. • In python, decision making is performed by the following statements. Statement Description If Statement The if statement is used to test a specific condition. If the condition is true, a block of code (if-block) will be executed. If - else Statement The if-else statement is similar to if statement except the fact that, it also provides the block of the code for the false case of the condition to be checked. If the condition provided in the if statement is false, then the else statement will be executed. Nested if Statement Nested if statements enable us to use if ? else statement inside an outer if statement.
  • 37. Control Structure Indentation in Python • For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the block level code. • In Python, indentation is used to declare a block. If two statements are at the same indentation level, then they are the part of the same block. • Generally, four spaces are given to indent the statements which are a typical amount of indentation in python. • Indentation is the most used part of the python language since it declares the block of code. • All the statements of one block are intended at the same level indentation. • We will see how the actual indentation takes place in decision making and other stuff in python.
  • 38. Control Structure The if statement • The if statement is used to test a particular condition and if the condition is true, it executes a block of code known as if-block. The condition of if statement can be any valid logical expression which can be either evaluated to true or false. Example : Program to print the largest of the three numbers. • a = int(input("Enter a? ")); • b = int(input("Enter b? ")); • c = int(input("Enter c? ")); • if a>b and a>c: • print("a is largest"); • if b>a and b>c: • print("b is largest"); • if c>a and c>b: • print("c is largest");
  • 39. Control Structure The if-else statement • The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition. • If the condition is true, then the if-block is executed. Otherwise, the else-block is executed. • Example: Program to check whether a number is even or not. • num = int(input("enter the number?")) • if num%2 == 0: • print("Number is even...") • else: • print("Number is odd...")
  • 40. Control Structure The elif statement • The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. We can have any number of elif statements in our program depending upon our need. However, using elif is optional. • The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement. • Example: • number = int(input("Enter the number?")) • if number==10: • print("number is equals to 10") • elif number==50: • print("number is equal to 50"); • else: • print("number is not equal to 10, 50 or 100");
  • 41. Control Structure: loops • The flow of the programs written in any programming language is sequential by default. Sometimes we may need to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of times. • For this purpose, The programming languages provide various types of loops which are capable of repeating some specific code several numbers of times. Loop Statement Description for loop The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. while loop The while loop is to be used in the scenario where we don't know the number of iterations in advance. The block of statements is executed in the while loop until the condition specified in the while loop is satisfied. It is also called a pre-tested loop. do-while loop The do-while loop continues until a given condition satisfies. It is also called post tested loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).
  • 42. Control Structure: loops • In Python, the for loop is often used to iterate over iterable objects such as lists, tuples, or strings. • Traversal is the process of iterating across a series. If we have a section of code that we would like to repeat a certain number of times, we employ for loops. • The for-loop is usually used on an iterable object such as a list or the in-built range function. • The for statement in Python traverses through the elements of a series, running the block of code each time. Syntax of for Loop • for value in sequence: • {loop body} On each iteration, the value is the parameter that gets the element's value within the iterable sequence. If an expression statement is present in a sequence, it is processed first. The iterating variable iterating_variable is then allocated to the first element in the sequence. After that, the intended
  • 43. Control Structure: loops • Example: • # Code to find the sum of squares of each element of the list using for loop • # creating the list of numbers • numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8] • # initializing a variable that will store the sum • sum_ = 0 • # using for loop to iterate over the list • for num in numbers: • sum_ = sum_ + num ** 2 print("The sum of squares is: ", sum_)
  • 44. Control Structure: loops The range() Function • Because the "range" function appears so frequently in for loops, we might mistakenly believe the range is a component of the syntax of for loop. It isn't: it's a Python built-in method that provides a series that follows a specified pattern (usually serial integers), fulfilling the criteria of giving a series for the for expression to run over. There is no necessity to count because for can act straight on sequences most of the time. If they're coming from some other language with distinctive loop syntax, this is a frequent novice construct: • Code • my_list = [3, 5, 6, 8, 4] • for iter_var in range( len( my_list ) ): my_list.append(my_list[iter_var] + 2) print( my_list ) • Output: [3, 5, 6, 8, 4, 5, 7, 8, 10, 6]
  • 45. Control Structure: loops Iterating by Using Index of Sequence • Another method of iterating through every item is to use an index offset within the sequence. Here's a simple illustration: • Code • # Code to find the sum of squares of each element of the list using for loop • # creating the list of numbers • numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8] • # initializing a variable that will store the sum • sum_ = 0 • # using for loop to iterate over list • for num in range( len(numbers) ): • sum_ = sum_ + numbers[num] ** 2 print("The sum of squares is: ", sum_)
  • 46. Control Structure: loops Nested Loops • If we have a piece of script that we want to run a number of times and then another piece of script inside that script that we want to run B number of times, we employ a "nested loop." When working with an iterable in the lists, these are widely utilized in Python. • Code • import random • numbers = [ ] • for val in range(0, 11): • numbers.append( random.randint( 0, 11 ) ) • for num in range( 0, 11 ): • for i in numbers: • if num == i: • print( num, end = " " )
  • 47. Control Structure: loops Python While loop • The Python while loop allows a part of the code to be executed until the given condition returns false. It is also known as a pre-tested loop. • It can be viewed as a repeating if statement. When we don't know the number of iterations then the while loop is most effective to use. • The syntax is given below. • while expression: • statements • Here, the statements can be a single statement or a group of statements. The expression should be any valid Python expression resulting in true or false. The true is any non-zero value and false is 0. • Python offers the following control statement to use within the while loop. • 1. Continue Statement - When the continue statement is encountered, the control transfer to the beginning of the loop. Let's understand the following example.
  • 48. Control Structure: loops Example: • # prints all letters except 'a' and 't' • i = 0 • str1 = 'javatpoint' • • while i < len(str1): • if str1[i] == 'a' or str1[i] == 't': • i += 1 • continue • print('Current Letter :', a[i]) • i += 1
  • 49. Control Structure: loops 2. Break Statement - When the break statement is encountered, it brings control out of the loop. Example: • # The control transfer is transfered • # when break statement soon it sees t • i = 0 • str1 = 'javatpoint' • • while i < len(str1): • if str1[i] == 't': • i += 1 • break • print('Current Letter :', str1[i]) • i += 1
  • 50. Control Structure: loops 3. Pass Statement - The pass statement is used to declare the empty loop. It is also used to define empty class, function, and control statement. Let's understand the following example. Example - • # An empty loop • str1 = 'javatpoint' • i = 0 • • while i < len(str1): • i += 1 • pass • print('Value of i :', i)
  • 51. Control Structure: loops Infinite while loop • If the condition is given in the while loop never becomes false, then the while loop will never terminate, and it turns into the infinite while loop. • Any non-zero value in the while loop indicates an always- true condition, whereas zero indicates the always-false condition. This type of approach is useful if we want our program to run continuously in the loop without any disturbance. Example • while (1): • print("Hi! we are inside the infinite while loop")
  • 52. Control Structure: loops Using else with while loop • Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for loop, if the while loop is broken using break statement, then the else block will not be executed, and the statement present after else block will be executed. The else statement is optional to use with the while loop. Consider the following example. Example • i=1 • while(i<=5): • print(i) • i=i+1 • else: • print("The while loop exhausted") •
  • 53. Control Structure: loops Continue vs. Pass • Usually, there is some confusion in the pass and continue keywords. So here are the differences between these two. Headings continue pass Definition The continue statement is utilized to skip the current loop's remaining statements, go to the following iteration, and return control to the beginning. The pass keyword is used when a phrase is necessary syntactically to be placed but not to be executed. Action It takes the control back to the start of the loop. Nothing happens if the Python interpreter encounters the pass statement. Application It works with both the Python while and Python for loops. It performs nothing; hence it is a null operation. Syntax It has the following syntax: -: continue Its syntax is as follows:- pass Interpretation It's mostly utilized within a loop's condition. During the byte-compile stage, the pass keyword is removed.
  • 54. Disadvantages of Python 1. Slow Speed • We discussed above that Python is an interpreted language and dynamically-typed language. The line by line execution of code often leads to slow execution. • The dynamic nature of Python is also responsible for the slow speed of Python because it has to do the extra work while executing code. So, Python is not used for purposes where speed is an important aspect of the project. 2. Not Memory Efficient • To provide simplicity to the developer, Python has to do a little tradeoff. • The Python programming language uses a large amount of memory. This can be a disadvantage while building applications when we prefer memory optimization.
  • 55. Disadvantages of Python 3. Weak in Mobile Computing • Python is generally used in server-side programming. We don’t get to see Python on the client-side or mobile applications because of the following reasons. Python is not memory efficient and it has slow processing power as compared to other languages. 4. Database Access • Programming in Python is easy and stress-free. But when we are interacting with the database, it lacks behind. • The Python’s database access layer is primitive and underdeveloped in comparison to the popular technologies like JDBC and ODBC. • Huge enterprises need smooth interaction of complex legacy data and Python is thus rarely used in enterprises.
  • 56. Disadvantages of Python 5. Runtime Errors • As we know Python is a dynamically typed language so the data type of a variable can change anytime. A variable containing integer number may hold a string in the future, which can lead to Runtime Errors. • Therefore Python programmers need to perform thorough testing of the applications.
  • 57. Conclusion • https://www.softwaretestinghelp.com/python/ • https://techvidvan.com/tutorials/python-advantages-and- disadvantages/ • https://www.javatpoint.com/python-data-types • https://www.programiz.com/python-programming/first-program • https://www.learnpython.org/ • https://www.studytonight.com/python/introduction-to-idle