Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views

Unit 1 Python notes

Bca 3rd sem Bangalore University

Uploaded by

bhuvaneshnair21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Unit 1 Python notes

Bca 3rd sem Bangalore University

Uploaded by

bhuvaneshnair21
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Unit -1

Parts Python Programming Language

 Variables, Keywords
 Statements and Expressions
 Operators, Precedence and Associativity
 Data Types, Indentation, Comments
 Type Conversions, the type () Function and Is Operator
 Control Flow Statements
- The if Decision Control Flow Statement
- The if…else Decision Control Flow Statement
- The if…elif…else Decision Control Flow Statement
- Nested if Statement
- The while Loop
- The For Loop
- The Continue and Break Statements
 Function Definition and Calling the Function
 The Return Statement and Void Function
 Command Line Arguments
 String Creating and storing
 Accessing Character in string
 String methods
Introduction

Why to choose python language?

There are many reasons:

 Easy-to-learn - Python has few keywords, simple structure, and a clearly


defined syntax.
 Easy-to-read – Python code is more clearly and visible to the eyes.
 Easy-to-maintain – Python’s source code is fairly easy-to-maintain.
 A broad standard library – Python’s bulk of the library is very portable and
cross-platform compatible on Unix, Windows, and Macintosh.
 Database – Python provides interfaces to all major commercial databases.
 Portable - Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
 Scalable- Python provides a better structure and support for large programs
than other scripting languages.

Interpreter and Compiler


 Python is a high-level language intended to be relatively straightforward for
humans to read and write and for computers to read and process.
 The CPU understand a language called machine language. Machine Language
is very tiresome to write because it is represented all in zeros and ones.
 Hence this high-level programming language has to be translated into machine
language using translations such as:
1)Interpreters
2)Compilers Interprets it immediately. Every
line of code can generate the
Interpreter output immediately

Source Code

Executable files
Compiler
(with extensions .exe,.dll)
Interpreter Compiler

Errors are displayed in every Errors are displayed in


single line. Compiler after Compiling
together at the current time.

The Interpreter does not save The compiler saves the


the Machine Language. Machine Language in form of
Machine Code on disks.

Interpreted codes run slower Compiled codes run faster than


than Compiler. Interpreter.

The interpreter does not The compiler generates an


generate any output. output in the form of (.exe).
It requires source code for later It does not require source code
execution. for later execution.
CPU utilization is less in the CPU utilization is more in the
case of an Interpreter. case of a Compiler.
No object code is saved for Object code is permanently
future use. saved for future use.

Python Program Execution


The execution of the Python Program involves 2 steps:
->Compiler
->Interpreter

Python compiled 101010101


Python Program
file 101010101
First.py
First.pyc 101010101

Source code Byte code Machine Code

Computer
Compiler
For Converting the code written in a high-level language into machine-level language
so that computers can easily understand, we use a compiler. Converts basically convert
high-level language to intermediate assembly language by a compiler and then
assembled into machine code by an assembler.

Interpreter

The simple role of an interpreter is to translate the material into a target language.
An Interpreter works line by line on a code. It also converts high-level language to
machine language.

What is Python
 Python is a widely used general-purpose, high level programming language.
It was created by Guido van Rossum in 1991 and further developed by the
Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in
fewer lines of code.
 Python is a high-level, general-purpose, and interpreted programming
language used in various sectors including machine learning, artificial
intelligence, data analysis, web development, and many more. Python is
known for its ease of use, powerful standard library, and dynamic semantics.

Features of Python:

 Simple and Easy to Learn


- Python is a simple programming language. When we read Python
Program, we can feel like reading English statement.
- The Indentation is used instead of curly braces in Python makes it very to
read python code.
 Platform Independent:
- Once we write a Python program, it can run on any platform without
rewriting once again. Internally PVM is responsible to convert into
machine understandable form.

 Portability:
- Python programs are portable. i.e. we can migrate from one platform to
another platform very easily. Python programs will provide same results
on any platform.

 High Level Programming language:


- Python is high level programming language and hence it is programmer
friendly language. Being a programmer, we are not required to
concentrate low level activities like memory management and security
etc...

 Freeware and Open Source:

