[go: up one dir, main page]

0% found this document useful (0 votes)
43 views92 pages

INT213 Unit1

The document discusses Python programming and introduces some key concepts: 1. It provides an overview of Python as a general-purpose programming language and discusses its history and uses. 2. It defines variables, data types, literals, identifiers and rules for naming variables in Python. 3. It explains the differences between identifiers and variables, and covers concepts like global variables, unpacking variables, and outputting variables.

Uploaded by

Shivanshu Pandey
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)
43 views92 pages

INT213 Unit1

The document discusses Python programming and introduces some key concepts: 1. It provides an overview of Python as a general-purpose programming language and discusses its history and uses. 2. It defines variables, data types, literals, identifiers and rules for naming variables in Python. 3. It explains the differences between identifiers and variables, and covers concepts like global variables, unpacking variables, and outputting variables.

Uploaded by

Shivanshu Pandey
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/ 92

INT213

PYTHON PROGRAMMING

P.Raja,
Assistant Professor in Embedded System Design(D4),
School of Electronics and Electrical Engineering
Unit I
 Introduction : python programming language, introduction
to program and debugging, formal and natural language
 Variables, Expression and Statements : Values and types,
variables, variables name and keywords, statements,
operators and operand, order of operations, operations on
string, composition and comments
 Conditionals and Iteration : modulus operator, Boolean
expressions, logic operators, conditional, alternative
execution, nested conditionals and return statements, while
statements, encapsulation and generalization
 Functions and recursion : function calls, type conversion
and coercion, math functions, adding new function,
parameters and argument, recursion and its use.
Difference between Compiler & Interpreter
IEEE spectrum list of top programming language 2021.
The list of programming languages is based on popularity.
Introduction - Python programming
language:
 The History of Python:-
 Python was created by Guido van Rossum in the Netherlands
in 1990 and was named after the popular British comedy
troupe Monty Python’s Flying Circus.
 Van Rossum developed Python as a hobby, and Python has
become a popular programming language widely used in
industry and academia due to its simple, concise, and intuitive
syntax and extensive library.
Cont…
 general-purpose programming language
 you can use Python to write code for any programming task
 in the Google search engine
 In mission-critical projects at NASA
 in transaction processing at the New York Stock Exchange.
 Python is interpreted
 Python is an object-oriented programming (OOP) language
Features of Python programming
Introduction - introduction to program and debugging :

 Program: A set of instructions that specifies a computation.


 What Is Debugging? Programming is a complex process, and
because it is done by human beings, it often leads to errors. For
whimsical reasons, programming errors are called Bugs. The process
of tracking them down and correcting them is called DEBUGGING.
 Three kinds of errors can occur in a program: 
 SYNTAX errors, 
 RUNTIME errors,
 SEMANTIC errors.
Glossary:
Problem-solving:
The process of formulating a problem, finding a solution, and
expressing the solution.
High-level language:
The python language is designed to be easy for humans
to read and write.
Low-level language:
A programming language that is created to be easy for a computer to
execute; also called “Machine language” or “Assembly language”.
 Interpreter:
To execute a program in a high-level language by changing it one line at
a time. 
Cont…
 Compiler:
 To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.
  Source code:
 A program in a high-level language before being compiled.
 Object code:
 The output of the compiler after it translates the program.
 Executable:
 Another name for object code that is ready to be executed.
Cont…

 Script:
 A program stored in a file (usually one that will be interpreted).
 Program:
 A set of instructions that specifies a computation.
 Algorithm:
 A general purpose for solving a category of problem.
 Bug:
 An error in a program.
Cont…
 Debugging:
 The process of finding and removing any of the three kinds of
programming errors.
  Syntax:
 The structure of the program.
  Syntax error:
 An error in a program that makes it impossible to parse (and therefore
impossible to interpret). 
Cont…
 Runtime error:
 An error that does not occur until the program has started to execute
but that prevents from continuing.
  Exception:
 Another name for run time error.
  Semantic error:
 An error in a program that makes it do something other than what the
program intended.
  Semantics:
 The meaning of the program. 
Introduction - formal and natural
language:
 Natural languages are the languages people speak, such as
