Unit 1 Python notes
Unit 1 Python notes
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
Source Code
Executable files
Compiler
(with extensions .exe,.dll)
Interpreter Compiler
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:
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.
- 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.
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
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.
# display
print (Number)
Types of 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.
Keywords Description
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
Subtraction: subtracts
– x–y
two operands
Multiplication:
* x*y
multiplies two operands
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.
a = True
b = False
print (a and b)
print (a or b)
print (not a)
4. Bitwise operators
| Bitwise OR x|y
~ Bitwise NOT ~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
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
Performs Bitwise OR on
|= operands and assign a|=b a=a|b
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.
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.
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:
Example 1:
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation
>>> (10+10) *2
40
Datatypes
Data Type represent the type of data present inside a variable.
Python contains the following inbuilt data types
Complex Numbers:
Complex number is represented by a complex class. It is specified as (real
part) + (imaginary part) j.
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)
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]]
5.Dictionary
Example:
capitals = {"USA”: “Washington D.C", "France”: “Paris", "India”: “New Delhi"}
print(type(capitals)) #output: <class 'dict'>
Indentation
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:
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))
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"
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.
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
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
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
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
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
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)
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)
def myFun(*argv):
for arg in argv:
print(arg)
Anonymous Function
Example:
def cube(x): return x*x*x
print(cube(7))
print(cube_v2(7))
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)
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