0% found this document useful (0 votes)
1 views269 pages

Programming Language I

Uploaded by

Saitou Akane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views269 pages

Programming Language I

Uploaded by

Saitou Akane
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming Language 1

Python
Dr. Suheer Al-Hadhrami
2

Programming Language 1 Python

The slides are prepared based on Shivam Mitra slides in slideshare website.
VARIABLES AND DATA
TYPES IN PYTHON
4

Variables

 Reserved memory locations to store values.


 It means that when you create a variable, you reserve some space in the memory.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)

30-09-2024 Programming language I


5

Variables
 Variables are used to store data
 These data are stored in main memory when you run the program
 Different data types in python
 Numbers
 Strings
 Lists
 Tuple
 Dictionary

30-09-2024 Programming language I


6

Multiple Assignment

 Python allows you to assign a single value to several variables simultaneously.


a=b=c=1
 You can also assign multiple objects to multiple variables
a, b, c = 1, 2, "john”

30-09-2024 Programming language I


RULES FOR NAMING
VARIABLES
RULE 1 - Variable names can contain only letters, numbers, and
underscores. They can start with a letter or an underscore, but
not with a number.
SUPPOSE YOU WANT TO WRITE TWO DIFFERENT MESSAGES ?
RULE 2 - Spaces are not allowed in variable names, but
underscores can be used to separate words in variable names.
RULE 3 - Avoid using Python keywords and function names as
variable names; that is, do not use words that Python has reserved
for a particular programmatic purpose, such as the word print.
WHAT ARE KEYWORDS IN
PYTHON?
 These are reserved words in python which are
used to define the syntax of python language.
 In English, “is”, “the”, “you” etc. are reserved
words which defines the grammar.
 Keywords have different meaning for Python
language.
 Do not use them in your variables or function
names.
14

Keywords
Keywords are the reserved words that are already defined by the Python for specific uses

False await else import pass


None break except in raise
True class finally is return
and continue for as assert
async def del elif from
global if lambda try not
or while with yield nonlocal

30-09-2024 Programming language I


BUILT-IN FUNCTIONS IN PYTHON
SOME OTHER IMPORTANT
POINTS TO NOTE
 Variable names should be short but descriptive.
 name is better than writing n
 message is better than writing m or
my_name_message
 Be careful when using the lowercase letter l and
the uppercase letter O because they could be
confused with the numbers 1 and 0.
It can take some practice to learn how to create good variable
names, especially as your programs become more interesting
and complicated. As you write more programs and start to read
through other people’s code, you’ll get better at coming up with
meaningful names.
AVOIDING NAME ERRORS WHEN
USING VARIABLES
20

Operators

Python language supports the following types of operators-


 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

30-09-2024 Programming language I


21

Arithmetic Operators
 Assume a=10 ,b =21, then … print(C)
Operator Description Example
+ Addition Adds values on either side of the operator. C=a + b
C = 31
- Subtraction Subtracts right hand operand from left hand C=a – b
operand. C = 31 = -11
* Multiplication Multiplies values on either side of the operator C=a * b
C = 31 = 210
/ Division Divides hand operand by right hand operand C= b / a
C = 31 =2.1
% Modulus Divides left hand operand by right hand operand and C=b % a
returns remainder C = 31 = 1
** Exponent Performs exponential (power) calculation on C=a**4
operators C =10000
// Floor Division - The division of operands where the result is the C=b//2
quotient in which the digits after the decimal point C=10
30-09-2024
are removed. Programming language I
22
Comparison Operators/ Relational operators
 These operators compare the values on either side of them and decide the relation among them.
 Assume a =10 , b=20, then
Operator< Description Example
== If the values of two operands are equal, then the condition become true if(a==b):
Print(‘is not true’)
!= If values of two operands are not equal, then condition become true if(a!=b) :
Print(‘is true’)
> If the value of the left operand is greater than the value of the right operand, if(a>b) :
then condition become true Print(‘ is not true’)
< If the value of the left operand is less than the value of the right operand, then if(a<b) :
condition become true Print(‘is true’)