- We can use Python software without any licence and it is freeware. Its
source code is open, so that we can we can customize based on our
requirement.

 Interpreted:
- We are not required to compile Python programs explicitly. Internally
Python interpreter will take care that compilation.
- If compilation fails interpreter raised syntax errors. Once compilation
success then PVM (Python Virtual Machine) is responsible to execute.

 Extensible:
- We can use other language programs in Python.
- The main advantages of this approach are:
1. We can use already existing legacy non-Python code.
2. We can improve performance of the application.

 GUI Programming:
- Python offers various libraries for creating Graphical user interface for
any application.
 Embedded:
- We can use Python programs in any other language programs. i.e. we
can embed Python programs anywhere.

 Both Procedure Oriented and Object Oriented:


- Python language supports both Procedure oriented (like C, pascal etc)
and object oriented (like C++, Java) features. Hence, we can get
benefits of both like security and reusability etc.

Limitations of Python:
1. Performance wise not up to the mark because it is interpreted language.
2. Not using for mobile Application.

Python vs JAVA

Python Java

Dynamically Typed Statically Typed


 No need to declare  All variable names (along with
anything. An assignment their types) must be explicitly
statement binds a name to declared. Attempting to assign an
an object, and the object object of the wrong type to a
can be of any type. variable name triggers a type
 No type casting is required exception.
when using container  Type casting is required when
objects using container objects.

Concise Express much in limited


Verbose Contains more words
words

Compact Less Compact

Uses Indentation for structuring


Uses braces for structuring code
code
Identifiers
 A Python identifier is a name used to identify a variable, function, class,
module or other object, an identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores and digits (0 to 9).
 Any name that is used to define a class, function, variable module, or object is
an identifier.
 Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
 Here are Naming Conventions for Python identifiers
1. Class names start with an uppercase letter. All other identifiers start with
a lowercase letter.
2. Starting an identifier with a single leading underscore indicates that the
identifier is private.
3. Starting an identifier with leading underscores indicates a strongly
private identifier.
4. If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.

Variables, Keywords
 A variable is a named place in the memory where a programmer can store data
and later retrieve the data using the variable name.
 An assignment statement creates new variables and gives them values.
 In python, a variable need not be declared with a specific type before its usage.
The type of it will be decided by the value assigned to it.

 Rules to follow when naming the variables.


- Variable names can contain letters, numbers, and the underscore.
- Variable names cannot contain spaces and other special characters.
- Variable names cannot start with a number.
- A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _).
- Keywords cannot be used start with a number.
- Variable in Python names are case-sensitive (name, Name, and NAME are
three different variables).

Declaration and Initialization of Variables


# declaring the var
Number = 100

# display
print (Number)

Types of Variables

Python supports 2 types of variables.


1. Global Variables
2. Local Variables

1. Global Variables
The variables which are declared outside of function are called global variables. These
variables can be accessed in all functions of that module.
Eg:
a=10 # global variable
def f1():
print(a)
def f2():
print(a)
f1()
f2()
Output
10
10
2. Local Variables:
The variables which are declared inside a function are called local variables. Local
variables are available only for the function in which we declared i.e. from outside of
function we cannot access.
Eg:
def f1():
a=10
print(a) # valid
def f2():
print(a) #invalid
f1()
f2()
Name Error: name 'a' is not defined

Global keyword:
We can use global keyword for the following 2 purposes:
1. To declare global variable inside function.
2. To make global variable available to the function so that we can perform required
modifications.
Eg: a=10
def f1():
global a
a=777
print(a)
def f2():
print(a)
f1()
f2()
Output
777
777
Keywords
 Keywords are a list of reserved words that have predefined meaning.
 Keywords are special vocabulary and cannot be used by programmers as
identifiers for variables, functions, constats or with any identifier name.
 Attempting to use a keyword as an identifier name will cause an error.

Rules for Keywords in Python


 Python keywords cannot be used as identifiers.
 All the keywords in Python should be in lowercase except True and False.

List of Python Keywords

Keywords Description

This is a logical operator which returns true if both the


and
operands are true else returns false.

This is also a logical operator which returns true if anyone


or
operand is true else returns false.

This is again a logical operator it returns True if the operand is


not
false else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The


elif elif statement is executed if the previous conditions were not
true.

