WeRCopyPasteDeveloper
Wednesday, January 22, 2020
Saturday, November 16, 2019
type() functions
type() functions
Syntax:
type(object)
Syntax:
type(name, bases, dict)
_name_ : Class name.
_bases_ : A possibly empty tuple containing the bases classes.
_dict_ : Dictionary containing the class’s namespace.
Multiple Assignment
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
a=b=c=5
print(a)
print(b)
print(c)
Output:
5
5
5
Python Literals
Python Literals
- A literals is a function for representing a fixed value.
- Python support two types of literals.
1. Numeric Literals.
2. Non-Numeric Literals.
1. Numeric Literals.
a. Integer Literals
>>> x=100
>>> print("Numeric literal is: ",x)
Numeric literal is: 100
b. Floating point Literals
>>> y=100.23
>>> print("Numeric Float literal is: ",y)
Numeric Float literal is: 100.23
c. List
d. Complex
>>> z=complex(1,2)
>>> print("Numeric Complex literal is: ",z)
Numeric Complex literal is: (1+2j)
2. Non-Numeric Literals.
a. String Literals
>>> Mystr="wercopypastedeveloper.blogspot.com"
>>> print("String literal is: ",Mystr)
String literal is: wercopypastedeveloper.blogspot.com
b. Escape Sequence.
3. Boolean literals.
a. True.
>>> a=True
>>> print("Boolean literal is: ",a)
Boolean literal is: True
b. False.
>>> a=False
>>> print("Boolean literal is: ",a)
Boolean literal is: False
4. Special literals.
In Python is same as “null”, means, non-existent not known or empty.
5. Literal Collections.
a. Tuples.
b. Lists
c. Sets
d. Dictionaries
>>> b=[1,2,3,4]
>>> print("List literal is: ",b)
List literal is: [1, 2, 3, 4]
>>> c=(1,2,3,4)
>>> print("Tuple literal is: ",c)
Tuple literal is: (1, 2, 3, 4)
>>> d={1,2,2,2,3,4}
>>> print( literal is: ",c)
>>> print(" literal is: ",d)
literal is: {1, 2, 3, 4}
>>> e={1:"ONE",2:"TWO"}
>>> print("Dict literal is: ",e)
Dict literal is: {1: 'ONE', 2: 'TWO'}
Example:
>>> x=100
>>> print("Numeric literal is: ",x)
Numeric literal is: 100
>>> y=100.23
>>> print("Numeric Float literal is: ",y)
Numeric Float literal is: 100.23
>>> z=complex(1,2)
>>> print("Numeric Complex literal is: ",z)
Numeric Complex literal is: (1+2j)
>>> Mystr="wercopypastedeveloper.blogspot.com"
>>> print("String literal is: ",Mystr)
String literal is: wercopypastedeveloper.blogspot.com
>>> a=True
>>> print("Boolean literal is: ",a)
Boolean literal is: True
>>> b=[1,2,3,4]
>>> print("List literal is: ",b)
List literal is: [1, 2, 3, 4]
>>> c=(1,2,3,4)
>>> print("Tuple literal is: ",c)
Tuple literal is: (1, 2, 3, 4)
>>> d={1,2,2,2,3,4}
>>> print(" literal is: ",d)
literal is: {1, 2, 3, 4}
>>> e={1:"ONE",2:"TWO"}
>>> print("Dict literal is: ",e)
Dict literal is: {1: 'ONE', 2: 'TWO'}
Python Identifiers
Python Identifiers
- Identifier is the name given to entities like classes, functions, variables, etc. in Python. It helps differentiating one entity from another.
- Rules for writing identifiers.
- Identifiers can be a combination of later in lowercase ( a to z ) or uppercase (A to Z) or underscore(_).
- Names like myClass, var_1 & print_this_to_screen; all are valid example.
- An identifier cannot start with a digit, 1 variable is invalid but variable is valid.
- Keywords cannot be used as identifiers.
Python Keywords
Python Keywords
- Keywords are reserved word whose meaning is reserved by Python translator.
- Keywords cannot used as user defined words.
- Each keyword is a predefined instruction or command.
- Keywords are case sensitive.
- Up to Python 3.3 version support 33 keywords.
True, False è Boolean values.
Null è reference value.
Keywords in Python programming languages:
False
|
class
|
finally
|
return
|
None
|
continue
|
for
|
lambda
|
True
|
Def
|
from
|
nonlocal
|
while
|
And
|
del
|
global
|
not
|
With
|
as
|
elif
|
if
|
Or
|
yield
|
assert
|
else
|
Import
|
pass
|
brcale
|
except
|
in
|
raise
|
|
Keyword related to function
def
lambda
return
yiald
Keyword belongs control statement
if
else
break
continue
while
for
Keywords belongs exception handling
finally
try
except
assest
raise
Keywords belongs Values
True
False
None
Keywords belongs to operator
from
is
in
or
and
as
del
UDT(user defined datatype)
Class
String Operations
String Operations
In general, you can’t perform mathematical operations on strings, even if the strings look like numbers.
The + operator performs strings concatenation, which means it joins the strings by linking them end-to-end.
Example:
>>> first="First"
>>> second="Second"
>>> fullstr=first+""+second
>>> print(fullstr)
FirstSecond
>>> print('Spam'*3)
SpamSpamSpam
>>> print("M"*5)
MMMMM
What is String ?
- String is collection of characters, these characters can be alphabets(a-z, A-Z), digits(0-9) and special characters.
- String allows characters available in other languages.
- Python allows to represent string in two formats.
1. Ascii – This string allows only alphabets of English.
2. Unicode – This string allows characters form other languages.
Datatypes:
1. Standard Datatypes:
int
float
complex
boolean
2. Sequence Datatypes:
str
list
tuple
set
- String is a sequence datatypes.
- str is class name, which is used in python to create string objects.
* Special characters in Strings:
In python the backslash(\) character is used to introduce a special character.
Escape Sequence Meaning
\n Newline
\t Horizontal Tab
\\ Backslash
\’ Single Quote
\” Double Quote
Example:
>>> print("This is Back Slash(\\)Mark")
This is Back Slash(\)Mark
>>> print("This is Back Slash \t Mark.")
This is Back Slash Mark.
>>> print("This is Back Slash\n Mark.")
This is Back Slash
Mark.
>>> print("This is Back Slash \' Single Quatrs \' Marks")
This is Back Slash ' Single Quatrs ' Marks
>>> print("This is \\ slash")
This is \ slash
Define String Slicing?
To cut a substring from a string is called string slicing.
Slicing is a process of dividing a sequence into sub-sequence.
String slicing is dividing string into substring.
Slicing is done in two ways :
1. Using Slice Operator.
2. Using Slice Method.
1. Slice Operator :
Syntax:
[start:stop:step]
[start:]
[:stop]
[::]
Start: starting index and default is 0.
Stop: ending index and default is length.
Step: Incremental or decremental value and default is +1.
Example:
>>> s='PYTHON'
>>> s[:]
'PYTHON'
>>> s[:3]
'PYT'
>>> s[::]
'PYTHON'
>>> s[::3]
'PH'
>>> s[:3]
'PYT'
>>> s[4::]
'ON'
>>> s[3::]
'HON'
>>> s[-1:-6]
''
>>> s[-1:-6:-1]
'NOHTY'
>>> s[-1::-1]
'NOHTYP'
>>> s[-1::1]
'N'
>>> s[-6:-1]
'PYTHO'
>>> s[-6]
'P'
>>> s[0:100]
'PYTHON'
>>> s[0:7]
'PYTHON'
>>> s[9:10]
''
>>> s1=s[-100:-1]
>>> print(s1)
PYTHO
* String Indices or Indexing:
String are arrays of characters and elements of an array can be accessed using indexing. Indices start with 0 from left side and -1 when from right side.
Here two indices are used separated by a colon (:). A slice 3:7 means indices characters of 3rd,4th,5th and 6th positions. The second integer index i.e. 7 is not included. You can use negative indices for slicing.
Each character inside string is identified with unique integer number, which is called index.
Index number can be +ve & -ve.
Positive index is given from 0 to length -1 it allows to read characters from to right.
Negative index is given from -1 to length, it allows to read characters from right to left.
Index allows to read characters from string in seq order or random order.
Each character read from string is again string type.
string_name[index]
If index is invalid, python runtime gives Index_Error.
Example:
s=”PYTHON”
s
P Y T H O N
Example:
>>> str="Naresh i Technologies"
>>> print(str[0])
N
>>> print(str[-1])
s
>>> print(str[1:4])
are
>>> print(str[:4])
Nare
* How to create string objects?
- Python allows to create string object in two ways.
1. Implicit Creation.
2. Explicit Creation.
1. Implicit Creation:
- This objects is created by python runtime.
- Anything in python represent within
1. ‘ ’
2. “ ”
3. “’ ‘”
is an instance of str class.
- “’ ‘” allows to represent string in multiple line.
Note :
String is immutable(do not changes) after creating string object. We connot do any changes.
Type Conversion or Type Casting
Type Conversion or Type Casting
Function and Description :
int(x[,base])
Converts x to an integer, base specifies the base if x is a string.
float(x)
Converts x to a floating-point number.
str(x)
Converts object x to a string representation.
list(s)
Converts s to list.
tuple(s)
Convert s to a tuple.
set(s)
Convert s to a set.
dict(d)
Creates a dictionary. D must be a sequence of (key, value) tuple.
ord(x)
Converts a single character to its Integer value.
hex(x)
Coverts an integer to hexadecimal string.
oct(x)
Converts an integer to an octal string.
complex(real)
Creates a complex number.
int(a,base): The function converts any data type to integer. ‘Base’ specifies the base in which string is if data type is string.
Example:
>>> print(int('2014'))
2014
>>> x='2014'
>>> print(type(x),x)
<class 'str'> 2014
>>> x=int(x)
>>> print(type(x),x)
<class 'int'> 2014
>>> print("1001",2)
1001 2
>>> print(int("1001",2))
9
>>> print(int(3.14055))
3
Type float(x) to convert x to a floating-point number.
Example:
>>> print(float('1.90'))
1.9
>>> print(float(5))
5.0
str() : Used to convert integer into a string.
Example :
>>> print(str(3.1455))
3.1455
>>> print(str([1,2,3,4]))
[1, 2, 3, 4]
list() : This function is used to convert any data type to a list type.
Example:
>>> print(list('Mary'))
['M', 'a', 'r', 'y']
>>> print(list((1,2,3,4)))
[1, 2, 3, 4]
>>> print(list((1,2,3,4)))
[1, 2, 3, 4]
>>> s="wercopypastedeveloper.blogspot.com"
>>> print(list(s))
['w', 'e', 'r', 'c', 'o', 'p', 'y', 'p', 'a', 's', 't', 'e', 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r', '.', 'b', 'l', 'o', 'g', 's', 'p', 'o', 't', '.', 'c', 'o', 'm']
tuple() : This function is used to convert to a tuple.
Example:
>>> print(tuple('Mary'))
('M', 'a', 'r', 'y')
>>> print(tuple([1,2,3,4]))
(1, 2, 3, 4)
>>> p="Python"
>>> print(tuple(p))
('P', 'y', 't', 'h', 'o', 'n')
set() : This function returns the type after converting to set.
Example:
>>> print(set('Mary'))
{'a', 'r', 'y', 'M'}
>>> print(set([1,2,3,4]))
{1, 2, 3, 4}
>>> s='Python'
>>> print(set(s))
{'n', 'P', 'y', 'o', 't', 'h'}
dict() : This function is used to convert a tuple of order (key, value) into a dictionary.
Example:
>>> print(dict(tup))
{'a': 1, 'b': 2, 'c': 3}
ord() : This function is used to convert a character to integer.
Example:
>>> a='A'
>>> print(ord(a))
65
>>> print(ord('Z'))
90
>>> print(ord('a'))
97
hex(): This function is to convert integer to hexadecimal string.
Example:
>>> c=hex(19)
>>> print(c)
0x13
>>> print(hex(1))
0x1
>>> print(hex(9))
0x9
oct() : This function is to convert integer to octal string.
Example:
>>> print(oct(1))
0o1
>>> print(oct(9))
0o11
>>>
complex(real,imag) : This function converts real numbers to complex(real, imag) number.
Example:
>>> c=complex(1,2)
>>> print(c)
(1+2j)
>>> print(complex(5,10))
(5+10j)
Swap Variable
Swap Variable
Syntax:
var1,var2=var2,var1
Example:
>>> a=10
>>> b=20
>>> print(a)
10
>>> print(b)
20
>>> a,b=b,a
>>> print(a)
20
>>> print(b)
10
Order of Operations
Order of Operations
When an expression contains more then one operator, the order of evaluation depends on the order of operations. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way.
PEMDAS
Parentheses Exponentiation Multiplication Division Addition Subtraction.
Parentheses :
>>> 3*(3-2)
3
>>> 3*(3-1)
6
Exponentiation :
>>> 1+2**3
9
>>> 1+2*3
7
>>> 2*6/2
6.0
Multiplication Division Addition Subtraction :
>>> 1+2*3
7
>>> 2*6/2
6.0
>>> 2*3-1
5
>>> 6+4/2
8.0
>>> 5-1+2*5*4/2
24.0
Operators and Operands
Operators and Operands
Operators are special symbols that represent computations like addition and multiplication. The values the operator is applied to are called operands.
Subscribe to:
Posts (Atom)
-
Operators and Operands Operators are special symbols that represent computations like addition and multiplication. The values the ope...
-
Clear screen inside python There is no Python Command for IDLE in Windows, to do clear the interactive screen. We can perform us...