SlideShare a Scribd company logo
Fundamentals of Python
Programming
Introduction to python programming
• High level, interpreted language
• Object-oriented
• General purpose
• Web development (like: Django and Bottle),
• Scientific and mathematical computing (Orange, SciPy, NumPy)
• Desktop graphical user Interfaces (Pygame, Panda3D).
• Other features of python includes the following:
• Simple language which is easier to learn
• Free and open source
• Portability
• Extensible and embeddable
• Standard large library
• Created by Guido van Rossum in 1991
• Why the name Python?
• Not after a dangerous snake.
• Rossum was fan of a comedy series from late seventies.
• The name "Python" was adopted from the same series "Monty Python's
Flying Circus".
Reasons to Choose Python as First Language
• Simple Elegant Syntax
• Not overly strict
• Expressiveness of the language
• Great Community and Support
Installation of Python in Windows
• Go to Download Python page on the official site
(https://www.python.org/downloads/) and click Download Python
3.6.5 (You may see different version name)
• When the download is completed, double-click the file and follow the
instructions to install it.
• When Python is installed, a program called IDLE is also installed along
with it. It provides graphical user interface to work with Python.
• Open IDLE, Write the following code below and press enter.
print("Hello, World!")
• To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).
• Write Python code and save (Shortcut: Ctrl+S) with .py file extension
like: hello.py or your-first-program.py
print("Hello, World!")
• Go to Run > Run module (Shortcut: F5) and you can see the output.
First Python Program
Fundamentals of Python Programming
Second Program
Fundamentals of Python Programming
Few Important Things to Remember
• To represent a statement in Python, newline (enter) is used.
• Use of semicolon at the end of the statement is optional (unlike
languages like C/C++)
• In fact, it's recommended to omit semicolon at the end of the
statement in Python
• Instead of curly braces { }, indentations are used to represent a block
Python Keywords
• Keywords are the reserved words(can not be used as a identifier) in
Python
• Are case sensitive
Python Identifiers
• Name given to entities like class, functions, variables etc. in Python
• Rules for writing 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 (_)
• myClass, var_1 and print_this_to_screen, all are valid examples
• Cannot start with a digit
• 1variable is invalid, but variable1 is perfectly fine
• Keywords cannot be used as identifiers
• Cannot use special symbols like !, @, #, $, % etc. in our identifier
• Can be of any length.
Things to care about
• Python is a case-sensitive language.
• Variable and variable are not the same.
• Multiple words can be separated using an underscore,
this_is_a_long_variable
• Can also use camel-case style of writing, i.e., capitalize every first
letter of the word except the initial word without any spaces
• camelCaseExample
Python Statement
• Instructions that a Python interpreter can execute are called
statements.
• Two types
• Single line statement:
• For example, a = 1 is an assignment statement
• Multiline statement:
• In Python, end of a statement is marked by a newline character.
• So, how to make multiline statement?
• Technique1:
• make a statement extend over multiple lines with the line continuation
character ().
• For example:
a = 1 + 2 + 3 + 
4 + 5 + 6 + 
7 + 8 + 9
• Technique2:
• make a statement extend over multiple lines with the parentheses ( )
• For example:
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
• Technique3:
• make a statement extend over multiple lines with the brackets [ ] and braces {
}.
• For example:
colors = ['red',
'blue',
'green']
• We could also put multiple statements in a single line using
semicolons, as follows
a = 1; b = 2; c = 3
Python Indentation
• Most of the programming languages like C, C++, Java use braces { } to
define a block of code
• Python uses indentation
• A code block (body of a function, loop etc.) starts with indentation
and ends with the first un-indented line
Fundamentals of Python Programming
Fundamentals of Python Programming
Error due to incorrect indentation
Python Comments
• To make the code much more readable.
• Python Interpreter ignores comment.
• Two types of comment is possible in python:
• Single line comment and
• Multi-line comment
Single line comment
• In Python, we use the hash (#) symbol to start writing a comment.
• It extends up to the newline character
Multi-line comments
• Two way:
• By using # sign at the beginning of each line
#This is a long comment
#and it extends
#to multiple lines
• By using either ‘ ‘ ‘ or “ “ “ (most common)
"""This is also a
perfect example of
multi-line comments"""
Python Variable
• a variable is a named location used to store data in the memory.
• Alternatively, variables are container that hold data which can be
changed later throughout programming
Declaring Variables
• In Python, variables do not need declaration to reserve memory
space.
• The "variable declaration" or "variable initialization" happens
automatically when we assign a value to a variable.
• We use the assignment operator = to assign the value to a variable.
Assigning Values to variables
Fundamentals of Python Programming
Changing value of a variable
Fundamentals of Python Programming
Assigning same value to the multiple variable
Fundamentals of Python Programming
Assigning multiple values to multiple variables
Fundamentals of Python Programming
Constants
• Value that cannot be altered by the program during normal
execution.
• In Python, constants are usually declared and assigned on a module
• And then imported to the file
Defining constantModule
Fundamentals of Python Programming
Fundamentals of Python Programming
Rules and Naming convention for variables
and constants
• Create a name that makes sense. Suppose, vowel makes more sense
than v.
• Use camelCase notation to declare a variable
• For example: myName, myAge, myAddress
• Use capital letters where possible to declare a constant
• For example: PI,G,MASS etc.
• Never use special symbols like !, @, #, $, %, etc.
• Don't start name with a digit.
• Constants are put into Python modules
• Constant and variable names should have combination of letters in
lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore (_).
• For example: snake_case, MACRO_CASE, camelCase, CapWords
Literals
• Literal is a raw data given in a variable or constant. In Python, there
are various types of literals they are as follows:
• Numeric literals
• String literals
• Boolean literals
• Special literals
Numeric Literals
Fundamentals of Python Programming
String Literals
Fundamentals of Python Programming
Docstrings
Fundamentals of Python Programming
Using boolean literals
Fundamentals of Python Programming
Special literal(None)
Fundamentals of Python Programming
Literals Collection
Fundamentals of Python Programming
Data Types
• In python data types are classes and variables are instance (object) of
these classes
• Different types of data types in python are:
• Python numbers
• Python lists
• Python tuples
• Python strings
• Python sets
• Python dictionary
Python Numbers
Fundamentals of Python Programming
Python List
• Ordered sequence of items
• Can contain heterogeneous data
• Syntax:
• Items separated by commas are enclosed within brackets [ ]
• Example: a= [1,2.2,'python']
Extracting elements from the list
Fundamentals of Python Programming
• Note: Lists are mutable, meaning, value of elements of a list can be
altered.
Python Tuple
• Same as list but immutable.
• Used to write-protect the data
• Syntax:
• Items separated by commas are enclosed within brackets ( )
• Example:
• t = (5,'program', 1+3j)
Fundamentals of Python Programming
Fundamentals of Python Programming
Fundamentals of Python Programming
Fundamentals of Python Programming
Python Strings
• use single quotes or double quotes to represent strings.
• Multi-line strings can be denoted using triple quotes, ''' or """.
• Example:
s = "This is a string"
s = '''a multiline
string’’’
• Strings are also immutable.
Fundamentals of Python Programming
Fundamentals of Python Programming
Python Set
• Unordered collection of unique items
• defined by values separated by comma inside braces { }
Fundamentals of Python Programming
• Set have unique values. They eliminate duplicates.
• Example:
• Since, set are unordered collection, indexing has no meaning.
• Hence the slicing operator [] does not work.
• Example:
Python Dictionary
• An unordered collection of key-value pairs.
• Must know the key to retrieve the value.
• Are defined within braces {} with each item being a pair in the form
key: value
• Key and value can be of any type
Fundamentals of Python Programming
Fundamentals of Python Programming
Conversion between data types
• Conversion can be done by using different types of type conversion
functions like:
• int(),
• float(),
• str() etc.
int to float
float to int
To and form string
convert one sequence to another
• To convert to dictionary, each element must be a pair:
Python Type Conversion and Type Casting
• The process of converting the value of one data type (integer, string,
float, etc.) to another data type is type conversion
• Python has two types of type conversion.
• Implicit Type Conversion
• Explicit Type Conversion
• Type Conversion is the conversion of object from one data type to
another data type
• Implicit Type Conversion is automatically performed by the Python
interpreter
• Python avoids the loss of data in Implicit Type Conversion
• Explicit Type Conversion is also called Type Casting, the data types of
object are converted using predefined function by user
• In Type Casting loss of data may occur as we enforce the object to
specific data type
Implicit Type Conversion
• Automatically converts one data type to another data type
• Always converts smaller data type to larger data type to avoid the loss
of data
Fundamentals of Python Programming
Problem in implicit type conversion
Fundamentals of Python Programming
Explicit Type Conversion
• Users convert the data type of an object to required data type.
• Predefined functions like int(), float(), str(), etc. are to perform explicit
type conversion
• Is also called typecasting because the user casts (change) the data
type of the objects.
• Syntax :
• (required_datatype)(expression)
• Int(b)
Example
Fundamentals of Python Programming
Python Input, Output and Import
• Widely used functions for standard input and output operations are:
• print() and
• input()
Python Output Using print() function
Output formatting
• Can be done by using the str.format() method
• Is visible to any string object
• Here the curly braces {} are used as placeholders. We can specify the
order in which it is printed by using numbers (tuple index).
Example
• We can even use keyword arguments to format the string
• We can even format strings like the old printf() style used in C
• We use the % operator to accomplish this
Input() function
• input() function to take the input from the user.
• The syntax for input() is :
• input([prompt])
• where prompt is the string we wish to display on the screen.
• It is optional
• Entered value 10 is a string, not a number.
• To convert this into a number we can use int() or float() functions
• This same operation can be performed using the eval(). It can
evaluate expressions, provided the input is a string.
Python Import
• When our program grows bigger, it is a good idea to break it into
different modules.
• A module is a file containing Python definitions and statements.
• Python modules have a filename and end with the extension .py
• Definitions inside a module can be imported to another module or
the interactive interpreter in Python
• We use the import keyword to do this
Fundamentals of Python Programming
• import some specific attributes and functions only, using the from
keyword.
Python Operators
• Operators are special symbols in Python that carry out arithmetic or
logical computation.
• The value that the operator operates on is called the operand.
• For example:
>>> 2+3
5
• Here, + is the operator that performs addition.
• 2 and 3 are the operands and 5 is the output of the operation.
Arithmetic operators
Example
Comparison operators
Fundamentals of Python Programming
Logical operators
Fundamentals of Python Programming
Bitwise operators
• Bitwise operators act on operands as if they were string of binary
digits. It operates bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000
0100 in binary)
Fundamentals of Python Programming
Assignment operators
• Assignment operators are used in Python to assign values to
variables.
• a = 5 is a simple assignment operator that assigns the value 5 on the
right to the variable a on the left.
• There are various compound operators in Python like a += 5 that adds
to the variable and later assigns the same.
• It is equivalent to a = a + 5.
Fundamentals of Python Programming
Special operators
• identity operator
• membership operator
Identity operators
• is and is not are the identity operators in Python.
• They are used to check if two values (or variables) are located on the
same part of the memory.
• Two variables that are equal does not imply that they are identical.
Fundamentals of Python Programming
Membership operators
• in and not in are the membership operators in Python
• They are used to test whether a value or variable is found in a
sequence (string, list, tuple, set and dictionary).
• In a dictionary we can only test for presence of key, not the value
Fundamentals of Python Programming
Python Namespace and Scope
• Name (also called identifier) is simply a name given to objects.
• Everything in Python is an object
• Name is a way to access the underlying object.
• For example:
• when we do the assignment a = 2, here 2 is an object stored in memory and a
is the name we associate it with
• We can get the address (in RAM) of some object through the built-in function,
id()
Fundamentals of Python Programming
Fundamentals of Python Programming
Fundamentals of Python Programming
A name could refer to any type of object
Functions are objects too, so a name can
refer to them as well
What is a Namespace in Python?
• namespace is a collection of names.
• Help to eliminate naming collision/naming conflict
• A namespace containing all the built-in names is created when we
start the Python interpreter and exists as long we don't exit
• Each module creates its own global namespace
• Modules can have various user defined functions and classes.
• A local namespace is created when a function is called, which has all
the names defined in it.
• Similar, is the case with class
Fundamentals of Python Programming
Python Variable Scope
• All namespaces may not be accessible from every part of the program
• Scope is the portion of the program from where a namespace can be
accessed directly without any prefix
• At any given moment, there are at least three nested scopes.
• Scope of the current function which has local names
• Scope of the module which has global names
• Outermost scope which has built-in names
• When a reference is made inside a function, the name is searched in
the local namespace, then in the global namespace and finally in the
built-in namespace.
• If there is a function inside another function, a new scope is nested
inside the local scope.
Fundamentals of Python Programming
Fundamentals of Python Programming
Fundamentals of Python Programming
Thank You !