Else is used with if and elif conditional statements. The else


else
block is executed if the given condition is not true.
Keywords Description

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

pass This is a null statement which means it will do nothing.

return It will return a value and exit the function.

True This is a Boolean value.

False This is also a Boolean value.

try It makes a try-except statement.

with The with keyword is used to simplify exception handling.

This function is used for debugging purposes. Usually used to


assert
check the correctness of code
Statements and Expressions
Statement
 A statement is an instruction that the Python interpreter can execute. We have
normally two basic statements, the assignment statement and the print
statement.
 Some other kinds of statements that are if statements, while statements, and for
statements generally called as control flows.

Examples: An assignment statement creates new variables and gives them values:
>>> x=10
>>> college="gfgc"
A print statement is something which is an input from the user, to be printed / displayed
on to the screen (or) monitor.
>>> print ("gfgc college")

Expressions
An expression is a combination of values, variables, and operators. An expression is
evaluated using assignment operator.
Examples:
Y=x + 17
>>> x=10
>>> z=x+20
>>> z 30
>>> x=10
>>> y=20
>>> c=x+y
>>> c 30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y
20
Operators, Precedence and Associativity
 Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.
 Python provides the following set of operators
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Special Operators
7.Membership Operators

1. Arithmetic Operators

Operator Description Syntax

Addition: adds two


+ x+y
operands

Subtraction: subtracts
– x–y
two operands

Multiplication:
* x*y
multiplies two operands

Division (float): divides


/ the first operand by the x/y
second

Division (floor): divides


// the first operand by the x // y
second

Modulus: returns the


remainder when the first
% x%y
operand is divided by
the second
Operator Description Syntax

Power: Returns first