>= If the value of the left operand is greater than or equal to the value of the right if(a>=b) :
operand, then condition become true Print(‘is not true’)

<= If the value of the left operand is less than or equal to the value of the right if(a<=b) :
operand, then condition become true Print(‘is true’)
30-09-2024 Programming language I
23

Logical operators
Precedence of logical operator
 not –unary operator
 and Decreasing order
 or
Example
>>> (10<5) and ((5/0)<10)
False
>>> (10>5) and ((5/0)<10)
ZeroDivisionError

30-09-2024 Programming language I


24

Bitwise operators
 Bitwise AND – x & y
 Bitwise OR – x|y
 Bitwise Complement - ~ x
 Bitwise Exclusive OR -x˄y
 Left Shift – x<<y
 Right Shift –x>>y

30-09-2024 Programming language I


25

Precedence and Associativity of operators


Operator
()
**
+x, -x, ~x
/, //, *, %
+, - Decreasing
<<, >> order
&
˄
|
==,<, >, <=, >= ,
!=
not
and
or
30-09-2024 Programming language I
26

Data Types

Python has five standard data types-


 Numbers
 String
 List
 Tuple
 Dictionary

30-09-2024 Programming language I


FINDING THE DATA TYPE OF A
VARIABLE

• Use type() built-in function


STRINGS DATA TYPE
WHAT ARE STRINGS ?
 A string is a series of characters
 Characters – alphabets, digits, special characters, white spaces
 Anything inside quotes is considered a string in Python
 You can use single or double quotes around your strings
SINGLE QUOTE VS DOUBLE QUOTE ?
 You can use any of these
 Be consistent
 Exceptions – print these text on screen:
 The language 'Python' is named after Monty Python, not the snake.
 I told my friend, "Python is my favorite language!"
ASSIGNMENT: Try to find out if it is possible to print first message by using single quotes and second by using double quotes
and how ?
BUILT-IN FUNCTIONS
ASSOCIATED WITH
STRINGS
UPPER/LOWER FUNCTION
 print() vs [Link]()
 These built-in functions are specific to strings.
 print() is specific to multiple data types
 The dot(.) operator acts on the variable and converts it into
upper/lower cases
 The original data doesn’t change
TITLE FUNCTION
 Converts the first character of each word into upper case
LEN FUNCTION
 Outputs the length of the string
 A single character is of length 1
 Characters can be alphabets or digits or punctuation or white
spaces
STRIP FUNCTIONS – strip(), lstrip(),
rstrip()
 Remove the extra whitespaces from a string
rstrip() – remove whitespace at right end
lstrip() – remove whitespace from left end
strip() – remove spaces from both ends
USING VARIABLES
INSIDE A STRING
COMBINE THESE TWO TO PRODUCE
FULL NAME
Use f-strings
 Feature is available from python 3.6
 Start string with f – f stands for format
 Put braces around variable name
CONCAT MULTIPLE STRINGS
Adding Whitespace to Strings
with Tabs or Newlines
 In programming, whitespace refers to any nonprinting
character, such as spaces, tabs, and end-of-line symbols.
 You can use whitespace to organize your output so it’s easier
for users to read.
Add a tab to your text
Add newline to your text
NUMBERS DATA TYPE
What are numbers ?
 Integers = 1, 2, 3
 Floats = 1.2, 2.55
 These data are used very frequently in a program.
INTEGERS

 You can add, subtract, multiply and divide


python integers
 Python uses two
multiplication symbols to
represent exponents.
MULTIPLE OPERATORS IN ONE
EXPRESSION
 The spacing in these examples has no effect on how Python evaluates the expressions
 Clarity
 More about precedence of operators in a future video
FLOATS
 Python calls any number with a decimal point a float.
 This term is used in most programming languages, and it refers to the fact that a
decimal point can appear at any position in a number.
 Example: 1.2, 12.35
This happens in all languages and is of little concern. Python tries to find a
way to represent the result as precisely as possible, which is sometimes
difficult given how computers have to represent numbers internally.
USE ROUND FUNCTION
INTEGERS AND FLOATS
DATA TYPE CONVERSION
MULTIPLE ASSIGNMENTS
 You can assign values to more than one variable using just a single line.
 This can help shorten your programs and make them easier to read.
 You’ll use this technique most often when initializing a set of numbers.
