SlideShare uma empresa Scribd logo
1 de 29
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 2
Fundamentals of Programming
Values and Types
A value is one of the basic things a program works with, like a
letter or a number
e.g 1, 2, and “Hello, World!”
2 is an integer, and “Hello, World!” is a string, so called because it
contains a “string” of letters
Type
If you are not sure what type a value has, the interpreter can tell
you
>>> type('Hello, World!')
>>> type(17)
>>> type(3.2)
Values and Types
What about values like ’17’ and ‘3.2’?
>>> type('17')
>>> type('3.2')
>>> print(1,000,000)
Python interprets 1,000,000 as a commaseparated sequence of
integers, which it prints with spaces between
Variables
A variable is a name that refers to a value
An assignment statement creates new variables and gives them
values:
>>> message = ‘Department of Computer Science'
>>> n = 17
>>> pi = 3.1415926535897931
Print()
To display the value of a variable, you can use a print statement:
n = 17
pi = 3.141592653589793
>>> print(n)
17
>>> print(pi)
3.141592653589793
The type of a variable is
the type of the value it
refers to.
>>>type(message)
>>>type(n)
>>> type(pi)
Variable Names and Keywords
Programmers generally choose names for their variables that are
meaningful and document what the variable is used for
Variables Names can contain both letters and numbers, but they cannot
start with a number
It is legal to use uppercase letters, but it is a good idea to begin variable
names with a lowercase letter
The underscore character ( _ ) can appear in a name
Variable names can start with an underscore character1
Variable Naming
>>>76trombones = 'big parade'
SyntaxError: invalid syntax
>>>more@ = 1000000
SyntaxError: invalid syntax
>>>class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax 1
Keywords
and del from None True as
elif
global nonlocal try assert else if
not
while break except import or with
class
False in pass yield continue finally
is
raise async def for lambda return
await
Statements
A statement is a unit of code that the Python interpreter can
execute
A script usually contains a sequence of statements
Operators and Operands
Operators are special symbols that represent computations like addition and multiplication
The values the operator is applied to are called operands.
The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and
exponentiation
20+32
hour-1
hour*60+minute
minute/60
5**2
(5+9)*(15-7)
/ Operator in Python 3 and Python 2
The division operator in Python 2.0 would divide two integers and
truncate the result to an integer
>>>minute = 5
>>>minute/2
2
/ Operator in Python 3 and Python 2
In Python 3.x, the result of this division is a floating point result:
>>>minute = 5
>>>minute/2
2.5
To get the floored division in python 3.x use //
>>>minute = 5
>>>minute/2
2
Expressions
An expression is a combination of values, variables, and
operators
A value all by itself is considered an expression, and so is a
variable, so the following are all legal expressions
17
x
x + 17
Expressions
In Interactive Mode:
the interpreter evaluates it and displays the result:
>>> 1 + 1
2
In Script:
But in a script, an expression all by itself doesn’t do
anything
Order of operations
the order of evaluation depends on the rules of precedence
For mathematical operators, Python follows mathematical convention
The acronym PEMDAS is a useful way to remember the rules
Parentheses (1+1)**(5-2)
Exponentiation 3*1**3
Multiplication and Division 6+4/2
Addition and Subtraction 5-3-1
Modulus Operator
The modulus operator works on integers and yields the
remainder
>>>quotient = 7 // 3
>>>print(quotient)
2
>>>remainder = 7 % 3
>>>print(remainder)
1
String Operations
+ operator performs concatenation, which means joining the strings by
linking them end to end
>>>first = 10
>>>second = 15
>>>print(first+second)
25
>>>first = '100‘
>>>second = '150'
>>>print(first + second)
100150
String Operations
The * operator also works with strings by multiplying the content
of a string by an integer
>>>first = 'Test '
>>>second = 3
>>>print(first * second)
Test Test Test
Asking the User for Input
Sometimes we would like to take the value for a variable from the user
via their keyboard
Python provides a built-in function called input that gets input from the
keyboard
When this function is called, the program stops and waits for the user
to type something
When the user presses Return or Enter, the program resumes and
input returns what the user typed as a string
Asking the User for Input
>>>inp = input(‘Enter Your Name: ’)
Enter Your Name: Adnan
>>>print(inp)
Adnan
Numbers Input
speed = input('Enter the speed in Miles: ')
miles_to_km = speed / 0.62137
print(miles_to_km)
Enter the speed in Miles: 1
Traceback (most recent call last):
File "C:/Users/Inzamam Baig/Desktop/speed.py", line 2, in
<module>
miles_to_km = speed / 0.62137
TypeError: unsupported operand type(s) for /: 'str' and
'float'
Comments
As programs get bigger and more complicated, they get more difficult to
read
it is a good idea to add notes to your programs to explain what your code in
doing
In Python they start with the # symbol
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
Everything from the # to the end of the line is ignored; it has no effect on the
program
Comments
v = 5 # assign 5 to v
v = 5 # velocity in meters/second
Choosing mnemonic variable names
follow the simple rules of variable naming, and avoid reserved
words
a = 35.0
b = 12.50
c = a * b
print(c)
hours = 35.0
rate = 12.50
pay = hours * rate
print(pay)
x1q3z9ahd = 35.0
x1q3z9afd = 12.50
x1q3p9afd = x1q3z9ahd * x1q3z9afd
print(x1q3p9afd)
Choosing mnemonic variable names
We call these wisely chosen variable names “mnemonic variable
names”.
The word mnemonic2 means “memory aid”.
We choose mnemonic variable names to help us remember why
we created the variable in the first place
Debugging
>>>bad name = 5
SyntaxError: invalid syntax
>>> month = 09
File "", line 1
month = 09 ^
SyntaxError: invalid token
Debugging
>>>principal = 327.68
>>>rate = 0.5
>>>interest = principle * rate
NameError: name 'principle' is not defined
>>>1.0 / 2.0 * pi
Variables names are case sensitive
Apple is not same as apple or APPLE