** x ** y
raised to power second
Eg:
a=10
b=2
print ('a+b= ‘, a+b)
print ('a-b=‘, a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)

2. Relational Operators or Comparison Operators


These are used to check the relationship (like less than, greater than etc) between
two operands. These operators return a Boolean value either True or False.

Operator Description Syntax

Greater than: True if the


> left operand is greater x>y
than the right

Less than: True if the left


< operand is less than the x<y
right

Equal to: True if both


== x == y
operands are equal

Not equal to – True if


!= x != y
operands are not equal

Greater than or equal to


>= x >= y
True if the left operand is
Operator Description Syntax

greater than or equal to


the right

Less than or equal to True


<= if the left operand is less x <= y
than or equal to the right
Eg:
a=10
b=20
print ("a > b is “, a>b)
print ("a >= b is ",a>=b)
print ("a < b is ",a<=b)
a > b is False
a >= b is False
a < b is True
a <= b is True

3. Logical operators
The logical operators and, or, not are used for comparing or negating the logical
values of their operands and to return the resulting logical value. The result of
the logical operator is always a Boolean value, True or False.

Operator Description Syntax

Logical AND: True if


and x and y
both the operands are true

Logical OR: True if


or either of the operands is x or y
true

Logical NOT: True if the


not not x
operand is false
Eg:

a = True
b = False
print (a and b)
print (a or b)
print (not a)

4. Bitwise operators

Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Eg:
a = 10
b = 4
print (a & b)
print (a | b)
print(~a)
print (a ^ b)
print (a >> 2)
print (a << 2)
5. Assignment operators

Operator Description Syntax

Assign the value of the


right side of the
= x=y+z
expression to the left side
operand

Add AND: Add right-


side operand with left-
+= a+=b a=a+b
side operand and then
assign to left operand

Subtract AND: Subtract


right operand from left
-= a-=b a=a-b
operand and then assign
to left operand

Multiply AND: Multiply


right operand with left
*= a*=b a=a*b
operand and then assign
to left operand

Divide AND: Divide left


operand with right
/= a/=b a=a/b
operand and then assign
to left operand

Modulus AND: Takes


modulus using left and
%= a%=b a=a%b
right operands and assign
the result to left operand

Divide(floor) AND:
Divide left operand with
//= right operand and then a//=b a=a//b
assign the value(floor) to
left operand

Exponent AND:
**= a**=b a=a**b
Calculate exponent(raise
Operator Description Syntax

power) value using


operands and assign
value to left operand

Performs Bitwise AND


&= on operands and assign a&=b a=a&b
value to left operand

Performs Bitwise OR on
|= operands and assign a|=b a=a|b
value to left operand

Performs Bitwise xOR on


^= operands and assign a^=b a=a^b
value to left operand

Performs Bitwise right


shift on operands and
>>= a>>=b a=a>>b
assign value to left
operand

Performs Bitwise left


shift on operands and
<<= a <<= b a= a << b
assign value to left
operand

Eg:
a = 10
b = a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
6. Special operators
1. Identity Operators
In Python, is and is not are the identity operator both are used to check if two values
are located on the same part of the memory. Two variables that are equal do not
imply that they are identical.

is - True if the operands are identical


is not - True if the operands are not identical

Eg:
a = 10
b = 20
c=a
print (a is not b)
print (a is c)

2.Membership Operators

In Python, in and not in are the membership operators that are used to test whether
a value or variable is in a sequence.

in - True if value is found in the sequence


not in - True if value is not found in the sequence

Eg:
x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print ("x is NOT present in given list")
else:
print ("x is present in given list")

if (y in list):
print ("y is present in given list")
else:
print ("y is NOT present in given list")

Precedence of Operators:

Operator precedence affects how an expression is evaluated.


For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has
higher precedence than +, so it first multiplies 3*2 and then adds into 7.

Example 1:
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation

>>> (10+10) *2
40

Parentheses () overriding the precedence of the arithmetic operators.

Datatypes
Data Type represent the type of data present inside a variable.
Python contains the following inbuilt data types

1. Numeric Data types:


The data stored in memory can be of many types. For example, a student roll
number is stored as a numeric value and his or her address is stored as
alphanumeric characters.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
>>> print (24656354687654+2)
24656354687656
>>> print (20)
20
>>> type (10)
<class ‘int’>
Float:
Float, or "floating point number" is a number, positive or negative, containing
one or more decimals. Float can also be scientific numbers with an "e" to indicate
the power of 10.
>>> y=2.8
>>> y
2.8
>>> y=2.8
>>> print(type(y))
<class ‘float’>

Complex Numbers:
Complex number is represented by a complex class. It is specified as (real
part) + (imaginary part) j.

For example – 2+3j

2. Boolean:
Data with one of two built-in values True or False. Notice that 'T' and 'F' are
capital. true and false are not valid Booleans and Python will throw an error for
them. Objects of Boolean type may have one of two values, True or False:
>>> type (True)
<class ‘bool’>
>>> type (False)
<class ‘bool’>
3.Sequence Type
 String: A string value is a collection of one or more characters put in single,
double or triple quotes. A string is a group/ a sequence of characters. Since
Python has no provision for arrays, we simply use strings.

Example:
str1='This is a string in Python'
print(str1)

str2="This is a string in Python"


print(str2)

 List: The list is a mutable sequence type. A list object contains one or more
items of different data types in the square brackets [] separated by a comma.
Example:
1) list1=[1,2,3,'A','B',7,8,[10,11]]
print(list1)
Output:
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

 Tuple: Tuple is an immutable (unchangeable) collection of elements of


different data types. It is an ordered collection, so it preserves the order of
elements in which they were defined. Tuples are defined by enclosing
elements in parentheses (), separated by a comma.
Example:
1) tpl=() # empty tuple
print(tpl) #output: ()

2) employee=(1, 'Steve', True, 25, 12000) # heterogeneous


datatuple

print(employee) #output:(1, 'Steve', True, 25, 12000)


4.Set
Set is mutable, unordered collection of distinct hashable objects. The set is a Python
implementation of the set in Mathematics. A set object has suitable methods to
perform mathematical set operations like union, intersection, difference, etc. which
are separated by a comma and enclosed in curly brackets {}.
Example:
nums = {1, 2, 2, 3, 4, 4, 5, 5}
print(nums) #output: {1, 2, 3, 4, 5}

5.Dictionary

A dictionary Dict () object is an unordered collection of data in a key:value pair


form. A collection of such pairs is enclosed in curly brackets.

Example:
capitals = {"USA”: “Washington D.C", "France”: “Paris", "India”: “New Delhi"}
print(type(capitals)) #output: <class 'dict'>