CONSTANTS IN PYTHON
 A constant is like a variable whose value stays the
same throughout the life of a program.
 Python doesn’t have built-in constant types, but
Python programmers use all capital letters to
indicate a variable should be treated as a constant
and never be changed.
LISTS IN PYTHON
STORING MULTIPLE NAMES ?
 5 names, 10 names …. 100 names
 Storing it in strings doesn’t scale well
 Storing multiple numbers
 Code clarity
 Slow access
INTRODUCING LISTS
 A list is a collection of items in a particular order
 List of
 Names
 Places
 list of digits
 list of colors
 Good to name your list names as plurals – names, places etc
LISTS IN PYTHON
 Use square brackets ([]) to represent a list
 Individuals elements are separated by a comma
 Printing a list
ACCESSING ELEMENTS IN A LIST
 Lists are ordered
 Access an element by its position or index
 In Python and most languages, list numbering starts from 0th position
 This is very important
USE STRING METHODS ON THESE
ELEMENTS
REMEMBER THIS IMPORTANT THING
 Each index in a list contains a data type – integers, float, strings etc
 Instead to using multiple variable names, you are using a single variable name to
store all these
 All functions/operations on a data type applies here to elements
CAN WE STORE DIFFERENT DATA
TYPES IN A LIST ?

But mostly we will store same type of data


LENGTH OF THE LIST USING LEN()
FUNCTION
ACCESSING LAST ELEMENTS IN A LIST
NEGATIVE INDEXING IN PYTHON

THIS WILL BE FASTER THAN THE LAST METHOD


STRINGS VS LISTS IN PYTHON
MODIFYING AN ELEMENT - LIST VS
STRING
MUTABLE VS IMMUTABLE DATA TYPES
 Immutable data type
 The value/data cannot be changed
 Example: strings, integers, floats etc
 Mutable data type
 The value/data can be changed
 Example – lists
 More about this in a separate video
INSERTING ELEMENTS AT THE END
OF A LIST
• This is very common
• As data is mostly known after the program starts running
INSERTING ELEMENTS AT ANY
POSITION
REMOVING ELEMENTS
FROM A LIST
REMOVING USING DEL STATEMENTS
REMOVING USING POP METHOD
 The pop() method removes the last item in a list, but it lets you work with that item
after removing it
POPPING ITEMS FROM ANY POSITION
IN THE LIST
WHEN TO USE DEL VS POP ?
REMOVING AN ELEMENT BY VALUE
REMOVING AN ELEMENT NOT IN A
LIST
CAN DUPLICATES BE REMOVED ?

• Removes first matching value


• USING REMOVE AGAIN WILL DO
ORGANIZING A LIST
SORTING A LIST
 Putting the elements in a particular order
 Increasing order
 Decreasing order
 Numbers = [2, 1, 3]
 Increasing = [1, 2, 3]
 Decreasing = [3, 2, 1]
SORTING A LIST OF STRINGS
 Alphabetical order
 Names = [‘Shivam’, ’Anil’, ‘Navneet’]
 Increasing alphabetical order = [‘Anil’, ‘Navneet’, ‘Shivam’]
 Decreasing alphabetical order = [‘Shivam’, ‘Navneet’, ‘Anil’]
SORTING A LIST PERMANENTLY WITH
SORT FUNCTION

BY DEFAULT, SORT() SHORTES IN INCREASING ORDER


SORTING IN REVERSE ALPHABETIC
ORDER
SORTING A LIST TEMPORARILY WITH
SORTED FUNCTION
 To maintain the original order of a list but present it in a sorted order, you can use
the sorted() function.
 The sorted() function lets you display your list in a particular order but doesn’t affect
the actual order of the list.
PRINTING A LIST IN REVERSE ORDER

What if you reverse again ?


AVOIDING INDEX ERRORS WHEN
WORKING WITH LIST