More Related Content

PPTX
Python Seminar PPT
PDF
Introduction to python programming
PPTX
Gps principle and working
PPT
Python ppt
PPTX
Introduction to the basics of Python programming (part 1)
PDF
Python final ppt
PPTX
Introduction to Basics of Python
PPT
programming with python ppt
Python Seminar PPT
Introduction to python programming
Gps principle and working
Python ppt
Introduction to the basics of Python programming (part 1)
Python final ppt
Introduction to Basics of Python
programming with python ppt

What's hot (20)

PDF
Datatypes in python
PPTX
Variables in python
PPT
Python Programming ppt
PPTX
Introduction to python
ODP
Python Presentation
PPTX
Python Functions
PPT
Intro to Python
PPT
Python Programming Language
PPTX
Python basics
PDF
Methods in Java
PPTX
Python
PPTX
Python for loop
PPTX
Introduction to python for Beginners
PPTX
Introduction to-python
PDF
Python Generators
PPTX
Python - An Introduction
PPT
Basic concept of OOP's
PDF
Python Programming
PPTX
PPTX
Python-Classes.pptx
Datatypes in python
Variables in python
Python Programming ppt
Introduction to python
Python Presentation
Python Functions
Intro to Python
Python Programming Language
Python basics
Methods in Java
Python
Python for loop
Introduction to python for Beginners
Introduction to-python
Python Generators
Python - An Introduction
Basic concept of OOP's
Python Programming
Python-Classes.pptx
Ad

