You are on page 1of 39

REVIEW OF PYTHON

BASICS
.

KEYWORDS AND IDENTIFIERS


• Keywords are reserved words .Example. for, while , int, break
• Identifiers : user defined names for any variable or function .
• Rules for writing identifiers :-
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.

 2. Names like myClass, var_1 and print_this_to_screen, all are valid example. An identifier cannot start with a digit. 1variable is Invalid,
but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
>>> global = 1
File "<interactive input>", line 1
global = 1
^
SyntaxError: invalid syntax
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
>>> a@ = 0
File "<interactive input>", line 1
a@ = 0
^
SyntaxError: invalid syntax
5. Identifier can be of any length
• NOTE: python is a case sensitive lang. so variable and Variable are two different things.
Built-in Data Types

Text Type: str


Numeric int, float, complex
Types:
Sequence list, tuple, range
Types:
Mapping dict
Type:
Set Types: set
Boolean bool
Type:
Binary Types: bytes
Mutable vs Immutable Objects in Python

• Every variable in python holds an instance of an object. There are two


types of objects in python i.e. Mutable and Immutable objects.
Whenever an object is instantiated, it is assigned a unique object id.
The type of the object is defined at the runtime and it can’t be
changed afterwards. However, it’s state can be changed if it is a
mutable object.
• mutable objects can change their state or contents and immutable
objects can’t change their state or content.
• Immutable Objects : These are of in-built types like int, float, bool,
string, unicode, tuple. In simple words, an immutable object can’t be
changed after it is created.
• Mutable Objects : These are of type list, dict, set .
• Getting the Data Type :- type()
type(variable)
• Setting the Data Type :- assigning value or using class of that datatype as:
variable = classname(value)
Ex. x = complex(1j) Var= list(‘1234’)
Literals

• A literal is a easily visible way to write a value.


• Python support the following literals:
• String literals   ::   "halo" , '12345'
• Int literals   ::   0,1,2,-1,-2
• Long literals   ::   89675L
• Float literals   ::   3.14
• Complex literals   ::   12j
• Boolean literals   ::   True or False
• Special literals   ::   None
• Unicode literals   ::   u"hello"
• List literals   ::   [], [5,6,7]
• Tuple literals   ::   (), (9,),(8,9,0)
• Dict literals   ::   {}, {'x':1}
• Set literals   ::   {8,9,10}
Type Conversion:
• 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.
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion:
• In Implicit type conversion, Python automatically converts one data type
to another data type. This process doesn't need any user involvement.
• Let's see an example where Python promotes conversion of lower
datatype (integer) to higher data type (float) to avoid data loss.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
OUTPUT:
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
Value of num_new: 124.23
datatype of num_new: <class 'float'>
Explicit Type Conversion:

• IExplicit Type Conversion, users convert the data type of an object to


required data type. We use the predefined functions like int(), float(),
str(), etc to perform explicit type conversion.

• This type conversion is also called typecasting because the user casts
(change) the data type of the objects
• Syntax :
(required_datatype)(expression)
Addition of string and integer using explicit conversion:
num_int = 123
num_str = "456“
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
OUTPUT:
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>
Dynamic typing
• Why python is a dynamically typed language.
Python is a dynamically typed language. It doesn’t know about the type
of the variable until the code is run. So declaration is of no use. What it
does is, It stores that value at some memory location and then binds
that variable name to that memory container. And makes the contents
of the container accessible through that variable name. So the data type
does not matter. As it will get to know the type of the value at run-time.
Creating a String
• Strings in Python can be created using single quotes or double quotes
or even triple quotes
• Built in functions related to string :
text = "program is fun“
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))
O/P
0program is fun
000000program is fun
program is fun
Method Description

Python String capitalize() Converts first character to Capital Letter

Python String count() returns occurrences of substring in string

Python String endswith() Checks if String Ends with the Specified Suffix

Python String find() Returns the index of first occurrence of substring

