0% found this document useful (0 votes)
2 views73 pages

Basics Programming Python

The document provides an overview of the basics of programming, including definitions, concepts, and structures applicable across various programming languages. Key topics include variables, conditional statements, arrays, loops, and the importance of syntax and Integrated Development Environments (IDEs) for writing and debugging code. It emphasizes the role of programming languages as intermediaries that translate human instructions into machine code, enabling computers to perform tasks accurately.

Uploaded by

deadm2018
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)
2 views73 pages

Basics Programming Python

The document provides an overview of the basics of programming, including definitions, concepts, and structures applicable across various programming languages. Key topics include variables, conditional statements, arrays, loops, and the importance of syntax and Integrated Development Environments (IDEs) for writing and debugging code. It emphasizes the role of programming languages as intermediaries that translate human instructions into machine code, enabling computers to perform tasks accurately.

Uploaded by

deadm2018
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
You are on page 1/ 73

BASICS OF PROGRAMMING

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

• Programming is the process of preparing an instructional program for a device.


• Attempting to get a computer to complete a specific task without making mistakes.
• It is like instructing your less intelligent friend to do something
• He can only build based on your commands
• He is far from competent on his own and so you must give him exact instructions
on how to build
• If there is even one piece of wrong the entire build is ruined
• Now replace the friend with computer and that is how we code.
• Computers only understand MACHINE CODE
• A series of 1’s and 0’ fed and interpreted by the computer
• Only way a computer can read English instructions.
• To make things worse, let your friends speaks Mandarin and you speak English, making
it impossible to communicate
• You need to convert your instructions from Mandarin to English in order for him to
understand them
• Similarly, in order to talk to computer you must first translate your English instructions
to Binary.
• It will be impractical to go for converting instructions into Machine code manually
PROGRAMMING LANGUAGES
• Programming languages serve as a middle-man
• Translate your instructions into MACHINE CODE
The series of 1’s and 0’s that the computer can understand
• Very useful for programmers
• Programming Languages serve as interpreters for converting languages
into other languages (faster than converting by hand)
• Each language is unique in how they operate
 Java and Python are general purpose languages
 HTML or CSS are designed for specific tasks like web page designing
• Languages also vary in how powerful it is
•JavaScript is not used for big problems
•Java and Pythons are
• Each language has also an attribute known as power or level, basically how
similar it is to machine code
• Low level programming languages, for example assembly or C
• High level programming language like Java and Python
How do we write a code?
• We cannot simply write words into a text document and expect that computer is able
to carry out the task
• We need Programming languages
• we cannot write down rubbish in certain programming languages
• We use IDEs (integrated development environment) to write code
• IDE is a graphic interface in which the programmer can easily right run and debug
code and also convert it into Machine Code.
• IDEs are like any other program on your computer used to facilitate coding. Example-
netbeans ,intellij, Visual Studio.
• In addition to a place to write code IDE also includes
• built-in error-checking for when code does not go right,
• auto fill for frequently used words auto fill for frequently used words
• project hierarchy that is organized files under a project
•IDE usually has a central area for writing codes and additional windows such as one for
printing useful information for the programmer (called Console), project hierarchy,
preview screen etc.
SYNTAX
• We cannot write random codes from a certain programming language
• Each programming language has its own set of rules you must follow within an IDE,
called syntax.
• Syntax- rules you must follow if you want the program to run correctly. It is related to-
 How you type out certain functions?
 What you put at the end of each line?
 How you set up certain functions?
• Learning a computer language is very similar to learning real languages.
• Syntax similar to grammar in real life.
• Programming grammar is referred to as syntax.
• All programming languages have a set of rules you must follow when writing a code.
• Syntax for each language is unique.
• Breaking programming rules will result in an error
• A variable is initialized differently in Java, python and JavaScript though
goal of the program is same but all three languages take very different
approaches

int x = 3; x=3 var x = 3


[Java] [Python] [JavaScript]

• If you forget one semicolon or misplace a character, the entire program


will not run and send you back a Syntax Error

Let’s eat, Maa!


Let’s eat Maa

• IDEs will let you know if there are syntax errors in your code
How do we get information from a computer?
CONSOLE

• Programmers keep track of their progress by looking at the


console

• console is to display output text from the program

• Text outputs are generally obtained from print statement.

• Do something and then instruct the computer to print the


