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

PDF
Python - Control Structures
PDF
Session 5-exersice
PDF
Introduction to Python
PPT
Python Control structures
DOCX
Compiler lab final report writing
PDF
Python Objects
PPTX
Python Training in Bangalore | Python Introduction Session | Learnbay
PDF
Conditional Statements
Python - Control Structures
Session 5-exersice
Introduction to Python
Python Control structures
Compiler lab final report writing
Python Objects
Python Training in Bangalore | Python Introduction Session | Learnbay
Conditional Statements

What's hot (18)

PDF
Function
PDF
PDF
C programming part4
PPSX
Complete C++ programming Language Course
PDF
[ITP - Lecture 12] Functions in C/C++
PPTX
MATLAB programming tips 2 - Input and Output Commands
PDF
Maxbox starter
PDF
Python for Machine Learning
PDF
C programming session6
PDF
Pseudocode By ZAK
PDF
C programming session5
PPTX
C Programming Unit-2
PDF
C programming session8
PDF
[ITP - Lecture 14] Recursion
Function
C programming part4
Complete C++ programming Language Course
[ITP - Lecture 12] Functions in C/C++
MATLAB programming tips 2 - Input and Output Commands
Maxbox starter
Python for Machine Learning
C programming session6
Pseudocode By ZAK
C programming session5
C Programming Unit-2
C programming session8
[ITP - Lecture 14] Recursion
Ad

Similar to Python Lecture 2 (20)

PDF
03-Variables, Expressions and Statements (1).pdf
PPTX
Pythonlearn-02-Expressions123AdvanceLevel.pptx
PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
PDF
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
PPTX
Lec2_cont.pptx galgotias University questions
PDF
Python unit 1 part-2
PPT
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
PPT
Input Statement.ppt
PPTX
Python_Modullllllle_2-_AFV._Funda-1.pptx
PDF
Advance Python Programming until operators.pdf
PDF
Variables in Python & Data Types and Their Values
PPTX
Introduction to Python Values, Variables Data Types Chapter 2
PDF
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
PPTX
unit1.pptx for python programming CSE department
PPTX
Intro to CS Lec03 (1).pptx
PPTX
parts_of_python_programming_language.pptx
PPTX
Module-1.pptx
PPTX
VARIABLES AND DATA TYPES IN PYTHON NEED TO STUDY
PPTX
Engineering CS 5th Sem Python Module-1.pptx
PDF
Python Programming - Basic Parts
03-Variables, Expressions and Statements (1).pdf
Pythonlearn-02-Expressions123AdvanceLevel.pptx
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
Lec2_cont.pptx galgotias University questions
Python unit 1 part-2
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
Input Statement.ppt
Python_Modullllllle_2-_AFV._Funda-1.pptx
Advance Python Programming until operators.pdf
Variables in Python & Data Types and Their Values
Introduction to Python Values, Variables Data Types Chapter 2
PPE-Module-1.2 PPE-Module-1.2 PPE-Module-1.2.pdf
unit1.pptx for python programming CSE department
Intro to CS Lec03 (1).pptx
parts_of_python_programming_language.pptx
Module-1.pptx
VARIABLES AND DATA TYPES IN PYTHON NEED TO STUDY
Engineering CS 5th Sem Python Module-1.pptx
Python Programming - Basic Parts
Ad

More from Inzamam Baig (13)

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

Recently uploaded (20)

PDF
faiz-khans about Radiotherapy Physics-02.pdf
PDF
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2015).pdf
PPTX
Thinking Routines and Learning Engagements.pptx
PDF
Journal of Dental Science - UDMY (2021).pdf
PDF
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
PPTX
What’s under the hood: Parsing standardized learning content for AI
PDF
Farming Based Livelihood Systems English Notes
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PDF
Compact First Student's Book Cambridge Official
PDF
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
PDF
Hospital Case Study .architecture design
PPTX
Integrated Management of Neonatal and Childhood Illnesses (IMNCI) – Unit IV |...
PDF
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
PPTX
Macbeth play - analysis .pptx english lit
PDF
Literature_Review_methods_ BRACU_MKT426 course material
PPTX
PLASMA AND ITS CONSTITUENTS 123.pptx
PPTX
Climate Change and Its Global Impact.pptx
PPTX
2025 High Blood Pressure Guideline Slide Set.pptx
PDF
Journal of Dental Science - UDMY (2020).pdf
PDF
Controlled Drug Delivery System-NDDS UNIT-1 B.Pharm 7th sem
faiz-khans about Radiotherapy Physics-02.pdf
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2015).pdf
Thinking Routines and Learning Engagements.pptx
Journal of Dental Science - UDMY (2021).pdf
Myanmar Dental Journal, The Journal of the Myanmar Dental Association (2013).pdf
What’s under the hood: Parsing standardized learning content for AI
Farming Based Livelihood Systems English Notes
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
Compact First Student's Book Cambridge Official
fundamentals-of-heat-and-mass-transfer-6th-edition_incropera.pdf
Hospital Case Study .architecture design
Integrated Management of Neonatal and Childhood Illnesses (IMNCI) – Unit IV |...
Skin Care and Cosmetic Ingredients Dictionary ( PDFDrive ).pdf
Macbeth play - analysis .pptx english lit
Literature_Review_methods_ BRACU_MKT426 course material
PLASMA AND ITS CONSTITUENTS 123.pptx
Climate Change and Its Global Impact.pptx
2025 High Blood Pressure Guideline Slide Set.pptx
Journal of Dental Science - UDMY (2020).pdf
Controlled Drug Delivery System-NDDS UNIT-1 B.Pharm 7th sem

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

  • #4: Not surprisingly, strings belong to the type str and integers belong to the type int.
  • #6: 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.
  • #7: 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.
  • #9: we generally avoid doing this unless we are writing library code for others to use
  • #10: 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
  • #11: The interpreter uses keywords to recognize the structure of the program, and they cannot be used as variable names
  • #16: If you type an expression in interactive mode, the interpreter evaluates it and displays the result
  • #18: 8 3 8 1
  • #19: you can check whether one number is divisible by another: if x % y is zero, then x is divisible by y
  • #25: You can also put comments at the end of a line: percentage = (minute * 100) / 60 # percentage of an hour
  • #27: The Python interpreter sees all three of these programs as exactly the same but humans see and understand these programs quite differently