Python Programming
Brian D. De Vivar, MIT
Special Lecturer
COMP 002 – Computer Programming 1
What are
these ?
1) Google Assistant
2) Ms. Sofia ( The Robot )
3)Cortana
What is essential for these
technologies ?
PROGRAMMING
What are
Programming and
Languages ?
⮚A programming language is a
formal language comprising a set of
instructions that produce various
kinds of output.
⮚Programming languages are used
in computer programming to
implement algorithms.
Here we're going to see about Python
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.
It is used for:
Web development (server-side)
Software development
System scripting
Machine Learning, Data Science
This Ph oto by Unknown author is licensed und er CC BY-SA.
1. Installation
Install the Python IDLE using this link - [Link]
Version - python 3
2. Syntax
[Link] is an interpreted language, we can run our code
snippets in python shell.
[Link] Extension - .py
>>> print("Hello, World!")
Hello, World!
3. Python Indentation
1. Indentation refers to the spaces at the beginning of a code line.
1. Python uses indentation to indicate a block of code.
if 10> 5:
print("Ten is greater than five!")
Thank you for watching !
Next session,
1. Variables
2. Data types
3. Casting and Numbers.
Python Programming
4. Comments
[Link] can be used to prevent execution when testing code.
[Link] can be used to make the code more readable.
Single Line Comment - #
print("Hello, World!") #This is a comment
Multiline Comment - ‘’’
Hello World !!!
‘’’
5. Data
Data is defined as facts or figures, or information that's stored in or used by a computer.
Ex:
Name: Ashwin R
Course: Information Technology
6. Data Types
Data Type is the type of data
Primary Data Types - Number, String, Boolean, Float, Complex
Secondary Data Types - Set, List, Dictionary, Tuple.
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
7. Variables
Variables are containers for storing data values.
Creating Variables
1. Python has no command for declaring a variable.
2. A variable is created the moment you first assign a value to it.
X=5
Y = "python"
print(X)
print(Y)
7.1 Variable Names
1.A variable name must start with a letter or the underscore character
2;.A variable name cannot start with a number
3.A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
[Link] names are case-sensitive (age, Age and AGE are three different variables)
7.2 Legal Names
myvar = "Ashwin"
my_var = "Ashwin"
_my_var = "Ashwin"
myVar = "Ashwin"
MYVAR = "Ashwin"
myvar2 = "Ashwin"
7.3 Illegal Names
2myvar = “Ashwin”
my-var = ”Ashwin”
my var = “Ashwin”
7.4 Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
7.5 One Value to Multiple Variables
You can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
7.6 Type of variable
Using Type() build in function, we can get the data type of the variable
>>>a= 5
>>>Type(a)
integer
>>> b=”Ashwin234”
>>>Type(b)
string
Thank you for watching !
Next session,
1. Input and Outputs
2. Casting
3. Keywords
Python Programming
8. Input
Input is the basic command or signal to the machine to perform several tasks.
Getting User Input in python
input() is the build in method to get input from user
Syntax : input(“Enter the Name:”)
int(input(“Enter the Age:”))
1. Default input data type is String.
2. To get the desired type of input, we need to do casting.
9. Casting or Type Casting
If you want to specify the data type of variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
10. Output
Outputs are the amount of something that produced due to some operations.
The Python print statement is often used to output variables.
a=input(“Enter your Name:”) # User Input ---> Ashwin
print(a) # Prints---> Ashwin
11. Keywords and Build in functions
Keywords are reserved words that having some specific meaning
Ex - print, int, bool, str, float, return, global, import, from etc.
Build in functions - These are also predefined functions, which is highly helpful to reduce the
complex tasks.
Ex - sum(), abs(), type(), def(), etc.
(Will see it elaborately in upcoming classes)
Data Types
12. Numbers
There are three numeric types in Python
1. int
[Link]
[Link]
Ex :
x=1 # int
y = 2.8 # float
z = 1j # complex
13. Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Ex : 'hello' is the same as "hello".
13.1 Multiline String
a = """This is
Python programming Tutorial
"""
print(a)
13.2 Strings are Arrays
Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
However, Python does not have a character data type, a single character is simply a string with a
length of 1.
Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
13.3 Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
for x in "Ashwin":
print(x)
13.3.1 String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
13.4 Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
txt = "The best things in life are free!"
if “free in text:
print(“Yes free word is present !”)
13.5 Slicing
You can return a range of characters by using the slice syntax.
[Link] the start index and the end index, separated by a colon, to return a part of the string.
b = "Hello, World!"
print(b[2:5])
2. Slicing from Start 3. Slice To the End
b=”Python” c=”Python”
print(b[:4]) print(b[2:])
13.5.1 Negative Indexing
Use negative indexes to start the slice from the end of the string:
b = “World!"
print(b[-3:-1])
Thank you for watching !
Next session,
1. String Methods (Part 2)
2. Boolean Type
3. Operators
Python Programming
13.6. Modify Strings
1. Upper Case
a = "Hello, World!"
print([Link]())
1. Lower Case
a = "Hello, World!"
print([Link]())
13.6.1 Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to remove this
space.
a = " Hello, World! "
print([Link]())
13.6.2 Replace String
a = "Hello, World!"
print([Link]("H", "J"))
13.6.3 Split String
The split() method returns a list where the text between the specified separator becomes the list
items.
a = "Hello, World!"
print([Link](","))
13.7 String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)
13.7.1 String Format
The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are
age = 36
txt = "My name is John, and I am {}"
print([Link](age))
14. Boolean
Booleans represent one of two values: True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
14.1 Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in return
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
15. Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values
a = 1+2 # + is an arithmetic operator
print(a)
if (2==2) # == is a relational operator
if 2>1 # > is a comparison operator etc .
Thank you for watching !
Next session,
1. Operators part 2
2. Sequential Data Types
3. List (Part 1)
Python Programming
15.1 Operators
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
15.2 Arithmetic Operator
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
15.3 Assignment Operator
= x=5
+= x += 3
-= x -= 3
*= x *= 3
/= x /= 3
%= x %= 3
//= x //= 3
**= x **= 3
&= x &= 3
15.4 Comparison Operator
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
15.5 Logical Operators
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not(x < 5 and x <
10)
15.6 Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location
is Returns True if both variables are the same object x is y
is not Returns True if both variables are not the same object x is not y
16.7 Membership Operator
Membership operators are used to test if a sequence is presented in an object
in Returns True if a sequence with the specified value is present in the object
Ex . x in y
not in Returns True if a sequence with the specified value is not present in the object
Ex. x not in y
15.8 Bitwise Operator
Bitwise operators are used to compare (binary) numbers
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift. Shift left by pushing zeros in from the right and let the leftmost
bits fall off
>> Signed right shift. Shift right by pushing copies of the leftmost bit in from the left,
and let the rightmost bits fall off
Sequence Data Types
16. Lists
Languages= ["Python", ”C” , ”Java”]
[Link] are used to store multiple items in a single variable.
[Link] are one of 4 built-in data types in Python used to store collections of data
16.1 List items
[Link] items are ordered, changeable, and allow duplicate values.
[Link] items are indexed, the first item has index [0], the second item has index [1]
etc
16.2 List length
Languages= [“Python”,”C”,”C++”,”Java”]
print(len(Languages))
16.3 List Items - Data Types
details=[“Ashwin”,21,”Chennai”,8.3,True]
16.3 List() Constructor
It is also possible to use the list() constructor when creating a new list.
details = list((“Ashwin”,21,”Chennai”))
16.4 List Accessing
List items are indexed and you can access them by referring to the index number
Details=[“Ashwin”,21,”Chennai”]
print(Details[0])
16.4.1 Negative Indexing
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Thank you for watching !
Next session,
1. List Methods (part 2)
2. Tuples
3. Tuples Methods (Part 1)
Python Programming
16.5 Change List Items
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
16.6 List
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
17 Tuples
Tuples are used to store multiple items in a single variable.
mytuple = ("apple", "banana", "cherry")
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List,
Set, and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets
18. Sets
myset = {"apple", "banana", "cherry"}
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Tuple, and Dictionary, all with different qualities and usage.
A set is a collection which is both unordered and unindexed.
Sets are written with curly brackets.
19. Dictionaries
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.
Control Structures
19. Conditional Statements: If..elif..else
An "if statement" is written by using the if keyword.
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
19.2 Short hand If..Else
a=2
b = 330
print("A") if a > b else print("B")
19.3 Nested IF
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
19.4 pass statement
if statements cannot be empty, but if you for some reason have an if statement with no content, put
in the pass statement to avoid getting an error.
a = 33
b = 200
if b > a:
pass
Thank you for watching !
Next session,
1. Looping Statement
2. OOPs
Python Programming
20. Loops
Python has two primitive loop commands:
while loops
for loops
20.1 While Loop
With the while loop we can execute a set of statements as long as a condition is true.
Print i as long as i is less than 6:
i=1
while i < 6:
print(i)
i += 1
20.2 Break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3: i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
20.3 For Loop
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
20.3.1 Looping through String
Even strings are iterable objects, they contain a sequence of characters:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
20.4 Continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
20.5 Range() function
To loop through a set of code a specified number of times, we can use the range() function,
range(start,stop,step)
for x in range(6):
print(x)
for x in range(2, 6):
print(x)
for x in range(2, 30, 3):
print(x)
20.6 Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop"
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
20.7 pass statement
for loops cannot be empty, but if you for some reason have a for loop with no content, put in the
pass statement to avoid getting an error.
for x in [0, 1, 2]:
pass
21. Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
21.1 Function Call
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function()
21.2 Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Thank you for watching !
Next session,
1. Functions (part 2)
2. Anonymous Functions
3. OOPs
21.2 Arbitrary Arguments
If you do not know how many arguments that will be passed into your function, add a *
before the parameter name in the function definition.
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus"
21.3 keyword arguments
You can also send arguments with the key = value syntax
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
21.4 Arbitrary Keyword Arguments,
**kwargs
If you do not know how many keyword arguments that will be passed into your function, add two
asterisk: ** before the parameter name in the function definition.
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
21.5 Default Parameter Value
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Lambda Functions
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
lambda arguments : expression
x = lambda a : a + 10
print(x(5))