Similar to Fundamentals of Python Programming (20)

PPTX
Python 01.pptx
PPTX
Python Programming 1.pptx
PPTX
modul-python-part1.pptx
PPTX
introduction to python
PPTX
Chapter7-Introduction to Python.pptx
PPTX
Python unit 2 is added. Has python related programming content
PPTX
Introduction to Python Basics for PSSE Integration
PPTX
INTRODUCTION TO PYTHON.pptx
PPTX
Introduction to Python Programming .pptx
PPTX
Topic 2 - Python, Syntax, Variables.pptx
PDF
Computer Related material named Phython ok
PDF
Python for katana
PPTX
Learn Python The Hard Way Presentation
PDF
Python Programing Bio computing,basic concepts lab,,
PPT
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
PDF
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
KEY
Programming with Python: Week 1
PPTX
python_class.pptx
PPT
Python slides for the beginners to learn
PPT
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Python 01.pptx
Python Programming 1.pptx
modul-python-part1.pptx
introduction to python
Chapter7-Introduction to Python.pptx
Python unit 2 is added. Has python related programming content
Introduction to Python Basics for PSSE Integration
INTRODUCTION TO PYTHON.pptx
Introduction to Python Programming .pptx
Topic 2 - Python, Syntax, Variables.pptx
Computer Related material named Phython ok
Python for katana
Learn Python The Hard Way Presentation
Python Programing Bio computing,basic concepts lab,,
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
Programming with Python: Week 1
python_class.pptx
Python slides for the beginners to learn
Py-Slides-1.ppt1234444444444444444444444444444444444444444
Ad

