Movatterモバイル変換


[0]ホーム

URL:


KA
Uploaded byKamal Acharya
PPTX, PDF15,144 views

Fundamentals of Python Programming

The document provides an introduction to Python programming including its features, uses, history, and installation process. Some key points covered include:- Python is an interpreted, object-oriented programming language that is used for web development, scientific computing, and desktop applications. - It was created by Guido van Rossum in 1991 and named after the Monty Python comedy group.- To install Python on Windows, users download the latest version from python.org and run the installer, which also installs the IDLE development environment.- The document then covers basic Python concepts like variables, data types, operators, and input/output functions.

Embed presentation

Downloaded 711 times
Fundamentals of PythonProgramming
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'sFlying 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 Python3.6.5 (You may see different version name)• When the download is completed, double-click the file and follow theinstructions to install it.• When Python is installed, a program called IDLE is also installed alongwith 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 extensionlike: hello.py or your-first-program.pyprint("Hello, World!")• Go to Run > Run module (Shortcut: F5) and you can see the output.
First Python Program
Second Program
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 (unlikelanguages like C/C++)• In fact, it's recommended to omit semicolon at the end of thestatement 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) inPython• 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) ordigits (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 firstletter of the word except the initial word without any spaces• camelCaseExample
Python Statement• Instructions that a Python interpreter can execute are calledstatements.• 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 continuationcharacter ().• 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 usingsemicolons, as followsa = 1; b = 2; c = 3
Python Indentation• Most of the programming languages like C, C++, Java use braces { } todefine a block of code• Python uses indentation• A code block (body of a function, loop etc.) starts with indentationand ends with the first un-indented line
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 aperfect example ofmulti-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 bechanged later throughout programming
Declaring Variables• In Python, variables do not need declaration to reserve memoryspace.• The "variable declaration" or "variable initialization" happensautomatically when we assign a value to a variable.• We use the assignment operator = to assign the value to a variable.
Assigning Values to variables
Changing value of a variable
Assigning same value to the multiple variable
Assigning multiple values to multiple variables
Constants• Value that cannot be altered by the program during normalexecution.• In Python, constants are usually declared and assigned on a module• And then imported to the file
Defining constantModule
Rules and Naming convention for variablesand constants• Create a name that makes sense. Suppose, vowel makes more sensethan 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 inlowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or anunderscore (_).• For example: snake_case, MACRO_CASE, camelCase, CapWords
Literals• Literal is a raw data given in a variable or constant. In Python, thereare various types of literals they are as follows:• Numeric literals• String literals• Boolean literals• Special literals
Numeric Literals
String Literals
Docstrings
Using boolean literals
Special literal(None)
Literals Collection
Data Types• In python data types are classes and variables are instance (object) ofthese classes• Different types of data types in python are:• Python numbers• Python lists• Python tuples• Python strings• Python sets• Python dictionary
Python Numbers
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
• Note: Lists are mutable, meaning, value of elements of a list can bealtered.
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)
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 multilinestring’’’• Strings are also immutable.
Python Set• Unordered collection of unique items• defined by values separated by comma inside braces { }
• 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 formkey: value• Key and value can be of any type
Conversion between data types• Conversion can be done by using different types of type conversionfunctions 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 toanother data type• Implicit Type Conversion is automatically performed by the Pythoninterpreter• Python avoids the loss of data in Implicit Type Conversion• Explicit Type Conversion is also called Type Casting, the data types ofobject are converted using predefined function by user• In Type Casting loss of data may occur as we enforce the object tospecific 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 lossof data
Problem in implicit type conversion
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 explicittype conversion• Is also called typecasting because the user casts (change) the datatype of the objects.• Syntax :• (required_datatype)(expression)• Int(b)
Example
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 theorder 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 canevaluate expressions, provided the input is a string.
Python Import• When our program grows bigger, it is a good idea to break it intodifferent 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 orthe interactive interpreter in Python• We use the import keyword to do this
• import some specific attributes and functions only, using the fromkeyword.
Python Operators• Operators are special symbols in Python that carry out arithmetic orlogical computation.• The value that the operator operates on is called the operand.• For example:>>> 2+35• 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
Logical operators
Bitwise operators• Bitwise operators act on operands as if they were string of binarydigits. 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 (00000100 in binary)
Assignment operators• Assignment operators are used in Python to assign values tovariables.• a = 5 is a simple assignment operator that assigns the value 5 on theright to the variable a on the left.• There are various compound operators in Python like a += 5 that addsto the variable and later assigns the same.• It is equivalent to a = a + 5.
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 thesame part of the memory.• Two variables that are equal does not imply that they are identical.
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 asequence (string, list, tuple, set and dictionary).• In a dictionary we can only test for presence of key, not the value
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 ais the name we associate it with• We can get the address (in RAM) of some object through the built-in function,id()
A name could refer to any type of object
Functions are objects too, so a name canrefer 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 westart 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 allthe names defined in it.• Similar, is the case with class
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 beaccessed 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 inthe local namespace, then in the global namespace and finally in thebuilt-in namespace.• If there is a function inside another function, a new scope is nestedinside the local scope.
Thank You !