Indentation

 Indentation is a very important concept of Python because without properly


indenting the Python code, you will end up seeing Indentation Error and the
code will not get compiled.
 Indentation in Python refers to the whitespaces at the start of the line to indicate
a block of code. We can create an indentation using space or tabs.
 When writing Python code, we have to define a group of statements for
functions and loops. This is done by properly indenting the statements for that
block.

Comments

 Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program. Comments enhance the
readability of the code and help the programmers to understand the code very
carefully.
 There are three types of comments in Python
 Single line Comments
 Multiline Comments
 Docstring Comments

Example:
# Print “GeeksforGeeks!” to console

print("GeeksforGeeks")

Type Conversions

The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type conversion.
There are two types of Type Conversion in Python:

1. Python Implicit Type Conversion


2. Python Explicit Type Conversion

Implicit Type Conversion in Python


In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.

Example:
x = 10

print("x is of type:",type(x))

y = 10.6
print("y is of type:",type(y))

z=x+y

print(z)
print("z is of type:",type(z))

Explicit Type Conversion in Python

In Explicit Type Conversion in Python, the data type is manually changed by the
user as per their requirement. With explicit type conversion, there is a risk of data
loss since we are forcing an expression to be changed in some specific data type.
# initializing string
s = "10010"

# printing string converting to int base 2


c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)

# printing string converting to float


e = float(s)
print ("After converting to float : ", end="")
print (e)

The type () Function and Is Operator

 The type () function is mostly used for debugging purposes. Two different types
of arguments can be passed to type () function, single and three arguments.
 If a single argument type(obj) is passed, it returns the type of the given object.
If three argument types (object, bases, dict) are passed, it returns a new type
object.

Syntax: type (object, bases, dict)

Parameters:
 object: Required. If only one parameter is specified, the type () function
returns the type of this object
 bases: tuple of classes from which the current class derives. Later
corresponds to the __bases__ attribute.
 dict: a dictionary that holds the namespaces for the class. Later
corresponds to the __dict__ attribute.

Example:

x=10
Print(type(x))
Control Flow Statements
A Conditional statement gives the developer to ability to check conditions and
change the behaviour of the program accordilly.

I. Conditional Statements
1) The if Deciosion Control Flow Statement

 The Boolean expression after the if keyword is called the condition.


 The if Statement consists of a header line that ends with the colon character
(:) followed by an indented block. Statements like this are called compound
statements because they stretch across more than one line.
 If the logical condition is true, then the block of statements get executed. If
the logical condition is false, the indented block is skipped.
2) The if…else Decision Control Flow Statement (alternative execution)
A second form of the if statement is alternative execution, in which there are
two possibilities and the condition determines which one gets executed is as
shown in flowchart below.

3)The if…elif…else Decision Control Statement (Chained Conditionals)


If there are more than two possibilities and we need more than two branches. One
way to express a computation like that is a chained conditional. elif is an
abbreviation of “else if”.
4)Nested if Statement
 The conditional statements can be nested. That is, one set of conditional
statements can be nested inside the other.
 Let us consider an example, the outer conditional statement contains two
branches.
II. Iterative Statements
If we want to execute a group of statements multiple times then we should go for
Iterative statements.
Python supports 2 types of iterative statements.
1. for loop
Python For loop is used for sequential traversal i.e. it is used for iterating over
an iterable like string, Tuple, List, set and Dictionary.
Syntax:
for var in iterable:
# statements

Example:
for i in range (0, 10, 2):
print(i)

2) While Loop
It is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop
in the program is executed.
Syntax:
while expression:
statement(s)
Example:
count = 0

while (count < 3):


count = count + 1
print ("Hello Geek")

III. Transfer Statements


1)break:
Python break is used to terminate the execution of the loop. We can use break
statement inside loops to break loop execution based on some condition.
Syntax: Loop {
Condition:
break

Example:
for i in range (10):
print(i)
if i == 2:
break

2)Continue
Python Continue Statement skips the execution of the program block after the
continue statement and forces the control to start the next iteration.
Syntax:
while True:
...
if x == 10:
continue
print(x)

Example:
for var in "Geeksforgeeks":
if var == "e":
continue
print(var)