REMEMBER THAT INDEXING STARTS AT 0


FOR LOOP IN PYTHON
AND USING LISTS
AGENDA
 FOR LOOP IN PYTHON
 INDENTATION IN PYTHON
 LIST COMPREHENSIONS
 SLICING A LIST
 COPYING A LIST
PRINT EACH NAME IN THE LIST
ISSUES WITH THIS APPROACH
 Repetitive code
 Need to change the code if the list size changes
FOR LOOP FOR PRINTING THE LIST
EXPLAINING HOW
FOR LOOP WORKED
AVOIDING
INDENTATION ERRORS
WHAT IS INDENTATION
 Indentation is used to make code more readability easier
 In languages like c, c++, python etc. , indentation is optional
 In Python, it is mandatory
 Python uses indentation to determine how a line, or group of lines, is related to the
rest of the program.
 Change indentation and the meaning of code changes
INDENTATION ERROR
LOGICAL ERROR
INDENTING UNNECESSARILY
FORGETTING THE COLON ( so tough to
find )
TABS VS SPACES FOR INDENTATION
WHAT’S THE ACTUAL
ISSUE ?
USING SPACES VS TABS
 Spaces - consistent on every text editor
 Tabs – not consistent on every text editor
 Can be 4 spaces
 Can be 8 spaces
 Mixing tabs and spaces causes error
 I prefer using 4 spaces for indentation
 Do not type spaces 4 times
RANGE FUNCTION

• Start to (end-1)
• Print 1 to 6
• Similar to other
programming languages
USING RANGE TO STORE A LIST OF
NUMBERS
SKIPPING NUMBERS WITHIN A RANGE
PRINT MULTIPLICATION TABLE OF 5

Output – [5, 10, 15, ……….., 50]


SIMPLE STATISTICS WITH A LIST OF
NUMBERS
 Maximum of a list
 Minimum of a list
 Sum of a list
LIST COMPREHENSIONS
 A list comprehension combines the for loop and the creation of new elements into
one line, and automatically appends each new element.
 Multiplication table in one line
 Not for beginner but you will see this in others code
WORKING WITH A PART OF A LIST
 Can we access multiple list elements at one go ?
 Welcome to slice in python
 Slice of pizza ?
 Not present in all programming languages
SLICING A LIST
 To make a slice, you specify the index of the first and last elements you want to work
with.
 Like range, the last element is not considered

• List can also be of strings or


any data type
LOOPING THROUGH A SLICE
COPYING A LIST
ASSIGNMENT
 Print square of numbers from 1 to 10 using for loop
 Store it a list first and then print
 One liner code
 fruits = [‘banana’, ‘apple’, ‘watermelon’, ‘orange’]
 Print first 2 fruits ( using slicing )
 Print last 2 fruits (suing slicing )
 Print fruits at odd positions ( using for loop )
 Print fruits at even positions (using for loop )
 Paste your code in the comment
IF ELSE STATEMENT IN
PYTHON
AGENDA
 SIMPLE IF ELSE STATEMENT
 CONDITIONAL TESTS
 AND, OR OPERATOR
 ADVANCED IF ELSE STATEMENTS
EXAMPLE
 Example 1
 number = 2
 If number is odd, print “odd number”
 If number is even, print “even number”
 Example 2
 name = ‘Shivam’
 If name is ‘Shivam’, print it in capital letters
 Otherwise, print as it is
CONDITIONAL TESTS
 Conditional test
 If test is true, execute the code under if statement
 If test is false, ignore the code under if statement and move forward
CHECK FOR EQUALITY
 Equality operator returns True if value on left and right side matches. Otherwise,
False.
 Assignment operator(=) vs Equality operator(==)
 Assignment -> Storing a value in a variable
 Equality operator -> Are the values equal on both the sides ?
IGNORING THE CASE WHEN
CHECKING FOR EQUALITY
 Gmail – freecodeschool vs FreeCodeSchool (@[Link])
CHECKING FOR INEQUALITY

• If two values doesn’t match, True