Mais conteúdo relacionado

Mais procurados (18)

Function
FunctionFunction
Function
 
Looping
LoopingLooping
Looping
 
Ch03
Ch03Ch03
Ch03
 
C programming part4
C programming part4C programming part4
C programming part4
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Ch09
Ch09Ch09
Ch09
 
[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++[ITP - Lecture 12] Functions in C/C++
[ITP - Lecture 12] Functions in C/C++
 
MATLAB programming tips 2 - Input and Output Commands
MATLAB programming tips 2 - Input and Output CommandsMATLAB programming tips 2 - Input and Output Commands
MATLAB programming tips 2 - Input and Output Commands
 
Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
C programming session6
C programming  session6C programming  session6
C programming session6
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
 
C programming session5
C programming  session5C programming  session5
C programming session5
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Ch05
Ch05Ch05
Ch05
 
Ch08
Ch08Ch08
Ch08
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
[ITP - Lecture 14] Recursion
[ITP - Lecture 14] Recursion[ITP - Lecture 14] Recursion
[ITP - Lecture 14] Recursion
 

Semelhante a Python Lecture 2

introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation fileRujanTimsina1
 
Python programing
Python programingPython programing
Python programinghamzagame
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdfMaheshGour5
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)ExcellenceAcadmy
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)ExcellenceAcadmy
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.pptjaba kumar
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schoolsDan Bowen
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 

Semelhante a Python Lecture 2 (20)

introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Python programing
Python programingPython programing
Python programing
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
1_Python Basics.pdf
1_Python Basics.pdf1_Python Basics.pdf
1_Python Basics.pdf
 
Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)Python Training in Chandigarh(Mohali)
Python Training in Chandigarh(Mohali)
 
Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)Python Training Course in Chandigarh(Mohali)
Python Training Course in Chandigarh(Mohali)
 