3) Pass
pass is a keyword in Python. In our programming syntactically if block is required
which won't do anything then we can define that empty block with pass keyword.
Syntax:
pass
|- It is an empty statement
|- It is null statement
|- It won't do anything
Example:
a = 10

b = 20

if(a<b):
pass
else:
print("b<a")
Functions
Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the
function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration

Types of Function in Python

1. Built in Functions
2. User Defined Functions

1. Built in Functions:
The functions which are coming along with Python software automatically, are
called built in functions or pre-defined functions
Eg: id(), type() , input() , eval() etc..
2.User Defined Functions
The functions which are developed by programmer explicitly according to
business requirements, are called user defined functions.
Declared in four different ways
1. Without Input and Without Return Input
2. Without Input and with Return Input
3. With Input and Without Return Input
4. With Input and with Return Input

Function Definition and Calling the Function


 Python facilitates programmer to define his/her own functions.
 The Function written once can be used wherever and whenever required.
 The syntax of user-defined function would be:

 The first line in the function def fname(arg_list) is known as function header/
definition. The remaining lines constitute function body.
 The function header is terminated by a colon and the function body must be
indented.
 To come out of the function, indentation must be terminated.
 Unlike few other programming languages like C, C++ etc, there is no main ()
function or specific location where a user-defined function has to be called.
 The programmer has to invoke(call) the function wherever required.
 Simple Example of user-defined function

The Return Statement and Void Function


 A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to
the caller.
 The statements after the return statements are not executed. If the return
statement is without any expression, then the special value None is returned.
 A return statement is overall used to invoke a function so that the passed
statements can be executed.
 Syntax:

def fun ():


statements
return [expression]

Example:
def cube(x):
r=x**3
return r

Void Function
 A Function that performs some tasks, but do not return any value to the
calling function is known as void function.
 Void functions are those that do not return any value after their calculation is
complete.
 These types of functions are used when the calculations of the functions are
not needed in the actual program.
Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function
can have any number of arguments separated by a comma.
Types of function arguments
Python supports various types of arguments that can be passed at the time of the
function call. In Python, we have the following 4 types of function arguments.
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)

1. Default argument
A default argument is a parameter that assumes a default value if a value is
not provided in the function call for that argument.
Example:
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)

2. Keyword arguments (named arguments)


The idea is to allow the caller to specify the argument name with values so that
the caller does not need to remember the order of parameters.
Example:

def wish(name,msg):
print("Hello",name,msg)
wish(name="Durga",msg="Good Morning")
wish(msg="Good Morning",name="Durga")

3. Positional arguments
These are the arguments passed to function in correct positional order.

Example:
def sub(a,b):
print(a-b)
sub(100,200)
sub(200,100)

The number of arguments and position of arguments must be matched. If we change


the order then result may be changed. If we change the number of arguments then we
will get error.

4. Arbitrary arguments (variable-length arguments *args and **kwargs)


In Python Arbitrary Keyword Arguments, *args and **kwargs can pass a variable
number of arguments to a function using special symbols.

There are two special symbols:


 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example:

def myFun(*argv):
for arg in argv:
print(arg)

myFun ('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Anonymous Function

An Anonymous Function means that a function is without a name. As we


already know the def keyword is used to define the normal functions
and the lambda keyword is used to create anonymous functions.

Example:
def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

Command Line Arguments


The arguments that are given after the name of the program in the command line
shell of the operating system are known as Command Line Arguments.
String
 A String is a data structure in Python that represents a sequence of characters.
It is an immutable data type, meaning that once you have created a string, you
cannot change it.
 Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data
that can be represented as text.
 Each character is encoded in the ASCII or Unicode character. So we can say that
Python strings are also called the collection of Unicode characters.

Creating a String
Strings in Python can be created using single quotes or double quotes or even
triple quotes.

Example:
String1 = 'Welcome to the Geeks World'
String2 = "I'm a Geek"
String3 = '''I'm a Geek and I live in a world of "Geeks"'''
print (String1)
print (String2)
print (String3)

Accessing Character in a String


We can access characters of a string by using the following ways.

1. By using index
Each individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the
back of the String.
While accessing an index out of the range will cause an Index Error. Only Integers
are allowed to be passed as an index, float or other types that will cause a Type Error.
Example 1:

str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[6])