English, Spanish, and French. They were not designed by people
(although people try to impose some order on them); they evolved
naturally.
 Formal languages are languages that are designed by people for
specific applications. For example, the notation that mathematicians
use is a formal language that is particularly good at denoting
relationships among numbers and symbols. Chemists use a formal
language to represent the chemical structure of molecules. And most
importantly:

 Programming languages are formal languages that have been designed to


express computations.
Types of Literals in Python
 Literals in Python is defined as the raw data assigned to
variables or constants while programming.
Python Identifiers

 An identifier is a name given to entities like class, functions, variables,


etc. It helps to differentiate one entity from another.
 Rules for writing identifiers
i. Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore _. Names like
myClass, var_1 and print_this_to_screen, all are valid example.
ii. An identifier cannot start with a digit. 1variable is invalid, but
variable1 is a valid name.
iii. Keywords cannot be used as identifiers.
iv. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
v. An identifier can be of any length.
Python Valid Identifiers Python Invalid Identifiers
Example Example
• abc123  123abc
•  abc_de   abc@
•  _abc   123
•  ABC   for
•  abc
Python Keywords

False def if raise


None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not await
class form or async
continue global pass
Python Variables

 Variables are containers for storing data values.


x = 5 x = 4  # x is of type int
y = "John“ x = "Sally" # x is now of type str

Casting: -
 If you want to specify the data type of a variable,
this can be done with casting.
 x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0
Cont…

Get the Type


 You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes?


Case-Sensitive
Cont…

 Variable Names
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume).
• Rules for Python variables:
• 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 (age, Age and AGE are
three different variables)
Cont…
Camel Case
 Each word, except the first, starts with a capital letter:
 myVariableName = "John“
Pascal Case
 Each word starts with a capital letter:
 MyVariableName = "John“
Snake Case
 Each word is separated by an underscore character:
 my_variable_name = "John"
Cont…
Many Values to Multiple Variables
 Python allows you to assign values to multiple variables in
one line:
 x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
 And you can assign the same value to multiple variables in
one line:
 x = y = z = "Orange"
print(x)
print(y)
print(z)
Cont…
Unpack a Collection
 If you have a collection of values in a list, tuple etc. Python
allows you to extract the values into variables. This is
called unpacking.
 fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables
 The Python print() function is often used to output variables.
 x = "Python is awesome"
print(x)
Cont…
Global Variables
 Variables that are created outside of a function (as
in all of the examples above) are known as global
variables.
 Global variables can be used by everyone, both
inside of functions and outside.
 x = "awesome"

def myfunc():
  print("Python is " + x)

myfunc()
Difference Between Identifier and Variable

 Identifier
• All of them are not variables.
• They are used to name a variable, a function, a class, a structure, a
union.
• It is created to give a unique name to an entity.
• They can consist of alphabets, digits, and underscores.
• There is no punctuation or special symbol, except the underscore.
• It can be upper case or lower case.
• It can start with lower case letter, upper case letter or an underscore.
• It helps locate the name of the entity which is defined along with a
keyword.
Cont…

 Variable
• It is used to give a name to a memory location.
• It holds a value.
• The names of variables are different.
• They help allot a unique name to a specific memory location.
Python Data Types
Operators and operand
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Arithmetic Operators

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Assignment Operators
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Comparison Operators
Operator Name Example

== Equal x == y

!= Not equal x != y

>  Greater than x>y

<  Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Logical Operators

Operator Description Example

and  Returns True if both statements x < 5 and  x < 10


are true

or Returns True if one of the x < 5 or x < 4


statements is true

not Reverse the result, returns not(x < 5 and x <


False if the result is true 10)
Identity Operators

Operator Description Example


is  Returns True if both x is y
variables are the same
object
is not Returns True if both x is not y
variables are not the same
object
Membership Operators

Operator Description Example

in  Returns True if a sequence with the x in y


specified value is present in the
object

not in Returns True if a sequence with the x not in y


specified value is not present in the
object
Bitwise Operators
Operato Name Description
r
&  AND Sets each bit to 1 if both bits are 1

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

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

~  NOT Inverts all the bits

<<  Zero fill Shift left by pushing zeros in from the right and let the
left shift leftmost bits fall off