More from Kamal Acharya (20)

PPTX
Programming the basic computer
PPTX
Computer Arithmetic
PPTX
Introduction to Computer Security
PPTX
Session and Cookies
PPTX
Functions in php
PPTX
Web forms in php
PPTX
Making decision and repeating in PHP
PPTX
Working with arrays in php
PPTX
Text and Numbers (Data Types)in PHP
PPTX
Introduction to PHP
PPTX
Capacity Planning of Data Warehousing
PPTX
Data Warehousing
PPTX
Search Engines
PPTX
Web Mining
PPTX
Information Privacy and Data Mining
PPTX
Cluster Analysis
PPTX
Association Analysis in Data Mining
PPTX
Classification techniques in data mining
PPTX
Data Preprocessing
PPTX
Introduction to Data Mining and Data Warehousing
Programming the basic computer
Computer Arithmetic
Introduction to Computer Security
Session and Cookies
Functions in php
Web forms in php
Making decision and repeating in PHP
Working with arrays in php
Text and Numbers (Data Types)in PHP
Introduction to PHP
Capacity Planning of Data Warehousing
Data Warehousing
Search Engines
Web Mining
Information Privacy and Data Mining
Cluster Analysis
Association Analysis in Data Mining
Classification techniques in data mining
Data Preprocessing
Introduction to Data Mining and Data Warehousing