output. This confirms that the computer has carried out the
instructions correctly

• Console is a developer’s tool not meant to be used by the


end user, it is hidden away behind the screen
What can computer do?
MATH
• The computer already knows how to do simple arithmetic
• Addition, subtraction, multiplication and division
• You will be able to print the results of any arithmetic operation in an IDE.
• Additional parameter known as modulus
• Modulus allows to get remainder of a divisional operation, ignore result
• EVEN and ODD numbers

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

Floats and Doubles-


• Store floating point data types- numbers with decimal places.
• Float can hold 32 bits of information and a double can hold 64 bits of information
(precision up to 64 bit) .
Strings-
• Store string of letters or sentences
• Useful for displaying information
• Strings can also be concatenated together
• Input from the user to type in name. Once the user type in name it will be
stored in a string variable
• Strings also help in displaying output

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

In Java: int x = 10;


In python: x = 10
BLANK VARIABLE

• Create a variable without value


• Can put value in it later down the road
• Simply saving some space in your computer
How do we manipulate variables?

• Dual pointed variable: string channelName = name;


• Variables can be updated.
X = 10
X = 18
• Each time you are running the code you are making new boxes and at the end of the code
you are destroying them all
• Arithmetic operations
 Addition subtraction multiplication division modulus are allowed for integer, float
and double type variables
 String variables can only be added
 Chars and Boolean cannot be operated on
Naming convention of variable-
• Name must be one continuous string
• If you need to use two words they are to be placed without any gap in between
 Camel case (don’t capitalize the first word but capitalize the first letter of all worlds after it (e.g
nullPointException).
 Use underscore between the words for a variable name, e.g. channel_name
• Keywords used in the programming languages such words are generally avoided while naming the
variables.
What are Conditional Statements?

Depending on certain conditions we want our code to do different things

If the condition is met-


• Our code will not be going down this path
• Our code will be going down this path

Conditional statements can take different forms-

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”)
}

If (score > 300){


Print (“ Nice Score”)
}
• Each condition is checked as a Boolean true or false
• If it turns out falls then the code pretends like everything within curly braces never
existed
if-else Statement

If the condition is True, then do one thing , otherwise do another thing

if (condition is TRUE){ if (x%2=0){


Do task 1 print (“Number is even”)
} }
else { else {
Do task 2 print (“Number is odd”)
} }
else-if statement
else-if statement will only be evaluated if the preceding if or else-if statement was
bypass due to it being false. It works in the following sequence

1. Check the initial statement (if statement)


2. If it is true we run that segment of code which comes after if statement within curly
braces, then move on to the rest part of the code.
3. If the condition in 1 is not true, we move on to any else-if statement and evaluate the
conditions associated with it. If this else-if condition is true then instructions within curly
braces immediately after the else-if condition will be executed, otherwise the program
control will move on to the next else-if segment, if there is any. And then move on.
4. If any of the if and else-if conditions are not true then the else part is executed.
if (if-condition is true){
Carry out instructions 1
}
else-if (else-if condition 1 is true){
Carry out instructions 2
}
else-if (else-if condition 2 is true){
Carry out instructions 3
}
else {
Carry out instructions 4
}
SWITCH statement

• Starts with a colon (:)


• Associated with a number of cases
• Each case is associated with a task
• Each switch statement also includes “default” case (similar to else)

Switch (var):

Case A Do something specific

Case B Do something specific


Rest part of
task
Case C Do something specific

Default Do Default task


What are Arrays?

• 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

Name Steve Robin John Graham David


Title Element1 Element2 Element3 Element4 Element5
REFERENCING ARRAY

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

• You can do this in either one of two ways.


 You can populate it with all the elements (creating and filling the array at the same time)
 You can define how many elements you want the array to hold and then populate it
with elements later
• When you initialize an array in this way it create some space in memory that has a size exactly
you give
• When we create array their sizes are final it cannot be increased or decrease in size
• While initializing and array you must determine its type. String array, integer array, double
array etc.
• The elements in an array should be of same type
PUTTING ARRAY WITHIN AN ARRAY

• Instead of using columns only in an array, we would add rows to it as well


• Every row is considered as an element of the array while every row element is also
an array in its own- 2-dimensional array
• Referencing in two dimensional arrays is done by an index of two numbers, the first
number refers to the position of the and the second number refers to the position
of the column.
• Index 12 refers to “James”

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