Recommended

PDF
Python-01| Fundamentals
PPTX
Python basics
PPT
Python ppt
PDF
An Introduction to Python Programming
PPTX
Python Programming Language
PPT
Introduction to Python
PDF
Python course syllabus
PPTX
Python presentation by Monu Sharma
PPTX
Introduction to python
PDF
Introduction to python programming
PPTX
Introduction to python for Beginners
PPTX
Python basics
PDF
Python final ppt
PDF
Python exception handling
PPTX
Introduction to Basics of Python
PPT
Python Programming Language
 
PPT
Python Programming ppt
PPTX
Looping statement in python
PDF
Python basic
PPTX
Functions in python
PPTX
Python Functions
PPTX
Python programming | Fundamentals of Python programming
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PDF
Python Basics
PDF
List,tuple,dictionary
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PDF
Variables & Data Types In Python | Edureka
PPT
1.python interpreter and interactive mode
PDF
Python Programming
PPTX
introduction to python

More Related Content

PDF
Python-01| Fundamentals
PPTX
Python basics
PPT
Python ppt
PDF
An Introduction to Python Programming
PPTX
Python Programming Language
PPT
Introduction to Python
PDF
Python course syllabus
PPTX
Python presentation by Monu Sharma
Python-01| Fundamentals
Python basics
Python ppt
An Introduction to Python Programming
Python Programming Language
Introduction to Python
Python course syllabus
Python presentation by Monu Sharma

What's hot

PPTX
Introduction to python
PDF
Introduction to python programming
PPTX
Introduction to python for Beginners
PPTX
Python basics
PDF
Python final ppt
PDF
Python exception handling
PPTX
Introduction to Basics of Python
PPT
Python Programming Language
 
PPT
Python Programming ppt
PPTX
Looping statement in python
PDF
Python basic
PPTX
Functions in python
PPTX
Python Functions
PPTX
Python programming | Fundamentals of Python programming
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
PDF
Python Basics
PDF
List,tuple,dictionary
PDF
Python Programming Language | Python Classes | Python Tutorial | Python Train...
PDF
Variables & Data Types In Python | Edureka
PPT
1.python interpreter and interactive mode
Introduction to python
Introduction to python programming
Introduction to python for Beginners
Python basics
Python final ppt
Python exception handling
Introduction to Basics of Python
Python Programming Language
 
Python Programming ppt
Looping statement in python
Python basic
Functions in python
Python Functions
Python programming | Fundamentals of Python programming
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Basics
List,tuple,dictionary
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Variables & Data Types In Python | Edureka
1.python interpreter and interactive mode

Similar to Fundamentals of Python Programming