>>  Signed Shift right by pushing copies of the leftmost bit in from
right shift the left, and let the rightmost bits fall off
Python Operator Precedence

 When evaluating complex expressions like 5+2*4%6-1 and


13 or 3 one might easily get confused about in which order
the operations will be performed.
 Python Operators Precedence Rule – PEMDAS
 You might have heard about the BODMAS rule in your
school’s mathematics class. Python also uses a similar type of
rule known as PEMDAS.
 P – Parentheses
E – Exponentiation
M – Multiplication
D – Division
A – Addition
S – Subtraction
Operator Description
Assignment expression (Lowest
:=
precedence) 
lambda Lambda expression
if-else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
<, <=, >, >=,  Comparison operators
!=, == Equality operators
Identity operators, membership
in, not in, is, is not,
operators
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Left and right Shifts
+, – Addition and subtraction
Multiplication, matrix multiplication,
*, @, /, //, %
division, floor division, remainder
+x, -x, ~x Unary plus, Unary minus, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index:index], x(arguments Subscription, slicing, call, attribute
…), x.attribute reference
Binding or parenthesized expression,
(expressions…), [expressions…],
list display, dictionary display, set
{key: value…}, {expressions…}
display
() Parentheses (Highest precedence) 
Python input and output
 input(prompt): To accept input from a user.
 print(): To display output on the console/screen.
 Input():-
 The input() method reads the user's input and returns it as a
string.
input() Syntax:
input(prompt)
 prompt: (Optional) A string, representing the default message
before taking input.
Python input and output
 Output()
 We use the print() function to output data to the standard output