A 2-D array can be expressed as

{(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?

• Loops are the statements used to run certain instructions repeatedly.


• They are very useful for repeated sections of a code.
• For example, if you want to print the same string for a hundred times it will require
rewriting the same instruction over and over again. You can place the print
statement inside of a loop and it will print as many times as you would like.
• There are three types of loops used in programming languages.
 for loop
 for each
 while loop
 do while loop
for loop

• A for loop consists of three parts-


• An integer value
• A conditioner statement that the integer must reach a value for existing will
loop
• An operation to modify the integer value, after the instruction inside the
loop is completed

for (int i = 0; i<3; i++){


Print (“Hello World”);
}

Infinite loop: condition is never met


and in that situation program will crash

for ( int x = 10; i < 3; i++){


Print (“Hello World”)
}
for each loop

• These are used for iterating through entire array or list.


• The loop will
•go through each element in the array
•carry out is set of instructions for each value.

• for each loop is useful for performing operations across entire collection of data.

seq = [18, 29, 38]

for each x of seq

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

• A do while loop is functionally similar to while loop.


• It will always carry out instruction at least once.
• The instruction inside loop will run once before checking the conditional
statement.

Benefits of loop

• Performs operation many times in a row


• Able to iterate through arrays and lists
• Decrease clutter of your code
Error or bug
• Your code does not work as expected because of certain errors in the code
known as bugs or errors.
• There may be three types of bugs or errors.
• Syntax error
• Runtime error
• Logic error

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

• The program will not run with a syntax error


• These errors are easy to solve because they are generally highlighted by IDE
Runtime error
• Do not appear until you actually run the code
• Caused by a part of your code not being able to be interpreted by computer in a
reasonable amount of time in spite of it being logically sound
• Example- infinite loop, instructions like ‘go to hell’. There is no feasible way to finish
it. The program will crash
• In order to avoid runtime error think through the flow of your code before running it
and plan your code before writing it

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?

• IDE will often print out an error message to the console


• Traverse through the line that gives error
• Syntax or runtime errors can be fixed easily
• For logic error use print statements to the console to see where the code is
going wrong. You have planned the code in some way but the computer is
thinking in another way. Place print statement at every branch of the code
and see from the print where the code is going wrong
• Use breakpoint
Commenting

• Comment out suspected section of the


code
• Run the code
• In python the symbol # is used for
commenting
What are functions?
• Functions are used to reuse code and thus making programs more efficient
and easier to read
• The functions we have already used are-
 Print
 For loops
 Basic mathematical operation like addition, subtraction,
multiplication, division
• Function is a segment of code that can be run by calling the function name
and function will do something in return.
• Can be called for any number of times and at any place in the code
• They are like wrapping up a segment of code into a nice present and giving it
a name which when called will unwrap the present and go through the code
print (“This is to be printed”)
• Functions reduce stress of programmers
Functions serve many purposes

• Used to recycle section of code which serve the same purpose


• Used for equations you want to allow many inputs
16 – 2t = 5t + 9
• Used to save space within your program

Types of functions

With return value


With argument
Without return value
Functions
With return value
Without argument
Without return value
• Variables that are passed into the function in order to be manipulated and returned
back to the user for print output or use in other subsequent operations
• Example:
• max () is a function which takes in two integers as arguments and returns the
maximum number between the two.

int maxNumber = max(1,100)


maxNumber = 100
int maxNumber = max(60,2)
maxNumber = 60
int maxNumber = max( “steve”,”robin”)-----error

• If you don’t input two numbers for it to compare then it is going to throw and error

Why are arguments useful?


• Arguments are way for a programmer to have one function that can do many
different things
• Add variability to program
• Helps diversity of your code
Function without argument

• No need to pass arguments into the function


• Example: checkPrimeNumber() that takes inputs from the user and returns if the
input number is a prime number or not
Functions with return value
Examples:

int maxNumber = max(100,10)


print(max(100,10)

Functions with no arguments and no return value

• 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

Java is the library; util is the package and scanner is class

• 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

• Free and open source


 Freely available and can be used, modified and re-distributed even
forcommercial purposes

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

Types (Data types)

type(variablename)
Numbers: These variables store numerical values

1. Integers

>>> a = 10
>>> b = 519287997458797745899666545
>>> type(a)
Output: int

 Need not to worry about size

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

>>> flag = True


>>> type(flag)
Output: bool

Floating Point data


• Fractions or decimal points.
• Example 0.0, - 21.9, 0.9833, 15.2963, - 2e5 (- 2 x 105), -2e-5 (-2X10-5)
Complex number
• Made up of two floating point values 1 each for real part and an imaginary part
• Accessed as
x.imag and x.real

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

• 3 types of sequence data: string, list and tuple


String
• Ordered sequence of letters/characters enclosed by " " or ' ‘

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

• Unordered collection of values of any type with no duplicate entry


• Unordered means
 do not have any defined order.
 The elements can appear in different orders every time they are used
 they cannot be referred to by index

• Values are immutable


• 1 are considered the same value in sets and therefore, are treated as duplicate
• Set items are unchangeable, but items can be removed or new items can be added

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

Mutable and immutable variables


>>> x = 5
>>> y = x (y refers to 5 stored in x)
>>> x = 10
>>> print x
Output: 10
>>> print y
Output: 5
Variable name

• Can be of any size


• Allowed characters: a-z, A-Z, 0-9, underscore
• Should begin with an alphabet or underscore
OPERATORS AND OPERANDS

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

from modulename import functioname1 [, functioname2, … . ]


Example
from math import sqrt
value = sqrt (25)
• Some Functions in the ‘math’ module
• Built-in Functions
Composition

b = fn2(fn1(a)) sin(math.radians(30))

USER DEFINED FUNCTION

• 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

The return statement can also be written as-


return radius**2
Void Function
A void function does not return a value, but prints a message on screen

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

Call the function:


check(19)
Output: False
check(20)
Output: True
result = check(22)
Output: True
print(result)
Output: None
Parameters and Arguments

• Parameters are values provided in the parenthesis


• values are required for the function to work
• In the function area (radius), 'radius' is the parameter
• Arguments are the values provided in the function call
• List of arguments should be supplied in the same order as parameters are listed
• An one-to-one parameter-argument bounding is required
• The arguments should be of the same data type as the parameter is
Scope of variable:
I. Global scope:
Variable with Global scope can be used anywhere in the
program. It can be created outside a function but can be used in
function.
x = 50
def test():
print ("Inside test: ", x)
print ("Outside test: ", x)
Output: Outside test: 50

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)

Output: Outside the function the value of a is 10


print ("Outside the function the value of b is ", b)
Output: NameError: name 'b' is not defined
local()
Output: Inside the function the value of a is 10 and
value of b is 20
Few more points on function:
 A global variable remains global even if its value is changed within a function. Such
change in value remains limited to the function.
Explanation:
x = 50
def test():
x = 20
y = 40
print("Inside the function the value of x is ",
x, "and the value of y is ", y)
test()
print("Outside the function the value of x is",x)
Outputs:
Inside the function the value of x is 20 and the
value of y is 40
Outside the function the value of x is 50
 But if you want to change the value of a global variable inside a function refer the
variable as global first.
Explanation:
x = 50
def test():
global x
x = 20
y = 40
print("Inside the function the value of x is ",
x, "and the value of y is ", y)
test()
print("Outside the function the value of x is",x)
Outputs:
Inside the function the value of x is 20 and the
value of y is 40
Outside the function the value of x is 20
 Default value of a parameter can be set while defining the function.
Explanation:
def greetings(message, times = 2):
print(message*times)
greetings("Good morning, ")
Output: Good morning, Good morning,
greetings("Good morning, ",3)
Output: Good morning, Good morning, Good morning,
 A function has multiple parameters and some of them are set with default values.
def arg(a, b=1, c=5):
print("a = ",a, "b = ",b, "c = ",c)
arg(3)
Output: a = 3 b = 1 c = 5
arg(3, b=2)
Output: a = 3 b = 2 c = 5
arg(25, c=10)
Output: a = 25 b = 1 c = 10
CONDITIONAL CONSTRUCT

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.

‘else’ statement in while loop:

The else statement, if present, is executed when the loop is completed.


Example:
i = 1
while i <=10:
print (i)
i = i+1
else:
print("End")
‘beak’ statement with while loop:

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

Nested for loop (for loop in another for loop):


# to print tables starting from 1 to specified number
n= 1
for i in range(1, n+2):
print ("Following is the Table of ",i)
for j in range(1,11):
print(i,"*",j,"=",i*j)
LISTS

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy