0% found this document useful (0 votes)
27 views90 pages

Unit - Ii

Uploaded by

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

Unit - Ii

Uploaded by

Chanakya Varma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 90

UNIT - II

• Python is a high-level, interpreted, interactive and object-oriented scripting language.

• Python is designed to be highly readable.

• Python is Interpreted: Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it.

• Python is Interactive: At a Python prompt u can interact with the interpreter directly.

• Python is Object-Oriented: It supports Object-Oriented style or technique of


programming that encapsulates code within objects.
• Python was developed by Guido van Rossum in the late eighties and
early nineties.
• Python is derived from many other languages, including ABC, Modula-
3, C, C++, Algol-68, SmallTalk, Unix shell, and other scripting
languages.
• Python Features:

• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the student
to pick up the language quickly.

• Easy-to-read: Python code is more clearly defined and visible to the eyes.

• 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 the same interface on all platforms.

• Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to
add to or customize their tools to be more efficient
• Databases: Python provides interfaces to all major commercial databases.

• GUI Programming: Python supports GUI applications that can be created


and ported to many system calls, libraries, and windows systems, such as
Windows MFC, Macintosh, and the X Window system of Unix.

• Scalable: Python provides a better structure and support for large


programs than shell scripting.
• Running Python
• There are three different ways to start Python:
• Interactive Interpreter: in command prompt type “python”
• 2. Script from the Command-line:
• A Python script can be executed at command line by invoking the
interpreter on your application, as in the following:
• (3) Integrated Development Environment:
• You can run Python from a Graphical User Interface (GUI)
environment as well,
• if you have a GUI application on your system that supports Python.
• Example: IDLE, PYCHARM, JUPYTER NOTEBOOK,….etc.
Basic Syntax
Python Identifiers
Python Keywords
• These are reserved words and you cannot use them as constant or
variable or any other identifier names.
• All the Python keywords contain lowercase letters only.
Lines and Indentation
• python provides no braces to indicate blocks of code for class and function
definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• in Python all the continuous lines indented with same number of spaces would
form a block.
• The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount.
• Correct Wrong
VARIABLE TYPES
• Variables are nothing but reserved memory locations to store values.
• This means when you create a variable, you reserve some space in
memory.
• Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
• Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables
• Assignig Values to Variables:
• Python variables do not need explicit declaration to reserve memory
space.
• The declaration happens automatically when you assign a value to a
variable.
• The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in
the variable.
• For example:
• counter = 100 # An integer assignment
• miles = 1000.0 # A floating point
• name = "John" # A string
• Print(counter)
• Print(miles)
• Print(names)
• Multiple Assignment
• Python allows you to assign a single value to several variables simultaneously. For
example:
• Example:
• a=b=c=1
• Here, an integer object is created with the value 1, and all three variables are assigned
to the same memory location.
• You can also assign multiple objects to multiple variables. For example:
• Example:
• a, b, c = 1, 2, "john“
• Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable c.
• Standard Data Types
• The data stored in memory can be of many types.
• For example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters.
• Python has various standard data types that are used to define the operations possible on
them and the storage method for each of them.
• Python has five standard data types:
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
• Python Numbers
• Number data types store numeric values.
• Number objects are created when you assign a value to them.
• Example:
• A =10
• B= 20
• You can also delete the reference to a number object by using the del statement.
• You can delete a single object or multiple objects by using the del statement.
• The syntax of the del statement is: del var1[,var2[,var3[....,varN]]]]
• Example:
• del A, B # A and B will be deleted
• Python supports four different numerical types:
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)
• Python allows you to use a lowercase L with long,
• But it is recommended that you use only an uppercase L to avoid confusion
with the number 1.
• Python displays long integers with an uppercase L.
• Python Strings
• Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
• Python allows for either pairs of single or double quotes.
• Subsets of strings can be taken using the slice operator ([ ] and [:] ) with
indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
• The plus (+) sign is the string concatenation operator and the asterisk
(*) is the repetition operator.
• For example:
• Python Lists
• Lists are compound data types.
• A list contains items separated by commas and enclosed within square brackets ([]).
• To some extent, lists are similar to arrays in C.
• One difference between them is that all the items belonging to a list can be of
different data type.
• The values stored in a list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1.
• The plus (+) sign is the list concatenation operator, and the asterisk (*) is the
repetition operator. For example:
• Python Tuples
• A tuple is another sequence data type that is similar to the list.
• A tuple consists of a number of values separated by commas.
• Unlike lists, however, tuples are enclosed within parentheses.
• The main differences between lists and tuples are:
• Lists are enclosed in brackets ( [ ] ) and their elements and size can be
changed,
• while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as readonly lists.
• Python Dictionary
• Python's dictionaries are kind of hash table type.
• They work like associative arrays or hashes found in Perl and consist of
key-value pairs.
• A dictionary key can be almost any Python type, but are usually numbers
or strings.
• Values, on the other hand, can be any arbitrary Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can be assigned
and accessed using square braces ([]).
• For example:
output
• Boolean data type in Python
• Python boolean type is one of the built-in data types provided by Python,
• which represents one of the two values i.e. True or False.
• Generally, it is used to represent the truth values of the expressions.
• For example, 1==1 is True whereas 2<1 is False.
• The boolean value can be of two types only i.e. either True or False.
• The output <class ‘bool’> indicates the variable is a boolean data type.
• Example:
• a = True
• type(a)
• b = False
• type(b)
• Expression Statements:
• A simple Python expression is similar to a mathematical expression.
• It consists of some numbers, connected by a mathematical operator.
• In programming terminology, numbers (this includes integers as well as
numbers with fractional parts ex. 5, 3.89) are called numeric literals.
• An operator (e.g. +, -, /) indicates mathematical operation between its
operands, and hence the value of the expression.
• The process of deriving the value of an expression is called the evaluation of
the expression.
• When a mathematical expression is entered, the Python interpreter
automatically evaluates and displays its value in the next line.
• Similar to the / division operator, we also have the // integer division
operator.
• The key difference is that the former outputs the decimal value
known as a float which can be seen in the above example and the
latter outputs an integer value
• i.e. without any fractional parts.
• Below is an example of an integer division where Python returns the
output value without any decimals.
• Example: 5 //3 , output is: 1
• Example:
• # Composite expression
• 5 + 3 - 3 + 4 , output is: 9
• In the example above, the order of evaluation is from left to right
• Resulting in the expression 5 + 3 evaluating first.
• Its value 8 is then combined with the next operand 3 by the - operator,
evaluating to the value 5 of the composite expression 5 + 3 - 3.
• This value is in turn combined with the last literal 4 by the + operator,
ending up with the value 9 for the whole expression.
• In the example, operators are applied from left to right, because - and + have
the same priority.
• For an expression where we have more than one operators, it is not
necessary all the operators have the same priority.
• Consider the following example:
• Example: 5 + 3 * 3 – 4, output is: 10
• Here, the expression above evaluated to 10, because the * operator has a
higher priority compared to - and + operators.
• The expression 3 * 3 is evaluated first resulting in the value of 9 which will be
combined with the operand 5 by the operator + producing the value of 14.
• This value is in turn combined with the next operand 4 by the operator -
which results in the final value of 10.
• The order in which operators are applied is called
• operator precedence:
• In Python, mathematical operators follow the natural precedence observed in
mathematics.
• Similar to mathematical functions, Python allows the use of brackets ( and ) to manually
specify the order of evaluation.
• Example:
• (5 + 3) * (3 - 4) , output is: -8
• In the examples above, an operator connects two operands, and hence they are called
binary operators.
• In contrast, operators can also be unary which take only one operand.
• Such an operator is - known as negation.
• Example: - (5+3), output is: -8
• Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
• Python Arithmetic Operators
• Python Assignment Operators
• Assignment operators are used to assign values to variables:
Python Comparison Operators
Comparison operators are used to compare two values:
Python Logical Operators
Python Operators Precedence
Example:
Control Statements
• In general, statements are executed sequentially:
• The first statement in a function is executed first, followed by the
second, and so on.
• There may be a situation when you need to execute a block of code
several number of times.
• Programming languages provide various control structures that allow
for more complicated execution paths.
• A loop statement allows us to execute a statement or group of
statements multiple times.
Python programming language provides following types of
loops to handle looping requirements.
Flow diagram
For Loop
• It has the ability to iterate over the items of any sequence, such as a
list or a string.
Example
Example The following program uses a nested for loop to find the prime numbers
from 2 to 100: CODE OUTPUT
if Statement
• Example:
n=5
for i in range(n):
if i < 2:
i += 1
if i > 2:
i -= 2
print(i) #12212
elif - Keyword
• elif
• The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition".
• Example:
• a = 33
• b = 33
• if b > a:
• print("b is greater than a")
• elif a == b:
• print("a and b are equal") # a and b are equal
Nested If
• You can have if statements inside if statements, this is called nested if
statements.
• Example:
• x = 41
• if x > 10:
• print("Above ten,")
• if x > 20: # it is called as “NESTED” – statement.
• print("and also above 20!")
• else:
• print("but not above 20.")
Break Statement
• The break is a keyword
• used to bring the program control out of the loop.
• it breaks the loops one by one,
• i.e., in the case of nested loops, it breaks the inner loop first and
then proceeds to outer loops.
• In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line
after the loop.
• The break is commonly used in the cases where we need to break
the loop for a given condition.
• Syntax:
• # loop statements
break;
• Example:
list =[1,2,3,4]
count = 1;
for i in list:
if i == 2:
print("item matched",i)
#Example:
break # break keyword is used str = "pythn code"
print("After the for loop") for i in str:
if i == 'o':
break
print(i); # pythn c
Continue Statement

