Basics Programming Python
Basics Programming Python
INTRODUCTION
• Covers basics of computer programming
• Information which can be applied to any and all programming languages
1. Introduction
2. What is programming?
3. How do we write code?
4. How do we get information from computers?
5. What can computers do?
6. What are variable?
7. How do we manipulate variables?
8. What are Conditional Statements?
9. What are Arrays?
10. What are Loops?
11. What are Errors?
12. How do we debug Codes?
13. What are Functions?
14. How we can import functions?
PROGRAMMING
• IDEs will let you know if there are syntax errors in your code
How do we get information from a computer?
CONSOLE
STRINGS
• Computer can also work with strings- another way to say text.
“Hello world” ; “A” – are strings
• Anything enclosed by quotation marks is denoted as a string
• Concatenation: Adding strings together
• print(“Game is over “+42+” is your final score”)
• print(“Game is over “+(4+2)+” is your final score”)
• 4 and “4” are different, mathematical operations are not allowed with “4”
• Addition can be done to concatenate strings
What are variables?
VARIABLE
• Something that can store information
• can be retrieved referenced and manipulated
• variable has a type, a name and a piece of information
NAME refers to the name of the variable, a label
TYPES
Type refers to different forms that the variable can take like integer (4), Boolean (true,
false), float (value of Pi), double (4.34256778…), string (“hi”), chars (“A”)
Integer-
Store and integer value, whole numbers like 2, 147, 684, -22
Boolean –
store a value of either true or false
USEFULNESS
• Variables are useful for
• Storing information
• Referencing
• Add to, or modify it.
• Taking inputs from user
• Making your program to have variability
• Manipulation of values
What happens when we define a variable?
• computer creates a little space in the memory that stores your variable name
and its content so that it can be referenced later
• It is like taking a box, labelling it (say, Name) and putting a piece of paper
written the information to be stored, say “nullpointerexception”
• if you want to know the content of your box called name, you just call it
computer will pool the information that is stored in that variable and use how
the user see fits.
• A variable is set by using equal to symbol
If statements:
• Most common type
• If something is true then the program will do one thing, otherwise will do
another thing or do nothing
if-statement structure
• Usually the condition will be enclosed by braces (). If the condition is met then carry
out instructions located within if statement curly braces {}
If (thing is true) {
Do what is inside the curly braces
}
• Python uses columns and white spaces to determine where a piece of code starts
and ends.
• There maybe many different types of conditions which are checked in if statements.
Examples:
If (name == “Steve”){
print (“Hello Steve”)
}
Switch (var):
• One biggest drawback with variables is that there inability to hold more than one piece
of information
• if we have list of names of the students in a class there is no way to use variables
because a variable will contain only one name in it
• But such list may become very important in-
Searching through it
Spliting it
Deleting one name from the list.
• This problem is solved by using an array
• Array is a list of items
Can be integers
Can be strings
Can be array of other arrays
• An array is a collection of information which all are related back to the title
Numbers 1 2 3 4 5 6 7 8 9 10
Index 0 1 2 3 4 5 6 7 8 9
• To refer to elements in array, we should call upon its index, a fancy way to saying that where
numbers are placed with in the array
• In programming languages first cell is referred to as zero
• If you slipup accidentally and reference the 10th element in the above array it would result in
an out of bound error since you are actually trying to reference the 9th element
INITIALIZE AN ARRAY
Index 0 1 2 3
Index Names Column1 Column2 Column3 Column4
0 Row1 John Steve Bob David
1 Row2 Tom Harry James Lily
2 Row3 James Jonny Alex Viv
30 68 34 19 19
58 47 96 25 34
87 91 23 12 15
45 42 49 13 144
78 87 95 14 35
{(30,68,34,19,19);
(58,47,96,25,34);
(87,91,23,12,15);
(45,42,49,13,144);
(78,87,95,14,35)}
What are loops?
• for each loop is useful for performing operations across entire collection of data.
print x
end
while loop
• Such a loop will continuously carry out its instructions while a conditional
statement given to it is true.
• It is similar to a for loop but broken apart. It can be used to purposely create an
infinite loop.
while (x == 0) while (x<3) while (score == “high score”)
do while loop
Benefits of loop
Syntax error:
• If there is any part of code that fails to meet the programming rules
• In this case computer does not know how to interpret the code
• Syntax errors can occur from mistakes like-
• forgot a ;
• defining a variable in two words
• Spelling mistakes
Logic error
• The code run smoothly without runtime or syntax error but the result is not what you
want
• Hardest type of error to solve
• Reason is often unknown to programmer
• Example- we want the sum to be stored in some variable but we have used
multiplication sign
How to debug code?
Types of functions
• If you don’t input two numbers for it to compare then it is going to throw and error
• A function which takes no argument and returns no value cannot be set to any
variable since it returns no value.
• Example: checkPrimeNumberAndDisplay()
• Importing functions allows you to gain access to libraries of functions that other people have
already made for you
• There are thousands of already made functions at your disposal and you can make use of
them in your code
• Libraries: collection of functions that all have the same theme. Example: math library, data
analysis library, graphic library etc.
• In most of the languages and import statement consists of three parts- the library you want
to import from the package then which class from that package you would like to use
• Example- you can load Java library and from there import util (short form of utilities)
package and then from that utility is package import this scanner class, a class which allows
to read information from the user
import.java.util.scanner
• Package : smaller set of functions and methods to help differentiate between thousands of
methods contained in a library
• A class is even more specialized
PYTHON BASICS
Features of Python Programming Language
• Easy to learn and code
• Python syntax is very simple compared to the languages like C, C++ and Java
• Cross platform
Windows Linux, Mac, Android
• Standard library
An extensive standard library available for anyone to use
The standard library has large number of modules and packages for image
manipulation, database handling, internet data handling, mathematical
operations, data compression, graphics and many such functionalities
• Interpreter based
Interpreter takes only one instruction from the source code and translates it
into machine code
The instructions that exist before the first occurrence of an erroneous
statement will be executed
• Interactive
Distribution comes with an interactive shell
You can write a valid Python expression after the prompt (>>>) it will be
readily executed
• Object-oriented and procedure-oriented
object oriented: program is designed focusing on data and object
procedural method the focus is on functions
Python supports both the approaches
• Extensible
Python can be extended to other programming languages
One can write modules in C language and incorporate it into the Python
library
• Portable
Python is portable across the systems
• GUI supportive
Python user can interact with the software using graphic user interface
(GUI)
• Expressive
Python requires writing a few lines to do complex tasks
• Dynamically typed
The type of the variable is not required to be declared at the time of
defining it in the code
• Script Mode
Codes can be written in a file with extension .py (filename.py) and it can
be run to execute
VARIABLES AND THEIR TYPES
A python variable needs to have- (A) Identity; (B) Type and (C) value
Identity:
The identity of a variable refers to its address in the memory. The identity of a variable
cannot be changed once created.
type(variablename)
Numbers: These variables store numerical values
1. Integers
>>> a = 10
>>> b = 519287997458797745899666545
>>> type(a)
Output: int
Boolean
• A unique data type consisting of two constants- True and False
• A Boolean true value is non-zero, non-null and non-empty data
Example:
>>> x = 1 + 0j
>>> print x.real, x imag
Output: 1.0 0.0
>>> Y = 9 - 5j
>>> print y.real, y.imag
Output: 9.0 -5.0
2. None
• Data with single value
• Used to define a non value or no value at all
• But None is not the same as 0, false or an empty string
3. Sequence
• Ordered collection of items indexed by positive integers
Examples:
>>> a = ‘Robin’
>>> b = “David”
>>> type(“Good Morning”)
output: string
>>> type(‘3.2’)
output: string
Type casting
• Change one type of value to another type
Lists
• Sequence of value of any type
• Values in a list are called 'elements‘
• These are mutable and indexed and ordered, and allow duplicate values
• Elements are closed in square brackets
Example:
>>> l = ['spam', 20.5, 5]
Tuples
Sequence of values of anything indexed by integer, ordered
Elements are immutable and the elements are enclosed by ()
Allow duplicate values
Example:
>>> t = (4,2)
>>>T = ("apple", "banana", "mango")
>>> type(t[0])
Output: apple
4. Sets
Example:
>>> s = {"apple", "banana", "mango"}
>>> set = {"apple", "banana", "mango", "banana"}
>>> print(set)
Output: {"apple", "banana", "mango“}
5. Dictionaries
• Items are ordered, changeable and do not allow duplicates
• Items are present in key : value pairs enclosed in {}
• The values are accessed by the key
Example:
>>> dict = {
"brand": "Maruti",
"model": "Dezire",
"year": 2020
}
print(dict["brand"])
Output: Maruti
Operators are special symbols which represent computations. They are applied on
'operands' (i.e. values or variables).
INPUT AND OUTPUT
• Data will be entered by the end user
• input() function available for input
input() or input(prompt)
input(“Enter Name: “)
• Program will stop and expect that the user will input data from keyboard
• User input data from keyboard and then presses enter
• Always of string type, type casting to be done to change data type
X = input(“Enter Name: “)
Enter Name: ABC (input by user from keyboard)
print(type(x) )
y = input(“Enter mobile no. “)
type(y)
mobile = int(y)
type(mobile)
• Valid Python expression is expected
X = input(‘Enter data: ‘)
Enter data: 5+1.0/2
It will store 5.5 to X.
OUTPUT
• Output is what the program produces
• print()function
• Syntax
print expression/constant/variable
• It outputs an entire line and goes to the next
• To print more than one item on a single line comma (,) can be used
print “hello”
print x, y
print 5.5
Comments
• Starts with # symbol
• Interpreter will ignore anything after # symbol
• A comment can also be written within triple quotes.
Example:
“””Calculate area
of a triangle”””
FUNCTIONS
• A function is a named sequence of statements that performs computations
• Executed by Python interpreter from top to bottom of the code
• A module is a file containing Python definitions (functions) and statements
• Modules are collected in the standard Python library
• Programmer needs to import the module
• Once a module is inserted/ imported, you can use any of the functions or variables from the
module in your code
Example:
calculation.py script file
def addition(x, y):
return (x+y)
def subtraction(x+y)
return(x-y)
• Modules can be imported into a program by using import statement
Syntax for calling Module:
import modulename
To import math module write-
import (math)
• This statement will instruct the interpreter to search for the specific module and create space
where module definitions (functions) and variables will be stored
• Then execute the statements in the module
• Once imported, the module functions and variables becomes part of the code
value = math.sqrt (25)
• sqrt () function of the math module is used to calculate square root
• Value in parenthesis, known as argument
• Result is inserted into value variable
Example
import calculation
result = calculation.addition(6, 8)
print(result)
• from statement is used to get a specific function from a module instead of calling the complete
module file
• Syntax
b = fn2(fn1(a)) sin(math.radians(30))
• A keyword def,
• then comes Name of the function, followed by
• () containing list of arguments and then
• Block statements
Examples:
Create a function:
# function area calculates the area of a circle given the radius as argument
def area(radius):
import math
a = math.pi*(radius**2)
return a
Call the function:
area(2)
Output: 12.566370614359172
Define a function:
# The check function checks if a number, given as an argument, is an even
number or not. If it is odd, the function prints True, else False
def check(num):
if (num%2==0):
print ("True")
else:
print ("False")
test()
Output: Inside test: 50
Any modification to global is permanent and visible to all
functions written in the file.
x = 50
x = x+10
def test():
print("Inside test: ", x)
print ("Outside test: ", x)
Output: Outside test: 60
test()
Output: Inside test: 60
II. Local scope:
A variable with local scope can be accessed only within the function.
a = 10
def local():
b = 20
print("Inside the function the value of a is ",a,
"and value of b is ",b)
print ("Outside the function the value of a is ", a)
print ("Outside the function the value of b is ", b)
if Statement:
if CONDITION:
x = int(input())
STATEMENTS BLOCK 1
if x > 0:
x = int(input())
print ("x is
if x > 0: positive")
print ("x is positive")
if-else Statement: x = int(input())
if CONDITION:
if x > 0:
STATEMENTS BLOCK 1
print ("x is positive")
else:
else:
STATEMENTS BLOCK 2
print("x ix negative")
Another way to write if-else statement is:
variable = variable1 if condition else variable2
a = 10
b = 5
x = True
y = False
variable = x if a < b else y
variable
Output: False
Nested condition
x = int(input("Insert a number x"))
y = int(input("Insert another number y"))
if x == y:
print("x and y are equal")
if x > y:
print("x is greater than y")
else:
print("x is smaller than y“)
LOOPING CONSTRUCTS
while loop
for loop
A. while loop:
Executed repetitively until the condition remains true. A variable will move nearer to
completion after each execution of the loop. This is called loop control variable.
Syntax:
while CONDITION:
STATEMENT BLOCK
Control variable is modified
Example:
# A loop to print numbers from 1 – 10
i = 1
while i <=10:
print (i)
i = i+1
Here i is the loop control variable.
The’ while’ loop may come with else, break and continue statements.
The ‘while’ loop can be stopped with a ‘break’ statement, even if the condition is
true.
Example:
i = 1
while i <=10:
print (i)
if i == 3:
break
i = i+1
‘continue’ statement with while loop:
The continue statement directs the loop to continue to the next iteration.
Example:
i = 0
while i <=10:
i = i+1
if i == 3:
continue
print (i)
Nested while loop:
When a while loop is placed inside another while loop then it becomes a nested loop.
Example:
i = 1
while(i<=5):
j = 1
while(j<=i):
print(j,end=" ")
j = j+1
print()
i = i+1
To print the elements in the same line separated by a white space we use: end =” “
To print in a new line we use: print()
for Loop
A ‘for’ loop executes statements for every of the elements of a sequence (list,
set, tuple, dictionary, string etc.). ‘for’ loop iterates over elements of a sequence.
Syntax:
for TARGET-LIST in EXPRESSION-LIST:
Statement Block 1
[else:
Statement Block 2]
Example:
# Loop to print 1 to 10
x = [1,2,3,4,5,6,7,8,9,10]
for i in x:
print (i, end= " ")
Output: 1 2 3 4 5 6 7 8 9 10
range() function:
• In for loop the range () function is used to define a sequence of integers over which
the loop will iterate
• In the range () function 3 integer values are given as arguments- start, end and step.
• The start value is optionally given to start from a particular number while the default
value is 0,
• the end value is mandatory; loop will stop just before this value is reached. It means
for range (6), the loop will run for 0, 1, 2, 3, 4 and 5.
• The last argument is also optional and it specifies the interval of the sequence.
Example:
for i in range(0, 10, 2):
print(i, end=" ")
Output: 0 2 4 6 8
Break statement:
The control unconditionally jumps out of the loop.
for i in "python":
if i == 'h':
break
print (i, end=" ")
Output: p y t
Continue Statement:
The continue statement is used to skip rest of the statement of the current loop.
Example:
for i in "letter":
if i == 't':
continue
print (i, end=" “)
Apart from range (), for loops can take values from strings, lists, dictionaries etc.
Example:
for i in "python":
print(i, end=" ")
Output: p y t h o n