Recently uploaded (20)

PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Business Ethics Teaching Materials for college
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Complications of Minimal Access Surgery at WLH
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Pre independence Education in Inndia.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
01-Introduction-to-Information-Management.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Anesthesia in Laparoscopic Surgery in India
Business Ethics Teaching Materials for college
human mycosis Human fungal infections are called human mycosis..pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Final Presentation General Medicine 03-08-2024.pptx
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Types and Its function , kingdom of life
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Complications of Minimal Access Surgery at WLH
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
Pre independence Education in Inndia.pdf
Insiders guide to clinical Medicine.pdf
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
01-Introduction-to-Information-Management.pdf
TR - Agricultural Crops Production NC III.pdf
Pharma ospi slides which help in ospi learning
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES

Fundamentals of Python Programming

  • 2. Introduction to python programming • High level, interpreted language • Object-oriented • General purpose • Web development (like: Django and Bottle), • Scientific and mathematical computing (Orange, SciPy, NumPy) • Desktop graphical user Interfaces (Pygame, Panda3D).
  • 3. • Other features of python includes the following: • Simple language which is easier to learn • Free and open source • Portability • Extensible and embeddable • Standard large library
  • 4. • Created by Guido van Rossum in 1991 • Why the name Python? • Not after a dangerous snake. • Rossum was fan of a comedy series from late seventies. • The name "Python" was adopted from the same series "Monty Python's Flying Circus".
  • 5. Reasons to Choose Python as First Language • Simple Elegant Syntax • Not overly strict • Expressiveness of the language • Great Community and Support
  • 6. Installation of Python in Windows • Go to Download Python page on the official site (https://www.python.org/downloads/) and click Download Python 3.6.5 (You may see different version name) • When the download is completed, double-click the file and follow the instructions to install it. • When Python is installed, a program called IDLE is also installed along with it. It provides graphical user interface to work with Python.
  • 7. • Open IDLE, Write the following code below and press enter. print("Hello, World!") • To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N). • Write Python code and save (Shortcut: Ctrl+S) with .py file extension like: hello.py or your-first-program.py print("Hello, World!") • Go to Run > Run module (Shortcut: F5) and you can see the output.
  • 12. Few Important Things to Remember • To represent a statement in Python, newline (enter) is used. • Use of semicolon at the end of the statement is optional (unlike languages like C/C++) • In fact, it's recommended to omit semicolon at the end of the statement in Python • Instead of curly braces { }, indentations are used to represent a block
  • 13. Python Keywords • Keywords are the reserved words(can not be used as a identifier) in Python • Are case sensitive
  • 14. Python Identifiers • Name given to entities like class, functions, variables etc. in Python • Rules for writing 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 (_) • myClass, var_1 and print_this_to_screen, all are valid examples • Cannot start with a digit • 1variable is invalid, but variable1 is perfectly fine • Keywords cannot be used as identifiers • Cannot use special symbols like !, @, #, $, % etc. in our identifier • Can be of any length.
  • 15. Things to care about • Python is a case-sensitive language. • Variable and variable are not the same. • Multiple words can be separated using an underscore, this_is_a_long_variable • Can also use camel-case style of writing, i.e., capitalize every first letter of the word except the initial word without any spaces • camelCaseExample
  • 16. Python Statement • Instructions that a Python interpreter can execute are called statements. • Two types • Single line statement: • For example, a = 1 is an assignment statement • Multiline statement: • In Python, end of a statement is marked by a newline character. • So, how to make multiline statement?
  • 17. • Technique1: • make a statement extend over multiple lines with the line continuation character (). • For example: a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
  • 18. • Technique2: • make a statement extend over multiple lines with the parentheses ( ) • For example: a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
  • 19. • Technique3: • make a statement extend over multiple lines with the brackets [ ] and braces { }. • For example: colors = ['red', 'blue', 'green']
  • 20. • We could also put multiple statements in a single line using semicolons, as follows a = 1; b = 2; c = 3
  • 21. Python Indentation • Most of the programming languages like C, C++, Java use braces { } to define a block of code • Python uses indentation • A code block (body of a function, loop etc.) starts with indentation and ends with the first un-indented line
  • 24. Error due to incorrect indentation
  • 25. Python Comments • To make the code much more readable. • Python Interpreter ignores comment. • Two types of comment is possible in python: • Single line comment and • Multi-line comment
  • 26. Single line comment • In Python, we use the hash (#) symbol to start writing a comment. • It extends up to the newline character
  • 27. Multi-line comments • Two way: • By using # sign at the beginning of each line #This is a long comment #and it extends #to multiple lines • By using either ‘ ‘ ‘ or “ “ “ (most common) """This is also a perfect example of multi-line comments"""
  • 28. Python Variable • a variable is a named location used to store data in the memory. • Alternatively, variables are container that hold data which can be changed later throughout programming
  • 29. Declaring Variables • In Python, variables do not need declaration to reserve memory space. • The "variable declaration" or "variable initialization" happens automatically when we assign a value to a variable. • We use the assignment operator = to assign the value to a variable.
  • 30. Assigning Values to variables
  • 32. Changing value of a variable
  • 34. Assigning same value to the multiple variable
  • 36. Assigning multiple values to multiple variables
  • 38. Constants • Value that cannot be altered by the program during normal execution. • In Python, constants are usually declared and assigned on a module • And then imported to the file
  • 42. Rules and Naming convention for variables and constants • Create a name that makes sense. Suppose, vowel makes more sense than v. • Use camelCase notation to declare a variable • For example: myName, myAge, myAddress • Use capital letters where possible to declare a constant • For example: PI,G,MASS etc.
  • 43. • Never use special symbols like !, @, #, $, %, etc. • Don't start name with a digit. • Constants are put into Python modules • Constant and variable names should have combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). • For example: snake_case, MACRO_CASE, camelCase, CapWords
  • 44. Literals • Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows: • Numeric literals • String literals • Boolean literals • Special literals
  • 57. Data Types • In python data types are classes and variables are instance (object) of these classes • Different types of data types in python are: • Python numbers • Python lists • Python tuples • Python strings • Python sets • Python dictionary
  • 60. Python List • Ordered sequence of items • Can contain heterogeneous data • Syntax: • Items separated by commas are enclosed within brackets [ ] • Example: a= [1,2.2,'python']
  • 63. • Note: Lists are mutable, meaning, value of elements of a list can be altered.
  • 64. Python Tuple • Same as list but immutable. • Used to write-protect the data • Syntax: • Items separated by commas are enclosed within brackets ( ) • Example: • t = (5,'program', 1+3j)
  • 69. Python Strings • use single quotes or double quotes to represent strings. • Multi-line strings can be denoted using triple quotes, ''' or """. • Example: s = "This is a string" s = '''a multiline string’’’ • Strings are also immutable.
  • 72. Python Set • Unordered collection of unique items • defined by values separated by comma inside braces { }
  • 74. • Set have unique values. They eliminate duplicates. • Example:
  • 75. • Since, set are unordered collection, indexing has no meaning. • Hence the slicing operator [] does not work. • Example:
  • 76. Python Dictionary • An unordered collection of key-value pairs. • Must know the key to retrieve the value. • Are defined within braces {} with each item being a pair in the form key: value • Key and value can be of any type
  • 79. Conversion between data types • Conversion can be done by using different types of type conversion functions like: • int(), • float(), • str() etc.
  • 82. To and form string
  • 83. convert one sequence to another
  • 84. • To convert to dictionary, each element must be a pair:
  • 85. Python Type Conversion and Type Casting • The process of converting the value of one data type (integer, string, float, etc.) to another data type is type conversion • Python has two types of type conversion. • Implicit Type Conversion • Explicit Type Conversion
  • 86. • Type Conversion is the conversion of object from one data type to another data type • Implicit Type Conversion is automatically performed by the Python interpreter • Python avoids the loss of data in Implicit Type Conversion • Explicit Type Conversion is also called Type Casting, the data types of object are converted using predefined function by user • In Type Casting loss of data may occur as we enforce the object to specific data type
  • 87. Implicit Type Conversion • Automatically converts one data type to another data type • Always converts smaller data type to larger data type to avoid the loss of data
  • 89. Problem in implicit type conversion
  • 91. Explicit Type Conversion • Users convert the data type of an object to required data type. • Predefined functions like int(), float(), str(), etc. are to perform explicit type conversion • Is also called typecasting because the user casts (change) the data type of the objects. • Syntax : • (required_datatype)(expression) • Int(b)
  • 94. Python Input, Output and Import • Widely used functions for standard input and output operations are: • print() and • input()
  • 95. Python Output Using print() function
  • 96. Output formatting • Can be done by using the str.format() method • Is visible to any string object • Here the curly braces {} are used as placeholders. We can specify the order in which it is printed by using numbers (tuple index).
  • 98. • We can even use keyword arguments to format the string
  • 99. • We can even format strings like the old printf() style used in C • We use the % operator to accomplish this
  • 100. Input() function • input() function to take the input from the user. • The syntax for input() is : • input([prompt]) • where prompt is the string we wish to display on the screen. • It is optional
  • 101. • Entered value 10 is a string, not a number. • To convert this into a number we can use int() or float() functions • This same operation can be performed using the eval(). It can evaluate expressions, provided the input is a string.
  • 102. Python Import • When our program grows bigger, it is a good idea to break it into different modules. • A module is a file containing Python definitions and statements. • Python modules have a filename and end with the extension .py • Definitions inside a module can be imported to another module or the interactive interpreter in Python • We use the import keyword to do this
  • 104. • import some specific attributes and functions only, using the from keyword.
  • 105. Python Operators • Operators are special symbols in Python that carry out arithmetic or logical computation. • The value that the operator operates on is called the operand. • For example: >>> 2+3 5 • Here, + is the operator that performs addition. • 2 and 3 are the operands and 5 is the output of the operation.
  • 112. Bitwise operators • Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name. • For example, 2 is 10 in binary and 7 is 111. • In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
  • 114. Assignment operators • Assignment operators are used in Python to assign values to variables. • a = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. • There are various compound operators in Python like a += 5 that adds to the variable and later assigns the same. • It is equivalent to a = a + 5.
  • 116. Special operators • identity operator • membership operator
  • 117. Identity operators • is and is not are the identity operators in Python. • They are used to check if two values (or variables) are located on the same part of the memory. • Two variables that are equal does not imply that they are identical.
  • 119. Membership operators • in and not in are the membership operators in Python • They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary). • In a dictionary we can only test for presence of key, not the value
  • 121. Python Namespace and Scope • Name (also called identifier) is simply a name given to objects. • Everything in Python is an object • Name is a way to access the underlying object. • For example: • when we do the assignment a = 2, here 2 is an object stored in memory and a is the name we associate it with • We can get the address (in RAM) of some object through the built-in function, id()
  • 125. A name could refer to any type of object
  • 126. Functions are objects too, so a name can refer to them as well
  • 127. What is a Namespace in Python? • namespace is a collection of names. • Help to eliminate naming collision/naming conflict
  • 128. • A namespace containing all the built-in names is created when we start the Python interpreter and exists as long we don't exit • Each module creates its own global namespace • Modules can have various user defined functions and classes. • A local namespace is created when a function is called, which has all the names defined in it. • Similar, is the case with class
  • 130. Python Variable Scope • All namespaces may not be accessible from every part of the program • Scope is the portion of the program from where a namespace can be accessed directly without any prefix
  • 131. • At any given moment, there are at least three nested scopes. • Scope of the current function which has local names • Scope of the module which has global names • Outermost scope which has built-in names • When a reference is made inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace. • If there is a function inside another function, a new scope is nested inside the local scope.