C++
C++C++
C++
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Chap 3 c++
Chap 3 c++Chap 3 c++
Chap 3 c++
 
C fundamental
C fundamentalC fundamental
C fundamental
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
Programming python quick intro for schools
Programming python quick intro for schoolsProgramming python quick intro for schools
Programming python quick intro for schools
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
 
3 algorithm-and-flowchart
3 algorithm-and-flowchart3 algorithm-and-flowchart
3 algorithm-and-flowchart
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 

Mais de Inzamam Baig

Mais de Inzamam Baig (13)

Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
 

Último

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
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.pptxheathfieldcps1
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
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.christianmathematics
 
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)Jisc
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
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 FellowsMebane Rash
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
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.MaryamAhmad92
 
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...Poonam Aher Patil
 

Último (20)

Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).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...
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
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.
 
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)
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
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
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
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.
 
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...
 

Python Lecture 2

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 2 Fundamentals of Programming
  • 2. Values and Types A value is one of the basic things a program works with, like a letter or a number e.g 1, 2, and “Hello, World!” 2 is an integer, and “Hello, World!” is a string, so called because it contains a “string” of letters
  • 3. Type If you are not sure what type a value has, the interpreter can tell you >>> type('Hello, World!') >>> type(17) >>> type(3.2)
  • 4. Values and Types What about values like ’17’ and ‘3.2’? >>> type('17') >>> type('3.2')
  • 5. >>> print(1,000,000) Python interprets 1,000,000 as a commaseparated sequence of integers, which it prints with spaces between
  • 6. Variables A variable is a name that refers to a value An assignment statement creates new variables and gives them values: >>> message = ‘Department of Computer Science' >>> n = 17 >>> pi = 3.1415926535897931
  • 7. Print() To display the value of a variable, you can use a print statement: n = 17 pi = 3.141592653589793 >>> print(n) 17 >>> print(pi) 3.141592653589793 The type of a variable is the type of the value it refers to. >>>type(message) >>>type(n) >>> type(pi)
  • 8. Variable Names and Keywords Programmers generally choose names for their variables that are meaningful and document what the variable is used for Variables Names can contain both letters and numbers, but they cannot start with a number It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter The underscore character ( _ ) can appear in a name Variable names can start with an underscore character1
  • 9. Variable Naming >>>76trombones = 'big parade' SyntaxError: invalid syntax >>>more@ = 1000000 SyntaxError: invalid syntax >>>class = 'Advanced Theoretical Zymurgy' SyntaxError: invalid syntax 1
  • 10. Keywords and del from None True as elif global nonlocal try assert else if not while break except import or with class False in pass yield continue finally is raise async def for lambda return await
  • 11. Statements A statement is a unit of code that the Python interpreter can execute A script usually contains a sequence of statements
  • 12. Operators and Operands Operators are special symbols that represent computations like addition and multiplication The values the operator is applied to are called operands. The operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and exponentiation 20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
  • 13. / Operator in Python 3 and Python 2 The division operator in Python 2.0 would divide two integers and truncate the result to an integer >>>minute = 5 >>>minute/2 2
  • 14. / Operator in Python 3 and Python 2 In Python 3.x, the result of this division is a floating point result: >>>minute = 5 >>>minute/2 2.5 To get the floored division in python 3.x use // >>>minute = 5 >>>minute/2 2
  • 15. Expressions An expression is a combination of values, variables, and operators A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions 17 x x + 17
  • 16. Expressions In Interactive Mode: the interpreter evaluates it and displays the result: >>> 1 + 1 2 In Script: But in a script, an expression all by itself doesn’t do anything
  • 17. Order of operations the order of evaluation depends on the rules of precedence For mathematical operators, Python follows mathematical convention The acronym PEMDAS is a useful way to remember the rules Parentheses (1+1)**(5-2) Exponentiation 3*1**3 Multiplication and Division 6+4/2 Addition and Subtraction 5-3-1
  • 18. Modulus Operator The modulus operator works on integers and yields the remainder >>>quotient = 7 // 3 >>>print(quotient) 2 >>>remainder = 7 % 3 >>>print(remainder) 1
  • 19. String Operations + operator performs concatenation, which means joining the strings by linking them end to end >>>first = 10 >>>second = 15 >>>print(first+second) 25 >>>first = '100‘ >>>second = '150' >>>print(first + second) 100150
  • 20. String Operations The * operator also works with strings by multiplying the content of a string by an integer >>>first = 'Test ' >>>second = 3 >>>print(first * second) Test Test Test
  • 21. Asking the User for Input Sometimes we would like to take the value for a variable from the user via their keyboard Python provides a built-in function called input that gets input from the keyboard When this function is called, the program stops and waits for the user to type something When the user presses Return or Enter, the program resumes and input returns what the user typed as a string
  • 22. Asking the User for Input >>>inp = input(‘Enter Your Name: ’) Enter Your Name: Adnan >>>print(inp) Adnan
  • 23. Numbers Input speed = input('Enter the speed in Miles: ') miles_to_km = speed / 0.62137 print(miles_to_km) Enter the speed in Miles: 1 Traceback (most recent call last): File "C:/Users/Inzamam Baig/Desktop/speed.py", line 2, in <module> miles_to_km = speed / 0.62137 TypeError: unsupported operand type(s) for /: 'str' and 'float'
  • 24. Comments As programs get bigger and more complicated, they get more difficult to read it is a good idea to add notes to your programs to explain what your code in doing In Python they start with the # symbol # compute the percentage of the hour that has elapsed percentage = (minute * 100) / 60 Everything from the # to the end of the line is ignored; it has no effect on the program
  • 25. Comments v = 5 # assign 5 to v v = 5 # velocity in meters/second
  • 26. Choosing mnemonic variable names follow the simple rules of variable naming, and avoid reserved words a = 35.0 b = 12.50 c = a * b print(c) hours = 35.0 rate = 12.50 pay = hours * rate print(pay) x1q3z9ahd = 35.0 x1q3z9afd = 12.50 x1q3p9afd = x1q3z9ahd * x1q3z9afd print(x1q3p9afd)
  • 27. Choosing mnemonic variable names We call these wisely chosen variable names “mnemonic variable names”. The word mnemonic2 means “memory aid”. We choose mnemonic variable names to help us remember why we created the variable in the first place
  • 28. Debugging >>>bad name = 5 SyntaxError: invalid syntax >>> month = 09 File "", line 1 month = 09 ^ SyntaxError: invalid token
  • 29. Debugging >>>principal = 327.68 >>>rate = 0.5 >>>interest = principle * rate NameError: name 'principle' is not defined >>>1.0 / 2.0 * pi Variables names are case sensitive Apple is not same as apple or APPLE

Notas do Editor

  1. Not surprisingly, strings belong to the type str and integers belong to the type int.
  2. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it doesn’t do the “right” thing.
  3. This example makes three assignments. The first assigns a string to a new variable named message; the second assigns the integer 17 to n; the third assigns the (approximate) value of π to pi.
  4. we generally avoid doing this unless we are writing library code for others to use
  5. 76trombones is illegal because it begins with a number. more@ is illegal because it contains an illegal character, @. But what’s wrong with class? It turns out that class is one of Python’s keywords
  6. The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names
  7. If you type an expression in interactive mode, the interpreter evaluates it and displays the result
  8. 8 3 8 1
  9. you can check whether one number is divisible by another: if x % y is zero, then x is divisible by y
  10. You can also put comments at the end of a line: percentage = (minute * 100) / 60 # percentage of an hour
  11. The Python interpreter sees all three of these programs as exactly the same but humans see and understand these programs quite differently