PDF
Python Programming
PPTX
introduction to python
PPTX
INTRODUCTION TO PYTHON.pptx
PPTX
Python 01.pptx
PPTX
Chapter7-Introduction to Python.pptx
PPTX
Introduction to Python Programming .pptx
PDF
Python quick guide
PPT
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
PPTX
Python programming fundamentals for class 12
PDF
Computer Related material named Phython ok
PDF
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
PPTX
BASICS OF PYTHON usefull for the student who would like to learn on their own
PPTX
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
PPTX
PROGRAMMING-QUARTER-2-PYTHON.pptxnsnsndn
PDF
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
PDF
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PPTX
introduction to python programming concepts
PPTX
python_class.pptx
PPTX
Introduction to python for the abs .pptx
PPTX
Python Traning presentation
Python Programming
introduction to python
INTRODUCTION TO PYTHON.pptx
Python 01.pptx
Chapter7-Introduction to Python.pptx
Introduction to Python Programming .pptx
Python quick guide
notwa dfdfvs gf fdgfgh s thgfgh frg reggg
Python programming fundamentals for class 12
Computer Related material named Phython ok
Py-Slides- easuajsjsjejejjwlqpqpqpp1.pdf
BASICS OF PYTHON usefull for the student who would like to learn on their own
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
PROGRAMMING-QUARTER-2-PYTHON.pptxnsnsndn
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
introduction to python programming concepts
python_class.pptx
Introduction to python for the abs .pptx
Python Traning presentation

More from Kamal Acharya

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

Recently uploaded

PPTX
Quarter 3 lesson 2 of English Grade 8.pptx
PDF
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
PDF
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
PDF
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
PPTX
Time Series Analysis - Meaning, Definition, Components and Application
PDF
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni
PDF
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
PPTX
Photography Pillar 1 The Subject PowerPoint
PPTX
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
PPTX
What are New Features in Purchase _Odoo 18
PDF
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
PPTX
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
PDF
DEFINITION OF COMMUNITY Sociology. .pdf
PPTX
Plant Breeding: Its History and Contribution
PDF
The invasion of Alexander of Macedonia in India
PPTX
Time Series Analysis - Weighted (Unequal) Moving Average Method
PPTX
Elderly in India: The Changing Scenario.pptx
 