• If two value matches, False
NUMERICAL COMPARISONS
CHECKING MULTIPLE CONDITIONS
 you might need two conditions to be True to take an action
 you might be satisfied with just one condition being True
 Keywords – and, or
USING AND TO CHECK MULTIPLE
CONDITIONS
 Multiple tests
 If all test passes, return True
 If even one of the test fails, return False
 Checking happens in order
 If one test returns False, further checking doesn’t happen
• More than 2 tests are also possible
using parentheses
USING OR TO CHECK MULTIPLE
CONDITIONS
 Multiple tests
 If any one of the test passes, return True
 Go in order and stop when any test passes
 If all the test fails, return False
CHECKING WHETHER A VALUS IS IN
THE LIST
CHECKING WHETHER A VALUE IS NOT
IN THE LIST
BOOLEAN EXPRESSIONS
 Another name for conditional statements
 A Boolean value is either True or False
IF STATEMENTS
SIMPLE IF STATEMENTS
IF-ELSE STATEMENTS
IF-ELIF-ELSE CHAIN
GRADING
 marks >= 90 and marks <= 100 – A
 marks >= 70 and marks < 90 – B
 marks >= 50 and marks < 70 – C
 marks >= 40 and marks < 50 – D
 Otherwise, F
OMITTING THE ELSE BLOCK
TESTING MULTIPLE CONDITIONS
USING IF STATEMENTS WITH LISTS
 ODD EVEN EXAMPLE
 SEARCH A NAME EXAMPLE
CHECKING IF A LIST IS EMPTY
ASSIGNMENT
a=2
b=3
If a is greater than b, print “a > b”
If a is smaller than b, print “a < b”
If a is equal to b , print “a = b”

Note: a and b can take any values


TUPLES IN PYTHON
LISTS IN PYTHON
 ITEMS IN A LIST CAN BE MODIFIED
 LISTS ARE MUTABLE
 WHAT IF WE WANT A DATA STRUCTURE SIMILAR TO LISTS BUT THAT
CANNOT BE MODIFIED ?
WLECOME TO TUPLES
 A tuple just looks like a list
 You have parentheses instead of square brackets
 But items in a list cannot be modified
WHAT IF WE CHANGE AN ELEMENT ?
IS THIS A TUPLE ?
A TUPLE WITH A SINGLE ELEMENT
LOOPING THROUGH ALL VALUES IN A
TUPLE
WRITING OVER A TUPLE
INSERTING IN A TUPLE
HOW I AM ABLE TO MODIFY A TUPLE ?
OPERATIONS SIMILAR TO LISTS
 Negative indexing
 Slicing
 min, max, sum functions
 len()
 Insertion/deletion commands of lists will not work here
DICTIONARIES IN
PYTHON
DICTIONARY IN PYTHON
 A collection of key-value pairs
 Each key is mapped to a value.
 Use key to access the value mapped to it
 Keys -> Numbers, Strings
 Values -> Any data type like number, strings, lists, dictionaries etc.
DEFINING A DICTINOARY IN PYTHON

• A dictionary is wrapped in braces


• Series of key-value pairs inside the braces
• Every key is connected to its value with colon
• Key-value pairs are separated by comma
• You can store as many key-value pairs you want
ACCESSING ELEMENT IN A
DICTIONARY

Similar to list but access using key here than index


A DICTIONARY WITH MULTIPLE KEYS
ADDING NEW KEY-VALUE PAIRS
STARTING WITH AN EMPTY
DICTIONARY
MODIFYING VALUES IN A DICTIONARY
DICTIONARIES ARE MUTABLE
 One can add, delete and modify key-value pairs in a dictionary
 Key or values can be mutable or immutable depending on their type
 Strings -> immutable
 Numbers, lists -> mutable
REMOVING KEY-VALUE PAIRS
STORING COUNTRY-CAPITAL
MAPPING
USING get() TO ACCESS VALUES

TRY RUNNING THIS CODE


WRITE A PROGRAM TO COUNT THE FREQUENCY OF EACH CHARACTER IN
A GIVEN STRING.