device (screen).
 print('This sentence is output to the screen’)
 print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Operation on String
 Strings in python are surrounded by either single quotation
marks, or double quotation marks.
 'hello' is the same as "hello".
 You can display a string literal with the print() function:
print("Hello")
print('Hello')
 Assign String to a Variable
a = "Hello"
print(a)
Operation on String
 Multiline Strings
a = """Lorem ipsum dolor sit amet, consectetur
adipiscing elit,sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."“”
print(a)
 Strings are Arrays
 Like many other popular programming languages, strings in
Python are arrays 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.
Operation on String
 Strings indexing and splitting
Operation on String
 Strings indexing and splitting
Operation on String
Operation on String
 Escape Sequences
 \’ Single Quote \\ Backslash \n New Line
 \r Carriage Return \t Tab \b Backspace
 \f Form Feed \ooo Octal value \xhh Hex value
Operation on String
 String Formatting
 %d Signed decimal integer
 %u unsigned decimal integer
 %c Character
 %s String
 %f Floating-point real number
Operation on String
 String format() Method
 >>> s= "The value x is in float {x:.2f}"
 >>> print(s.format(x=150))
 The value x is in float 150.00
 The format() method formats the specified value(s) and insert
them inside the string's placeholder.
 The placeholder is defined using curly brackets: {}. Read more
about the placeholders in the Placeholder section below.
 Syntax
 string.format(value1, value2...)
Operation on String
 The Placeholders
 The placeholders can be identified using named indexes
{price}, numbered indexes {0}, or even empty placeholders
{}.
 txt1 = "My name is {fname}, I'm
{age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm
{1}".format("John",36)
txt3 = "My name is {}, I'm
{}".format("John",36)
:< Left aligns the result (within the available space)
:> Right aligns the result (within the available space)
:^ Center aligns the result (within the available space)
:= Places the sign to the left most position
:+ Use a plus sign to indicate if the result is positive or negative

:- Use a minus sign for negative values only


:  Use a space to insert an extra space before positive numbers (and
a minus sign before negative numbers)

:, Use a comma as a thousand separator


:_ Use a underscore as a thousand separator
:b Binary format
:c Converts the value into the corresponding unicode character

:d Decimal format
:e Scientific format, with a lower case e
:E Scientific format, with an upper case E
:f Fix point number format
:F Fix point number format, in uppercase format
(show inf and nan as INF and NAN)
:g General format
:G General format (using a upper case E for scientific notations)

:o Octal format
:x Hex format, lower case
:X Hex format, upper case
:n Number format
:% Percentage format
Operation on String
 quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {}
dollars."
print(myorder.format(quantity, itemno, price))

 Output:
I want 3 pieces of item 567 for 49.95 dollars.
Operation on String
 String Methods
capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string
count() Returns the number of times a specified value occurs in a
string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string


find() Searches the string for a specified value and returns the
position of where it was found
capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string
count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string


endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string


find() Searches the string for a specified value and returns the position
of where it was found
isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string


lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a


specified value
rfind() Searches the string for a specified value and returns the last
position of where it was found

rindex() Searches the string for a specified value and returns the last
position of where it was found

rjust() Returns a right justified version of the string


rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string


split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string


swapcase() Swaps cases, lower case becomes upper case and vice
versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the


beginning
 String find() Method
 txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
 >>> "Hello" in "Hello world"
 True
 string1 = "helloworld"
 print("w" in string1)
 print("W" in string1)
 print("t" not in string1)
Conditional Statements

 If Statement :-
if(condition):
 #if statement  
  
 Example:
 a = 10  
 b = 20  
 if a<b:  
   print("a is less than b") 
Conditional Statements

 If else statement :-
 if(condition):    
    # if statement  
 else:    
    # else statement  
 Example :-
a = 10  
b = 20  
if a==b:  
  print("a and b are equal")  
else:  
  print("a and b are not equal") 
Conditional Statements

Elif statement :- Example :-



a = 10  
if(condition):  

b = 10  
   # if statement   
if a < b:  
elif(condition):   
  print("a is greater than b")
   # elif statement   

elif a == b:  
  

  print("a and b are equal")  
else:   
else:  
   # else statement 
  print("b is greater than a")
      
 
Conditional Statements

 Nested if statement :-
 if(condition):  
   if(condition):  
     # if statemen 

 Example:-
 a= 1001  
 if a> 100:  
   print("Above 100")  
   if a > 1000:  
     print("and also above 1000") 
Conditional Statements

 Nested if else statement :-


 if(condition):  
    if(condition):  
        #if statement  
    else:  
        #else statement  
 else:  
  #else statement  
Conditional Statements

 Example:-
 a=int(input("enter the a value"))#user give a valu 
 if a> 100:  
   print("Above 100")  
   if a > 1000:  
     print("and also above 1000")  
   else:  
     print("and also below 1000")  
 else:  
     print("below 100") 
Conditional Statements

 Short Hand If :-
 if condition: statement
 Example :-
 if a > b: print("a is greater than b")
 Short Hand If ... Else
 statement1 if condition else statement2
 statement1 if condition1 else statement2 if condition2
else statement3
Conditional Statements

 Example :-
Loop Statements

 While Loop Statements :-


while expression:
 statement(s)
 Example :-
Loop Statements

 Using else Statement with While Loop :-


while expression:
 statement(s)
Else:
 Statement(s)
 Example :-
Loop Statements

 Using else Statement with While Loop :-


while expression:
 statement(s)
Else:
 Statement(s)
 Example :-
Loop Statements

 For Loops :-
 for val in sequence:
 loop body
 Example :-
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
for x in "banana":
  print(x)
Loop Statements

 For Loops :-
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)
Loop Statements

 The range() Function :-


Loop Statements

 The range() Function :-


Loop Statements

 The range() Function :-


Loop Statements

 for loop with range() :-


Loop Statements

 for loop with range() :-


Functions

 Syntax:-
Functions

 Syntax:-
Functions

 Built-in function :-
 range(), id(), type(), input(), eval() etc.
 User-defined function :-
Functions

 User-defined function :-
Functions

 Function Arguments :-
1.Positional arguments
2.keyword arguments
3.Default arguments
4.Variable-length arguments
 Positional Arguments
Functions

 Function Arguments :-
 keyword arguments
Functions

 Function Arguments :-
 keyword arguments
Functions

 Function Arguments :-
 Default arguments
Functions

 Function Arguments :-
 Variable-length arguments
Functions

 Recursive Function :-
 A recursive function is a function that calls itself, again and
again.
Functions

 Anonymous/Lambda Function :-
 Sometimes we need to declare a function without any name. The nameless
property function is called an anonymous function or lambda function.
 Syntax of lambda function:
lambda: argument_list:expression
 x = lambda a : a + 10
print(x(5))
 x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

You might also like