Example 2:
str=” HELLO”
for i in range (0, len(str)):
print(str[i], end=’ ‘)

2. String Slicing
 A segment of a string is called a slice. Selecting a slice is similar to selecting a
character:
 Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes
starting at 0 in the beginning of the string and working their way from -1 at the
end.
 Slice out substrings, sub lists, sub-Tuples using index.
 Syntax: [Start: stop: steps]
 Slicing will start from index and will go up to stop in step of steps.
 Default value of start is 0.
 Stop is last index of list
 And for step default is 1

Example:
1− str = 'Hello World!'
print str # Prints complete string print
str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
Example 2:
>>> x='computer'
>>> x[1:4]
'omp'
>>> x[1:6:2]
'opt'
>>> x[3:]
'puter'
>>> x[:5]
'compu'
>>> x[-1]
'r'
>>> x[-3:]
'ter'
>>> x[:-2]
'comput'
>>> x[::-2]
'rtpo'
>>> x[::-1]
'retupmoc'

Immutability:
It is tempting to use the [] operator on the left side of an assignment, with the intention
of changing a character in a string.
For example:
>>> greeting='gfgc college!'
>>> greeting [0]='n'
TypeError: 'str' object does not support item assignment
String Methods

Example:
capitalize () It converts the initial letter of the str1=” hello”
string to uppercase. str2=str1.capitalize()
Syntax: print(str2)
String.capitalize() Output
Hello

Converts the first character of every Example:


title () word to uppercase and the other Str1=” hello”
characters to lowercase. Str2=str1.title()
Syntax: Print(str2)
String.title() Output
HELLO

Provides the smallest index where Example:


find () the specified substring is located, if str1=” I like Python”
present. position=str1.find(“like”)
Syntax: print(position)
String.find(substring) output
2

Formats the string into a nicer Example:


format () output. str1=” python”
print(“Hello{}.”.format(str1)}
Output
Hello python
Counts occurrences of a substring Example:
count () in the string. str1=” python”
Syntax: n=str1.count(“py”)
String.count(substring) print(n)
output
1

Substitutes instances of one Example:


replace () substring with a different one. str1=” I love python”
Syntax: str2=str1.replace(“love”,”like”)
String.replace(oldstring,newstring) print(str2)
output
I like python
Splits the string at the separator. Example:
split () Syntax: str=” Bangalore Karnataka”
String.split(separator) print(str.split())
output
[‘Bangalore, ’Karnataka’]

lower () Converts all characters in the string Example:


to lowercase. This method is widely str=”Hi Python”
used in case-insensitive print(str.lower())
comparisons. output
Syntax: hi python
String.lower()
Example:
upper () Transforms all characters to str=”hi python”
uppercase. It's commonly used for print(str.upper())
emphasizing certain texts or for output
uniform data entry. HI PYTHON
Syntax:
String.upper()

It returns a string by joining all the Example:


join () Elements of an iterable. str=”1234”
Syntax: print(str.join(“BCA”))
String.join(group of string) output
B1234C1234A
Checks if all characters are Example:
isalpha () alphabetic. string="nikhil"
Syntax: string.isalpha()
String.isalpha() Output
True
isdigit() returns true if string Example:
isdigit() contains only digits and false string="123456789"
otherwise. string.isdigit()
Syntax: Output
String.isdigit() True
isspace() isspace() returns true if string Example:
contains only whitespace characters string=" "
and false otherwise. string.isspace()
Syntax: Output
String.isspace() True
converts lowercase letters in a string Example:
swapcase() to uppercase and viceversa string="HELLO"
Syntax: string.swapcase()
String.find(„string‟) Output
'hello'
Determines if string or a substring Example:
startswith() of string. string="Nikhil Is Learning"
Syntax: string.startswith('N')
String.startswith(„string‟) output
True
Determines if string or a substring Example:
endswith() of string (if starting index beg and string="Nikhil Is Learning"
ending index end are given) ends string.startswith('g')
with substring str; returns true if so output
and false otherwise. True
Syntax:
String.endswith(„string‟)
It returns the index position of the Example:
index () first occurrence of the substring str=” python”
from the main string. position = str1.index(“y”)
print(position)
output
1

You might also like