Python String format() formats string into nicer output

Python String index() Returns Index of Substring

Python String isalnum() Checks Alphanumeric Character

Python String isalpha() Checks if All Characters are Alphabets

Python String isdecimal() Checks Decimal Characters

Python String isdigit() Checks Digit Characters

Python String islower() Checks if all Alphabets in a String are Lowercase

Python String isnumeric() Checks Numeric Characters


Python String isspace() Checks Whitespace Characters

Python String isupper() returns if all characters are uppercase characters

Python String join() Returns a Concatenated String

Python String lower() returns lowercased string

Python String upper() returns uppercased string

Python String swapcase() swap uppercase characters to lowercase; vice versa

Python String lstrip() Removes Leading Characters

Python String rstrip() Removes Trailing Characters

Python String strip() Removes Both Leading and Trailing Characters

Python String replace() Replaces Substring Inside

Python String split() Splits String from Left

Python String startswith() Checks if String Starts with the Specified String

Python String zfill() Returns a Copy of The String Padded With Zeros
List = [1,2,3]
li=list([23,45]) Method Description

li=list(“hello”) append() Adds an element at the


end of the list

li=list((1,2,3,4) clear() Removes all the elements


from the list
li=list({'A':'one','B':'two'}) copy() Returns a copy of the list
count() Returns the number of
elements with the specified
value
extend() Add the elements of a list
(or any iterable), to the end
of the current list

index() Returns the index of the


first element with the
specified value
insert() Adds an element at the
specified position

pop() Removes the element at


the specified position

remove() Removes the first item with


the specified value

reverse() Reverses the order of the


list
sort() Sorts the list
l=list(12345)
What is problem in the above python code.

Traceback (most recent call last):


File "<pyshell#2>", line 1, in <module>
l=list(12345)
TypeError: 'int' object is not iterable
tup = (1,2,3)
tup=(1,) print(type(tup))
tup=(12) print(type(tup))
li=tuple([23,45])
li=tuple(“hello”)
li=tuple({'A':'one','B':'two'})
Python includes the following tuple functions −
Sr. Function with Description
N
o.
1 len(tuple)Gives the total length of the tuple.
2 max(tuple)Returns item from the tuple with max value.
3 min(tuple)Returns item from the tuple with min value.
4 tuple(seq)Converts a list into tuple.
5 Index(element) returns index of passed element
Dictionary
Method Description
x = ('key1', 'key2', 'key3')
clear() Removes all the elements from the
dictionary y = 0
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified thisdict = dict.fromkeys(x, y)
keys and values
get() Returns the value of the specified key print(thisdict)
items() Returns a list containing a tuple for each
key value pair
keys() Returns a list containing the dictionary's
keys OUTPUT:-
pop() Removes the element with the specified C:\Users\My Name>python
key demo_dictionary_fromkeys.py
popitem() Removes the last inserted key-value pair ['key1': 0, 'key2': 0, 'key3': 0]

update() Updates the dictionary with the specified


key-value pairs
values() Returns a list of all the values in the
dictionary
Dictionary creation
# empty dictionary
Dict = {}
# interger keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}

# with dict() method


Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})

# with each item as a Pair


Dict = dict([(1, 'Geeks'), (2, 'For')])

# dictionary using zip function


name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]

# using zip() to map values


mapped = dict(zip(name, roll_no))
print(mapped)
There is one more scope of variable:
FIND O/P

def myfun(*name):
print('Hello', name)
myfun('my', 'school')

O/P:
Hello ('my', 'school')
FIND O/P:
x = 150
def myfunc():
global x
print('x is', x)
x = x*2
print('Changed global x to', x)
myfunc()
print('Value of x is', x)
x is 150
Changed global x to 300
Value of x is 300
O/P:
def a(n):
if n==0:
return 0
elif n==1:
return 1
else:
return a(n-1)+a(n-2)
for i in range(0,6):
print(a(i),end=" ")
011235

You might also like