SlideShare uma empresa Scribd logo
1 de 37
POWERED BY
RANA ALI
PYTHON PROGRAMMING
LANGUAGE (OVERVIEW)
The Python Programming Language
Audience
• Having basic understanding of programming or worked
on any High Level language like C, JAVA, or C ++, etc
At the end you will be able:
• Understand the significance of Python Programming
• Familiarize with the Python IDE Environment
• Understand the Input and Output operations in Python
• Use variables in Python language
What is Python Programming
• Python was developed by Guido van Rossum
(a Dutch programmer) in 1991
• Python is a High Level Language (whereas C and
Java are not High Level Language)
• Python has a design philosophy that emphasizes
Code Readability
• The syntax allows programmer to express
concepts in fewer lines of code than might be
used in languages such as C++, Java etc
Why Python Programming
According to IEEE Spectrum the top Programming Languages in
2017 are:
http://spectrum.ieee.org/computing/software/the-2017-top-programming-languages
Because it Easy to learn and use: Its simple
syntax is very accessible to programming
novices and will look familiar to anyone with
experience in Matlab, C/C++, Java. Also
Python has powerful libraries
Why Python Programming
• Because it is FREE
There is no worried of buying the key and or unethical use of software by
cracking its key
• Because it is Open Source
Why Python Programming
In the Open Source software the
source code, blue print and
documentation are freely available to
public. The software developer
voluntarily put their part to add the
features in the software
Python has vast development implementation
Python Cross-compilers to other languages
Python Web development frameworks
Python in other Science
Python has Powerful Libraries
Who uses Python
How to Learn Python
Working on Python IDLE
Download Python IDLE 2.x or 3.x from Python Software Foundation
Website for Free
Python IDLE Environment
IDLE (Integrated Development Learning Environment)
• IDLE has multi-window text editor with syntax highlighting,
auto-completion, smart indent
• The Shell window execute command at the statement
complete
• User code written in Text Editor window
Some Useful command for Python IDLE Shell
window
• Alt + p to retrieve Previous Command
• Alt + n to retrieve Next Command
• To get help of instruction or command use
help(instruction)
Python IDLE Environment
My First Python Program
Open Python IDLE Shell window and write the following
instruction
A print is an output instruction use to display string or
data value on screen
print(“HELLO")
Note: Program contain no header file, no main() function,
no semi column at instruction end, even you write string
in single quotation mark. BUT one thing common with
other programming language that is Case Sensitive
print(‘HELLO‘)
Output Instruction
Escape Sequence Working
 Backslash ()
' Single quote (')
" Double quote (")
n ASCII Linefeed (LF)
t ASCII Horizontal Tab (TAB)
Example:
>>>print('BackslashtTabnNewline')
Backslash Tab
Newline`
The following are the Escape Sequence use with
print instruction
Python Data types
Python has five standard data types
• Numbers(Integer and Float)
• String
• List (Array)
• Tuple (Constant Array)
• Dictionary
Variable Number type:
• Integer (whole number)
• Float (decimal point number)
• Character/String (ASCII format)
• Boolean (True and False)
Python Variable
• Type of Variable: Check the type of Variable
• Deleting Variable: Delete the declare variable
Syntax: del(variable_name)
>>> a = 2
>>> print(a)
2
>>> del(a)
>>> print(a)
NameError: name 'a' is not defined
Variable value Type command Result
a=2 type(a) <class 'int'>
b=3.5 type(b) <class 'float'>
c=’f’ type(c) <class 'str'>
d=’abc123’ type(d) <class 'str'>
type(True) <class 'bool'>
type(False) <class 'bool'>
Python is an Interpreter Language
Working Compiler Interpreter
Converting code Convert whole code Step by step
Translation time Slow Fast
Execution time Fast Slow
Programming Languages
C, Visual Basic, Java,
LabView etc
Python, Matlab, PHP, MS
Excel etc
Python Interpreter Example
In Interpreter, if code contains error it may run
partially and stop when error occurs. In the
following code Error is present in line number 7 that
is “d=B” where ‘B’ is not define before, so program
runs and execute up to that line.
Input Instruction
• Input Instruction: To take an input from user through
keyboard input() command is used, this instruction take
input from keyboard in the form of ASCII character and
store it the variable.
• Syntax:
take_input = input(1 Argument)
• Example:
name = input('Enter your name =')
age = input('Enter your age = ')
print('Your name is ', name , ',and your age is = ',age)
Python Version
• Python Version 1 is obsolete now
• Python Version 2 and Python Version 3 is active
• The Python 2 is old version but retain for programming
because lots of module was developed on it which not
work with Python 3
• There is only some difference in execution of
instructions other wise both have same working
Difference between Python 2 and Python 3
Output Instruction
Python 2 Python 3
Python 2 allows to write the print
instruction argument with in Round
bracket ( and) or with out it.
The argument of the print instruction must
written with in Round bracket ( and)
>>> print('String') #Allow
String
>>> print("String") #Allow
String
>>> print 'String' #Allow
String
>>> print "String" #Allow
String
>>> print('String') #Allow
String
>>> print("String") #Allow
String
>>> print 'String' #NotAllow
SyntaxError: Missing parentheses in call to 'print‘
>>> print "String" #NotAllow
SyntaxError: Missing parentheses in call to 'print‘
Difference between Python 2 and Python 3
Input Instruction
Python 2 Python 3
input(prompt) raw_input(prompt) Input(prompt)
It keeps the type of user
enter data
Automatically update the
Input variable to the user
enter data
Always take data in the
string format regardless of
the user enter data
Syntax:
Input_variable = input(prompt)
Input_variable data type is
same as user enter data
Syntax:
Input_variable = input(prompt)
Input_variable is String
Syntax:
Input_variable = input(prompt)
Input_variable is String
Input Instruction Example
Python 2 Python 3
input(prompt) raw_input(prompt) Input(prompt)
>>> a = input("Enter = ")
Enter = 12
>>> type(a)
<type 'int'>
>>> a = input("Enter = ")
Enter = 12.12
>>> type(a)
<type 'float'>
>>> a = input("Enter = ")
Enter = "Ab12"
>>> type(a)
<type 'str'>
>>> a = input("Enter = ")
Enter = Ab12
NameError: name 'Ab12' is not
defined
>>> a = raw_input("Enter = ")
Enter = 12
>>> type(a)
<type 'str'>
>>> a = raw_input("Enter = ")
Enter = 12.12
>>> type(a)
<type 'str'>
>>> a = raw_input("Enter = ")
Enter = "Ab12"
>>> type(a)
<type 'str'>
>>> a = raw_input("Enter = ")
Enter = Ab12
>>> type(a)
<type 'str'>
>>> a = input("Enter = ")
Enter = 12
>>> type(a)
<class 'str'>
>>> a = input("Enter = ")
Enter = 12.12
>>> type(a)
<class 'str'>
>>> a = input("Enter = ")
Enter = "Ab12"
>>> type(a)
<class 'str'>
>>> a = input("Enter = ")
Enter = Ab12
>>> type(a)
<class 'str'>
Difference between Python 2 and Python 3
Difference between Python 2 and Python 3
(problem and its solution)
Python 2 Python 3
Program
num = input('Enter a number = ')
print num,‘x 3 = ',num * 3
num = input('Enter a number = ')
print( num,‘x 3 = ',num * 3 )
Output
Enter a number = 5
5 x 3 = 15
Enter a number = 5
5 x 3 = 555
Observation: the num is integer so
number 5 x 3 is number 15
Observation: the num is String so String 5
x 3 is three times of number 5
The problem in the output of Python 3 is
solved in later slides
Change the variable type
Function Description
Example
Instruction Output
str(x) Converts object x to a string representation.
str(75)
str("25.25")
‘75’
'25.25'
int(x) Converts object x to a integer number.
int(35.26)
int(100.101 )
35
100
float(x) Converts object x to a float number.
float(35)
float(100)
35.0
100.0
list(s) Converts s to a list.
list(range(5,10))
list(range(1,10,2))
[5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
tuple(s) Converts s to a tuple.
tuple(range(5,10))
tuple(range(1,10,2))
(5, 6, 7, 8, 9)
(1, 3, 5, 7, 9)
dict(d)
Creates a dictionary. d must be a sequence
of (key,value) tuples.
chr(x) Converts an integer to a character.
chr(65)
chr(97)
'A‘
‘a’
ord(x) Converts a single character to its ASCII (integer value)
ord('A')
ord(‘a')
65
97
hex(x) Converts an integer to a hexadecimal string.
hex(16)
hex(100)
'0x10‘
'0x64'
oct(x) Converts an integer to an octal string.
oct(9)
oct(50)
'0o11‘
'0o62'
Exercise
Rewrite the following program in Python 3 with
correct output display
Without changing Variable Type Changing Variable Type
num = input(“Enter a number = “)
print( num,”x 3 = “,num * 3 )
num = input(“Enter a number = “)
print( num,“x 3 = ",int(num) * 3 )
3 x 3 = 333 3 x 3 = 9
Python IDEs
• Python IDLE
• PyCharm
• Sublime Text
• Atom
• Geany
• Anjuta
• Eric
• Komodo IDE
• KDevelop
• Ninja-IDE
•
• Spyder
Integer Operation
Function Description
bit_length(...)
Number of bits necessary to represent self in binary
Example: >>> (37).bit_length() 6
>>> int_num.bit_length() 2
bin(…)
Return binary of the integer
Example: >>> bin(37) '0b100101'
>>> bin(25) '0b1111111'
Denominator The denominator of a rational number in lowest terms
Imag The imaginary part of a complex number
numerator The numerator of a rational number in lowest terms
real The real part of a complex number
conjugate(...) Returns self, the complex conjugate of any int.
to_bytes(...) Return an array of bytes representing an integer.
Float Operation
Function Description
float.fromhex (...)
Create a floating-point number
from a hexadecimal string.
Example: >>>float.fromhex('0x1.ffffp10') 2047.984375
float.hex(…)
Return a hexadecimal representation of a floating-point number
Example: >>>3.14159.hex() '0x1.921f9f01b866ep+1'
is_integer(...)
Return True if the float is an integer
Example: >>> num = 5.5
>>> num.is_integer() False
>>> num = num - 0.5 # remove floating value
>>> num.is_integer() True
as_integer_ratio(...)
Return a pair of integers, whose ratio is exactly equal to the original float and
with a positive denominator.
Example: >>> (10.0).as_integer_ratio() (10, 1)
>>> (0.0).as_integer_ratio() (0, 1)
>>> (-.25).as_integer_ratio() (-1, 4)
conjugate(...) Return self, the complex conjugate of any float.
imag The imaginary part of a complex number
Real The real part of a complex number
String Operation
Function Description
len(string) Return length of string
capitalize(...)
Return a capitalized version of S, i.e. make the first character have upper
case and the rest lower case.
title(...)
Return a title cased version of S, i.e. words start with title case characters,
and all remaining cased characters have lower case.
lower(...) Return a copy of the string S converted to lowercase.
upper(...) Return a copy of S converted to uppercase.
casefold(...) Return a version of S suitable for caseless comparisons
islower(...)
Return True if all cased characters in S are lowercase and there is at least one
cased character in S, False otherwise.
isupper(...)
Return True if all cased characters in S are uppercase and there is at least
one cased character in S, False otherwise.
isnumeric(...) Return True if there are only numeric characters in S, False otherwise.
isdecimal(...) Return True if there are only decimal characters in S, False otherwise
isdigit(...)
Return True if all characters in S are digits and there is at least one character
in S, False otherwise.
a = input("Enter your name:")
print("Lower Case of Enter string = " ,a.lower())
print("Upper Case of Enter string = " , a.upper())
print("Title Case of Enter string = " , a.title())
print("Length of Enter string = " , len(a))
print("Your Enter string is Alpha = " , a.isalpha())
print("Your Enter string is Decimal = " , a.isdecimal())
print("Your Enter string is Digit = " , a.isdigit())
print("Your Enter string is in Lower case = " , a.islower())
print("Your Enter string is in Upper case = " , a.isupper())
print("Your Enter string is in Title case = " , a.istitle())
Output 1:
Enter your name:Hamdard university
Lower Case of Enter string = hamdard university
Upper Case of Enter string = HAMDARD UNIVERSITY
Title Case of Enter string = Hamdard University
Length of Enter string = 18
Your Enter string is Alpha = False
Your Enter string is Decimal = False
Your Enter string is Digit = False
Your Enter string is in Lower case = False
Your Enter string is in Upper case = False
Your Enter string is in Title case = False
Output 2:
Enter your name:123456
Lower Case of Enter string = 123456
Upper Case of Enter string = 123456
Title Case of Enter string = 123456
Length of Enter string = 6
Your Enter string is Alpha = False
Your Enter string is Decimal = True
Your Enter string is Digit = True
Your Enter string is in Lower case = False
Your Enter string is in Upper case = False
Your Enter string is in Title case = False
String Operation Example
Comparing Python with C/C++
Programming Parameter Python Language C/C++ Language
Programming type Interpreter Compiler
Programming Language High level Language Middle level Language
Header file import #include
Code block Whitespace Indentation
Code within curly bracket
{ code}
Single line statement
termination
Nothing Semicolon ;
Control flow (Multi line)
statement termination
Colon : Nothing
Single line comments # comments //comments
Multi-line comments
‘’’
Comments lines
‘’’
/*
Comments lines
*/
If error code found Partial run code until find error
Did not run until error is
present
Program length Take fewer lines Take relatively more lines
THANK YOU

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Data types in python
Data types in pythonData types in python
Data types in python
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Python basic
Python basicPython basic
Python basic
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
Tkinter Python Tutorial | Python GUI Programming Using Tkinter Tutorial | Pyt...
 

Semelhante a Python basics

PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
manikamr074
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
Nimrahafzal1
 

Semelhante a Python basics (20)

Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
INTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptxINTRODUCTION TO PYTHON.pptx
INTRODUCTION TO PYTHON.pptx
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
 
Python
PythonPython
Python
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
 
Python ppt
Python pptPython ppt
Python ppt
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Hands on Session on Python
Hands on Session on PythonHands on Session on Python
Hands on Session on Python
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
2022-23TYBSC(CS)-Python Prog._Chapter-1.pptx
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
Python Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdfPython Programming by Dr. C. Sreedhar.pdf
Python Programming by Dr. C. Sreedhar.pdf
 
c_pro_introduction.pptx
c_pro_introduction.pptxc_pro_introduction.pptx
c_pro_introduction.pptx
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 

Python basics

  • 1. POWERED BY RANA ALI PYTHON PROGRAMMING LANGUAGE (OVERVIEW)
  • 2. The Python Programming Language Audience • Having basic understanding of programming or worked on any High Level language like C, JAVA, or C ++, etc At the end you will be able: • Understand the significance of Python Programming • Familiarize with the Python IDE Environment • Understand the Input and Output operations in Python • Use variables in Python language
  • 3. What is Python Programming • Python was developed by Guido van Rossum (a Dutch programmer) in 1991 • Python is a High Level Language (whereas C and Java are not High Level Language) • Python has a design philosophy that emphasizes Code Readability • The syntax allows programmer to express concepts in fewer lines of code than might be used in languages such as C++, Java etc
  • 4. Why Python Programming According to IEEE Spectrum the top Programming Languages in 2017 are: http://spectrum.ieee.org/computing/software/the-2017-top-programming-languages
  • 5. Because it Easy to learn and use: Its simple syntax is very accessible to programming novices and will look familiar to anyone with experience in Matlab, C/C++, Java. Also Python has powerful libraries Why Python Programming
  • 6. • Because it is FREE There is no worried of buying the key and or unethical use of software by cracking its key • Because it is Open Source Why Python Programming In the Open Source software the source code, blue print and documentation are freely available to public. The software developer voluntarily put their part to add the features in the software
  • 7. Python has vast development implementation
  • 8. Python Cross-compilers to other languages
  • 10. Python in other Science
  • 11. Python has Powerful Libraries
  • 13. How to Learn Python
  • 14. Working on Python IDLE Download Python IDLE 2.x or 3.x from Python Software Foundation Website for Free
  • 15. Python IDLE Environment IDLE (Integrated Development Learning Environment) • IDLE has multi-window text editor with syntax highlighting, auto-completion, smart indent • The Shell window execute command at the statement complete • User code written in Text Editor window
  • 16. Some Useful command for Python IDLE Shell window • Alt + p to retrieve Previous Command • Alt + n to retrieve Next Command • To get help of instruction or command use help(instruction) Python IDLE Environment
  • 17. My First Python Program Open Python IDLE Shell window and write the following instruction A print is an output instruction use to display string or data value on screen print(“HELLO") Note: Program contain no header file, no main() function, no semi column at instruction end, even you write string in single quotation mark. BUT one thing common with other programming language that is Case Sensitive print(‘HELLO‘)
  • 18. Output Instruction Escape Sequence Working Backslash () ' Single quote (') " Double quote (") n ASCII Linefeed (LF) t ASCII Horizontal Tab (TAB) Example: >>>print('BackslashtTabnNewline') Backslash Tab Newline` The following are the Escape Sequence use with print instruction
  • 19. Python Data types Python has five standard data types • Numbers(Integer and Float) • String • List (Array) • Tuple (Constant Array) • Dictionary Variable Number type: • Integer (whole number) • Float (decimal point number) • Character/String (ASCII format) • Boolean (True and False)
  • 20. Python Variable • Type of Variable: Check the type of Variable • Deleting Variable: Delete the declare variable Syntax: del(variable_name) >>> a = 2 >>> print(a) 2 >>> del(a) >>> print(a) NameError: name 'a' is not defined Variable value Type command Result a=2 type(a) <class 'int'> b=3.5 type(b) <class 'float'> c=’f’ type(c) <class 'str'> d=’abc123’ type(d) <class 'str'> type(True) <class 'bool'> type(False) <class 'bool'>
  • 21. Python is an Interpreter Language Working Compiler Interpreter Converting code Convert whole code Step by step Translation time Slow Fast Execution time Fast Slow Programming Languages C, Visual Basic, Java, LabView etc Python, Matlab, PHP, MS Excel etc
  • 22. Python Interpreter Example In Interpreter, if code contains error it may run partially and stop when error occurs. In the following code Error is present in line number 7 that is “d=B” where ‘B’ is not define before, so program runs and execute up to that line.
  • 23. Input Instruction • Input Instruction: To take an input from user through keyboard input() command is used, this instruction take input from keyboard in the form of ASCII character and store it the variable. • Syntax: take_input = input(1 Argument) • Example: name = input('Enter your name =') age = input('Enter your age = ') print('Your name is ', name , ',and your age is = ',age)
  • 24. Python Version • Python Version 1 is obsolete now • Python Version 2 and Python Version 3 is active • The Python 2 is old version but retain for programming because lots of module was developed on it which not work with Python 3 • There is only some difference in execution of instructions other wise both have same working
  • 25. Difference between Python 2 and Python 3 Output Instruction Python 2 Python 3 Python 2 allows to write the print instruction argument with in Round bracket ( and) or with out it. The argument of the print instruction must written with in Round bracket ( and) >>> print('String') #Allow String >>> print("String") #Allow String >>> print 'String' #Allow String >>> print "String" #Allow String >>> print('String') #Allow String >>> print("String") #Allow String >>> print 'String' #NotAllow SyntaxError: Missing parentheses in call to 'print‘ >>> print "String" #NotAllow SyntaxError: Missing parentheses in call to 'print‘
  • 26. Difference between Python 2 and Python 3 Input Instruction Python 2 Python 3 input(prompt) raw_input(prompt) Input(prompt) It keeps the type of user enter data Automatically update the Input variable to the user enter data Always take data in the string format regardless of the user enter data Syntax: Input_variable = input(prompt) Input_variable data type is same as user enter data Syntax: Input_variable = input(prompt) Input_variable is String Syntax: Input_variable = input(prompt) Input_variable is String
  • 27. Input Instruction Example Python 2 Python 3 input(prompt) raw_input(prompt) Input(prompt) >>> a = input("Enter = ") Enter = 12 >>> type(a) <type 'int'> >>> a = input("Enter = ") Enter = 12.12 >>> type(a) <type 'float'> >>> a = input("Enter = ") Enter = "Ab12" >>> type(a) <type 'str'> >>> a = input("Enter = ") Enter = Ab12 NameError: name 'Ab12' is not defined >>> a = raw_input("Enter = ") Enter = 12 >>> type(a) <type 'str'> >>> a = raw_input("Enter = ") Enter = 12.12 >>> type(a) <type 'str'> >>> a = raw_input("Enter = ") Enter = "Ab12" >>> type(a) <type 'str'> >>> a = raw_input("Enter = ") Enter = Ab12 >>> type(a) <type 'str'> >>> a = input("Enter = ") Enter = 12 >>> type(a) <class 'str'> >>> a = input("Enter = ") Enter = 12.12 >>> type(a) <class 'str'> >>> a = input("Enter = ") Enter = "Ab12" >>> type(a) <class 'str'> >>> a = input("Enter = ") Enter = Ab12 >>> type(a) <class 'str'> Difference between Python 2 and Python 3
  • 28. Difference between Python 2 and Python 3 (problem and its solution) Python 2 Python 3 Program num = input('Enter a number = ') print num,‘x 3 = ',num * 3 num = input('Enter a number = ') print( num,‘x 3 = ',num * 3 ) Output Enter a number = 5 5 x 3 = 15 Enter a number = 5 5 x 3 = 555 Observation: the num is integer so number 5 x 3 is number 15 Observation: the num is String so String 5 x 3 is three times of number 5 The problem in the output of Python 3 is solved in later slides
  • 29. Change the variable type Function Description Example Instruction Output str(x) Converts object x to a string representation. str(75) str("25.25") ‘75’ '25.25' int(x) Converts object x to a integer number. int(35.26) int(100.101 ) 35 100 float(x) Converts object x to a float number. float(35) float(100) 35.0 100.0 list(s) Converts s to a list. list(range(5,10)) list(range(1,10,2)) [5, 6, 7, 8, 9] [1, 3, 5, 7, 9] tuple(s) Converts s to a tuple. tuple(range(5,10)) tuple(range(1,10,2)) (5, 6, 7, 8, 9) (1, 3, 5, 7, 9) dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples. chr(x) Converts an integer to a character. chr(65) chr(97) 'A‘ ‘a’ ord(x) Converts a single character to its ASCII (integer value) ord('A') ord(‘a') 65 97 hex(x) Converts an integer to a hexadecimal string. hex(16) hex(100) '0x10‘ '0x64' oct(x) Converts an integer to an octal string. oct(9) oct(50) '0o11‘ '0o62'
  • 30. Exercise Rewrite the following program in Python 3 with correct output display Without changing Variable Type Changing Variable Type num = input(“Enter a number = “) print( num,”x 3 = “,num * 3 ) num = input(“Enter a number = “) print( num,“x 3 = ",int(num) * 3 ) 3 x 3 = 333 3 x 3 = 9
  • 31. Python IDEs • Python IDLE • PyCharm • Sublime Text • Atom • Geany • Anjuta • Eric • Komodo IDE • KDevelop • Ninja-IDE • • Spyder
  • 32. Integer Operation Function Description bit_length(...) Number of bits necessary to represent self in binary Example: >>> (37).bit_length() 6 >>> int_num.bit_length() 2 bin(…) Return binary of the integer Example: >>> bin(37) '0b100101' >>> bin(25) '0b1111111' Denominator The denominator of a rational number in lowest terms Imag The imaginary part of a complex number numerator The numerator of a rational number in lowest terms real The real part of a complex number conjugate(...) Returns self, the complex conjugate of any int. to_bytes(...) Return an array of bytes representing an integer.
  • 33. Float Operation Function Description float.fromhex (...) Create a floating-point number from a hexadecimal string. Example: >>>float.fromhex('0x1.ffffp10') 2047.984375 float.hex(…) Return a hexadecimal representation of a floating-point number Example: >>>3.14159.hex() '0x1.921f9f01b866ep+1' is_integer(...) Return True if the float is an integer Example: >>> num = 5.5 >>> num.is_integer() False >>> num = num - 0.5 # remove floating value >>> num.is_integer() True as_integer_ratio(...) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Example: >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) conjugate(...) Return self, the complex conjugate of any float. imag The imaginary part of a complex number Real The real part of a complex number
  • 34. String Operation Function Description len(string) Return length of string capitalize(...) Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. title(...) Return a title cased version of S, i.e. words start with title case characters, and all remaining cased characters have lower case. lower(...) Return a copy of the string S converted to lowercase. upper(...) Return a copy of S converted to uppercase. casefold(...) Return a version of S suitable for caseless comparisons islower(...) Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. isupper(...) Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. isnumeric(...) Return True if there are only numeric characters in S, False otherwise. isdecimal(...) Return True if there are only decimal characters in S, False otherwise isdigit(...) Return True if all characters in S are digits and there is at least one character in S, False otherwise.
  • 35. a = input("Enter your name:") print("Lower Case of Enter string = " ,a.lower()) print("Upper Case of Enter string = " , a.upper()) print("Title Case of Enter string = " , a.title()) print("Length of Enter string = " , len(a)) print("Your Enter string is Alpha = " , a.isalpha()) print("Your Enter string is Decimal = " , a.isdecimal()) print("Your Enter string is Digit = " , a.isdigit()) print("Your Enter string is in Lower case = " , a.islower()) print("Your Enter string is in Upper case = " , a.isupper()) print("Your Enter string is in Title case = " , a.istitle()) Output 1: Enter your name:Hamdard university Lower Case of Enter string = hamdard university Upper Case of Enter string = HAMDARD UNIVERSITY Title Case of Enter string = Hamdard University Length of Enter string = 18 Your Enter string is Alpha = False Your Enter string is Decimal = False Your Enter string is Digit = False Your Enter string is in Lower case = False Your Enter string is in Upper case = False Your Enter string is in Title case = False Output 2: Enter your name:123456 Lower Case of Enter string = 123456 Upper Case of Enter string = 123456 Title Case of Enter string = 123456 Length of Enter string = 6 Your Enter string is Alpha = False Your Enter string is Decimal = True Your Enter string is Digit = True Your Enter string is in Lower case = False Your Enter string is in Upper case = False Your Enter string is in Title case = False String Operation Example
  • 36. Comparing Python with C/C++ Programming Parameter Python Language C/C++ Language Programming type Interpreter Compiler Programming Language High level Language Middle level Language Header file import #include Code block Whitespace Indentation Code within curly bracket { code} Single line statement termination Nothing Semicolon ; Control flow (Multi line) statement termination Colon : Nothing Single line comments # comments //comments Multi-line comments ‘’’ Comments lines ‘’’ /* Comments lines */ If error code found Partial run code until find error Did not run until error is present Program length Take fewer lines Take relatively more lines