INPUT – ‘mississippi’
Output: Count of each character in this word. ‘m’ -> 1
LOOPING THROUGH A DICTIONARY
 A dictionary can contain millions of entries
 Looping over all
 Key-value pairs
 Keys
 Values
LOOPING THROUGH ALL KEY-VALUE
PAIRS

key, value -> k,v


HOW DOES LOOPING WORKS ?
TRY LOOPING THROUGH
COUNTRY-CAPITAL
EXAMPLE
LOOPING THROUGH DICTIONARY
KEYS
LOOPING THROUGH KEYS IN AN
ORDER

Print keys in reverse order


LOOPING THROUGH ALL VALUES IN A
DICTIONARY

Print the values in order


NESTING
 Storing multiple dictionary in a list
 List of items as a value in a dictionary
 A dictionary inside another dictionary
 This is called nesting.
A LIST OF DICTIONARIES
A MORE REALISTIC EXAMPLE
 Store the (number->square of number) mapping for numbers 1 to 5
A LIST IN A DICTIONARY
A DICTIONARY IN A
DICTIONARY
USER INPUTS IN
PYTHON
 Most programs are written to solve end user’s problem
 We need to get input from the users
 Check whether a person can vote or not ?
 Check whether a number is even or odd ?
INPUT FUNCTION IN PYTHON

Input function takes only one argument


The function waits for user input and continues once user presses enter
Write meaningful messages
HOW TO ACCEPT NUMERICAL INPUTS
?
HOW TO ACCEPT A LIST ?
USE LIST
COMPHEHENSION ?
PROGRAMS TO PRACTICE
 Check if a number is odd or even
 Check if one can vote or not
 Find the sum of all the numbers

Assignment:
 Print the table of a number ( take input from user )
 Check if a number is multiple of 10 or not ( take input from the user )
WHILE LOOP IN
PYTHON
WHILE LOOP IN PYTHON

Counting number from 1 to 5


LETTING THE USER CHOOSE WHEN
TO QUIT
USING A FLAG
CHECK IF ALL NUMBERS ARE EVEN OR
NOT
USING BREAK TO EXIT A LOOP
 When we use break statement, the loop will terminate immediately.
 Applicable with for/while loop
USING CONTINUE IN A LOOP
 Return to the beginning of the loop
 Print only the odd numbers
AVOIDING INFINITE WHILE LOOPS
 We can accidentally write while loops that runs infinitely
USING WHILE WITH LISTS
 Do not use for loop when your modifying the list inside it
 Python will find tough to track the elements
 Use while loop
GET A LIST OF NUMBERS FROM USERS
REMOVING ALL INSTANCES OF A
VALUE FROM THE LIST
FILLING A DICTIONARY WITH USER
INPUT
FUNCTIONS IN
PYTHON
DEFINING AND CALLING A FUNCTION
IN PYTHON
WHY TO USE FUNCTIONS ?
 Reusability – finding greater of two numbers
 Avoiding repetitive code
 Users do not need to know how function is working
USER DEFINED VS BUILT-IN
FUNCTIONS
 print(), len(), sort() – built-in
PASSING INFORMATION TO A
FUNCTION

Multiple calls
FUNCTION PARAMETERS AND
ARGUMENTS
 Parameters -> Function definition inputs
 Arguments -> Function call inputs
 Used interchangeably
PASSING ARGUMENTS TO FUNCTIONS
 A function can have multiple parameters
 A function call may need multiple arguments
 Positional arguments
 Keyword arguments
POSITIONAL ARGUMENTS

• Interchange the arguments


• Increase/Decrease the number of arguments
KEYWORD ARGUMENTS

• Interchange
• Wrong keyword
DEFAULT VALUES

 One can define default values for


each function parameter
 If an argument for a parameter is
not passed, default value is used
DIFFERENT WAYS OF CALLING A
FUNCTION
RETURN VALUES
 A function doesn’t always have to display the output
 It can also return value back to the function call
 return statement is used
Return a dictionary
Return a list
USING A FUNCTION
WITH WHILE LOOP
PASSING A LIST TO A FUNCTION
MODIFYING A LIST IN A FUNCTION
Thank You

You might also like