• Continue keyword return control of the iteration to the beginning of


the Python for loop or Python while loop.

• All remaining lines in the prevailing iteration of the loop are skipped
with the help of continue keyword, which returns execution to the
beginning of the next iteration of the loop.
• Example: #Example:
list =[1,2,3,4] str = "pythn code"
for i in list: for i in str:
if i == 2: if i == 'o':
print("item matched",i) continue
print(i); # pythn cde
continue # break keyword is used
print("After the for loop") # 1
The pass Statement
• if statements cannot be empty.
• but if you for some reason have an if statement with no content, put
in the pass statement to avoid getting an error.
• Example:
• a = 33
• b = 200
• if b > a:
• pass # pass keyword
else in Loop
• The else statement is used with the if clause.
• You can combine the else keyword with the for and the while loop.
• After the code block of the loop, the else block is displayed.
• After completing all the iterations, the interpreter will carry out the
code in the else code block.
• Only when the else block has been run does the program break from
the loop.
• Example:
# Python program to show how to use else statements with a loop
for n in range(5):
print(f"Current iteration: {n+1}")
else:
print("This is the else block")
print("Outside the loop")
Idiomatic approach to solve
Programming Problems
• Idiomatic refers to the most common way to write something in
a language.

• Writing idiomatic code means following the conventions of the


language, and solving problems the way they are meant to be
solved in that language.
• How do I make a code more pythonic?
• Increase readability and maintainability and
• Decrease bugs in the code.
• Use Language constructs properly while writing the code.
• Avoid repetition of code (follow modular approach)

You might also like