SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot (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
 

Similar to Python Lecture 2

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
 
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_18012013Kurmendra Singh
 

Similar to Python Lecture 2 (20)

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
 
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
 

More from Inzamam Baig

More from 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
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

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

Editor's Notes

  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