PPTX
Declaration of Helsinki Basic principles in medical research ppt.pptx
PPTX
General Wellness & Restorative Tonic: Draksharishta
PPTX
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK
Quarter 3 lesson 2 of English Grade 8.pptx
AI and ICT for Teaching and Learning, Induction-cum-Training Programme, 5th 8...
Risk Management and Regulatory Compliance - by Ms. Oceana Wong
“Step-by-Step Fabrication of Bipolar Junction Transistors (BJTs)”
Time Series Analysis - Meaning, Definition, Components and Application
Cattolica University - Lab Generative and Agentic AI - Mario Bencivinni
LH_Lecture Note on Spices , AI And Importance in Human Life.pdf
Photography Pillar 1 The Subject PowerPoint
Finals - History and Geography Quiz - Around the World in 80 Questions - IITK
What are New Features in Purchase _Odoo 18
Past Memories and a New World: Photographs of Stoke Newington from the 70s, 8...
kklklklklklklklk;lkpoipor[3rjdkjoe99759893058085
DEFINITION OF COMMUNITY Sociology. .pdf
Plant Breeding: Its History and Contribution
The invasion of Alexander of Macedonia in India
Time Series Analysis - Weighted (Unequal) Moving Average Method
Elderly in India: The Changing Scenario.pptx
 
Declaration of Helsinki Basic principles in medical research ppt.pptx
General Wellness & Restorative Tonic: Draksharishta
Prelims - History and Geography Quiz - Around the World in 80 Questions - IITK

Fundamentals of Python Programming

  • 1.
  • 2.
    Introduction to pythonprogramming• 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 featuresof python includes the following:• Simple language which is easier to learn• Free and open source• Portability• Extensible and embeddable• Standard large library
  • 4.
    • Created byGuido 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'sFlying Circus".
  • 5.
    Reasons to ChoosePython as First Language• Simple Elegant Syntax• Not overly strict• Expressiveness of the language• Great Community and Support
  • 6.
    Installation of Pythonin Windows• Go to Download Python page on the official site(https://www.python.org/downloads/) and click Download Python3.6.5 (You may see different version name)• When the download is completed, double-click the file and follow theinstructions to install it.• When Python is installed, a program called IDLE is also installed alongwith 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 extensionlike: hello.py or your-first-program.pyprint("Hello, World!")• Go to Run > Run module (Shortcut: F5) and you can see the output.
  • 8.
  • 10.
  • 12.
    Few Important Thingsto Remember• To represent a statement in Python, newline (enter) is used.• Use of semicolon at the end of the statement is optional (unlikelanguages like C/C++)• In fact, it's recommended to omit semicolon at the end of thestatement in Python• Instead of curly braces { }, indentations are used to represent a block
  • 13.
    Python Keywords• Keywordsare the reserved words(can not be used as a identifier) inPython• Are case sensitive
  • 14.
    Python Identifiers• Namegiven 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) ordigits (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 careabout• 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 firstletter of the word except the initial word without any spaces• camelCaseExample
  • 16.
    Python Statement• Instructionsthat a Python interpreter can execute are calledstatements.• 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:• makea statement extend over multiple lines with the line continuationcharacter ().• For example:a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
  • 18.
    • Technique2:• makea statement extend over multiple lines with the parentheses ( )• For example:a = (1 + 2 + 3 +4 + 5 + 6 +7 + 8 + 9)
  • 19.
    • Technique3:• makea statement extend over multiple lines with the brackets [ ] and braces {}.• For example:colors = ['red','blue','green']
  • 20.
    • We couldalso put multiple statements in a single line usingsemicolons, as followsa = 1; b = 2; c = 3
  • 21.
    Python Indentation• Mostof the programming languages like C, C++, Java use braces { } todefine a block of code• Python uses indentation• A code block (body of a function, loop etc.) starts with indentationand ends with the first un-indented line
  • 24.
    Error due toincorrect indentation
  • 25.
    Python Comments• Tomake 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• Twoway:• 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 aperfect example ofmulti-line comments"""
  • 28.
    Python Variable• avariable is a named location used to store data in the memory.• Alternatively, variables are container that hold data which can bechanged later throughout programming
  • 29.
    Declaring Variables• InPython, variables do not need declaration to reserve memoryspace.• The "variable declaration" or "variable initialization" happensautomatically when we assign a value to a variable.• We use the assignment operator = to assign the value to a variable.
  • 30.
  • 32.
  • 34.
    Assigning same valueto the multiple variable
  • 36.
    Assigning multiple valuesto multiple variables
  • 38.
    Constants• Value thatcannot be altered by the program during normalexecution.• In Python, constants are usually declared and assigned on a module• And then imported to the file
  • 39.
  • 42.
    Rules and Namingconvention for variablesand constants• Create a name that makes sense. Suppose, vowel makes more sensethan 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 usespecial 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 inlowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or anunderscore (_).• For example: snake_case, MACRO_CASE, camelCase, CapWords
  • 44.
    Literals• Literal isa raw data given in a variable or constant. In Python, thereare various types of literals they are as follows:• Numeric literals• String literals• Boolean literals• Special literals
  • 45.
  • 47.
  • 49.
  • 51.
  • 53.
  • 55.
  • 57.
    Data Types• Inpython data types are classes and variables are instance (object) ofthese classes• Different types of data types in python are:• Python numbers• Python lists• Python tuples• Python strings• Python sets• Python dictionary
  • 58.
  • 60.
    Python List• Orderedsequence of items• Can contain heterogeneous data• Syntax:• Items separated by commas are enclosed within brackets [ ]• Example: a= [1,2.2,'python']
  • 61.
  • 63.
    • Note: Listsare mutable, meaning, value of elements of a list can bealtered.
  • 64.
    Python Tuple• Sameas 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• usesingle 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 multilinestring’’’• Strings are also immutable.
  • 72.
    Python Set• Unorderedcollection of unique items• defined by values separated by comma inside braces { }
  • 74.
    • Set haveunique values. They eliminate duplicates.• Example:
  • 75.
    • Since, setare unordered collection, indexing has no meaning.• Hence the slicing operator [] does not work.• Example:
  • 76.
    Python Dictionary• Anunordered 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 formkey: value• Key and value can be of any type
  • 79.
    Conversion between datatypes• Conversion can be done by using different types of type conversionfunctions like:• int(),• float(),• str() etc.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
    • To convertto dictionary, each element must be a pair:
  • 85.
    Python Type Conversionand 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 Conversionis the conversion of object from one data type toanother data type• Implicit Type Conversion is automatically performed by the Pythoninterpreter• Python avoids the loss of data in Implicit Type Conversion• Explicit Type Conversion is also called Type Casting, the data types ofobject are converted using predefined function by user• In Type Casting loss of data may occur as we enforce the object tospecific 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 lossof data
  • 89.
    Problem in implicittype 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 explicittype conversion• Is also called typecasting because the user casts (change) the datatype of the objects.• Syntax :• (required_datatype)(expression)• Int(b)
  • 92.
  • 94.
    Python Input, Outputand Import• Widely used functions for standard input and output operations are:• print() and• input()
  • 95.
    Python Output Usingprint() function
  • 96.
    Output formatting• Canbe done by using the str.format() method• Is visible to any string object• Here the curly braces {} are used as placeholders. We can specify theorder in which it is printed by using numbers (tuple index).
  • 97.
  • 98.
    • We caneven use keyword arguments to format the string
  • 99.
    • We caneven 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 value10 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 canevaluate expressions, provided the input is a string.
  • 102.
    Python Import• Whenour program grows bigger, it is a good idea to break it intodifferent 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 orthe interactive interpreter in Python• We use the import keyword to do this
  • 104.
    • import somespecific attributes and functions only, using the fromkeyword.
  • 105.
    Python Operators• Operatorsare special symbols in Python that carry out arithmetic orlogical computation.• The value that the operator operates on is called the operand.• For example:>>> 2+35• Here, + is the operator that performs addition.• 2 and 3 are the operands and 5 is the output of the operation.
  • 106.
  • 107.
  • 108.
  • 110.
  • 112.
    Bitwise operators• Bitwiseoperators act on operands as if they were string of binarydigits. 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 (00000100 in binary)
  • 114.
    Assignment operators• Assignmentoperators are used in Python to assign values tovariables.• a = 5 is a simple assignment operator that assigns the value 5 on theright to the variable a on the left.• There are various compound operators in Python like a += 5 that addsto the variable and later assigns the same.• It is equivalent to a = a + 5.
  • 116.
    Special operators• identityoperator• membership operator
  • 117.
    Identity operators• isand is not are the identity operators in Python.• They are used to check if two values (or variables) are located on thesame part of the memory.• Two variables that are equal does not imply that they are identical.
  • 119.
    Membership operators• inand not in are the membership operators in Python• They are used to test whether a value or variable is found in asequence (string, list, tuple, set and dictionary).• In a dictionary we can only test for presence of key, not the value
  • 121.
    Python Namespace andScope• 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 ais 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 couldrefer to any type of object
  • 126.
    Functions are objectstoo, so a name canrefer to them as well
  • 127.
    What is aNamespace in Python?• namespace is a collection of names.• Help to eliminate naming collision/naming conflict
  • 128.
    • A namespacecontaining all the built-in names is created when westart 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 allthe 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 beaccessed directly without any prefix
  • 131.
    • At anygiven 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 inthe local namespace, then in the global namespace and finally in thebuilt-in namespace.• If there is a function inside another function, a new scope is nestedinside the local scope.
  • 135.

[8]ページ先頭

©2009-2025 Movatter.jp