Python Basics-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

1. Python was developed by Guido van Rossum and released in 1991.

Python is an
interpreter based scripting language, which can be used:
● To create web based application
● To connect to the database systems and to read and modify files.
● To handle big data and perform complex mathematics.
● For rapid application development.

2. Python stands out as the present generation Programming language because of


the following reasons:
● It works on multiple platforms (Windows, Mac, Linux, Raspberry Pi etc)
● It has a simple syntax that allows developers to write robust programs
easily and efficiently.
● It can be used to write procedural and object oriented codes.

3. Python codes can be executed in:


● Interactive mode (Shell) using the Python IDLE (Integrated Development
and Learning Environment) for executing single line Python commands.
● Scripting mode (Editor) to write a program and execute its statements
line by line and get the result in the Python shell.

4. Some of the Sample commands, which can be tried on Python prompt


(Interactive mode)
>>> “Hello”
'Hello'
>>>'Hello'
'Hello'
>>>1+2
3
>>>1+2*3
7
>>>print(“Hello”)
Hello
>>>0o10 #ttt
8
>>>0b111
7
>>>0xF //Hexadecimal ->0-9, A,B,C,D,E,F
15
[Note that Strings/Character constant can appear within single/double/triple
single quotes or triple double quotes.
Triple double quotes or triple single quotes are used for supporting multiple
lines:
>>>print('''Hello
world''')
Hello
world
>>> print("""'Hello
world"""')
Hello
world
You can have multi line expressions also:
[ttt]
>>> 20 + 30 \
+ 50
100
[Note the use of \ which indicates the continuation]
>>> print("hello"\
)
hello

5. For Script mode:


● click on File and then click on new
● Write statement(s) to execute
● Save the code (Ctr+S or Click on File>Save); The extension should be
py.If you don’t specify it is taken as by default.
● Execute the code by pressing function key F5. Alternatively click on
Run>Run Module.

6. For quit python IDLE, simply type the following command on the Python shell
prompt:
quit()
Or
exit()

7. Python recognizes all characters in the ASCII character set as well as the
UNICODE characters.

8. Tokens:
A Token is the smallest unit in a program that makes a program. It is
categorized into 5 parts:
● Identifier
● Keywords
● Delimiters/Punctuators
● Literals/Constants
● Operators

9. Identifier
A. It is a name given to a particular Python object (e.g: variable, function,
module etc) in order to identify it.
B. Rules to be followed while giving an identifier name:
a. It consists of three types of characters:
i. Alphabets (A-Z / a-z)
ii. Digits (0-9)
iii. Underscore(_)
b. It should either start with an alphabet or an underscore.
c. It should not be a keyword
[Note : Python is case sensitive, so the identifiers should be referred in the
same case in which it is specified.]
● Examples of valid Identifiers : Sum, _Sum1, Total_number etc

[Suggestion: Try to give names, starting with uppercase except True, False and
None]

10. Keyword
● A keyword is a reserved word that is pre-defined in the python library
for a particular purpose. [Note that you cannot change its purpose]
● In python, you can get the list of keywords by importing the module
keyword.
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield']

[Note : All the keywords are in lower cases except True, False and None which
starts with upper case]

● You should not confuse yourself between keywords and builtin-


functions. A built-in function can be used directly and unlike keywords,
the purpose of these functions can be changed e.g. An identifier name
can be ‘print’ but in that case the meaning of print will be changed. So
it is not suggested to name any identifier with the same name as that
of a builtin.
● Some of the examples of builtin functions:
['abs()', 'bin()', 'bool()', 'chr()', 'dict()', 'float()', 'hex()', 'id()', 'input()',
'int()', 'len()', 'list()', 'max()', 'min()', 'oct()', 'open()', 'ord()', 'pow()',
'print()', 'range()', 'round()', 'set()', 'slice()', 'sorted()', 'str()', 'sum()',
'super()', 'tuple()', 'type()']
[T T T
dir(__builtins__) #>>>dir (double underscore followed by the word builtins and
then double underscore ]

11. Delimiters
It includes Grouping, punctuation, and binding symbols. The following is the
list of characters used as Delimiters:
Brackets [ ]
Parenthesis ( ),
Braces { }
Semicolon ;
Colon :
Single quotes '
Double quotes "
Pound Sign #
Triple single quotes ' ' '
Triple double quotes,
Braces { }
Comma quotes " " "

12 Literals
Literals in Python are raw data which are processed using Python statements.
In python, we have three types of literals:
● Numeric Literals
○ Integers
E.g: 23, 0b1001 (binary), 0o17(octal),0x1a(hexadecimal)
[Note: 'zero b' -> (for binary) 0b or 0B both will work. Same goes
for octal and hexadecimal i.e 0o or 0O / 0x or 0X
○ Float Literal
E.g; 15.5, 2.5e3 (It means 2.5 X 103 i.e. 2500.0)
○ Complex Literal
z=3.14j (over here the Real part will be 0 and the imaginary part
will be 3.14. You can see this result by typing z.real and z.imag)
● String Literals
○ A string is a set of characters.
○ As discussed in point IV a string literal can appear within
single/double/triple quotes.
● Boolean Literal
○ A boolean literal in Python can have two values : True or False
Note: True and False are the keywords, which start with an
upper case alphabet.
○ E.g:
>>> a=(5>4)
>>> a
True
>>> type(a)
<class 'bool'>
[Note: type is a built-in function which returns the data type of
the parameter

E.g:
>>> a=10
>>> b=1.5
>>> c="hello"
>>> d=1.5j
>>> e=(3>4)
>>> type(a)
<class 'int'>
>>> type(b)
<class 'float'>
>>> type(c)
<class 'str'>
>>> type(d)
<class 'complex'>
>>> type(e)
<class 'bool'>
]

13. Operators
● An operator is a tool that performs an operation on the basis of
operands passed to it.
● Python divides the operators into following categories:
○ Arithmetic operators
○ Assignment operators
○ Relational operators
○ Logical operators
○ Identity operators (is/is not)
○ Membership operators (in/ not in)
○ Bitwise operators (|, &, <<, >>, ^ and ~)
[Note : Last three operators will be covered later]

14. Arithmetic Operators : These are used to perform arithmetic operations on


the basis of operands passed to it. These operators are : (as per their
precedence)

Operators Name Precedence

** Exponent 1
*,/,//,% Multiplication, Division, Floor 2 (All these operators are
Division and Modulo having Same Precedence)

+,- Addition and Subtraction 3(Addition and Subtraction


are having equal Precedence)

Examples : [TTT]
>>>2**3
8
>>>5//2
2
>>>5/2
2.5
>>>15%4
3
>>>a=10
>>>b=3
>>>a-b
7
>>>-15%2
1

>>>15%-2
-1
>>>-15%-2
-1
>>>2**3**2
512
>>>-15%7%20
(OPERATION WILL BE Left to Right)
6
[Note : Remainder = Numerator - (Numerator//Denominator)* Denominator]

15. Assignment Operators: It is used to assign a Constant/Value/Expression to a


variable
Syntax:
<Object identifier> = <C/V/E>
Note that the Right value goes to the variable, which is the Left operand of
the assignment operator.
>>>a=10
>>>a
10
>>>b=a+10
>>>b
20
>>>c=b
>>>c
20

~ Assigning multiple values to multiple variables:


Multiple variables can be assigned values using a single python assignment
operator:
a, b, c = 10, 10.5, "Hello World"
Note that in a single statement variable a, b and c are initialized via three
different types of values.

~ Assigning same value to multiple variables

Multiple variables can be assigned a single value:


a = b = c = 20
Note that a, b and c will get a value 20

~Shorthand Notation

Operator Example and meaning

**= >>> a=2


>>> a**=5 #It implies a= a ** 5
>>> a
32

/= a /= 2 # It implies a= a / 2

*= a *= 2 #It implies a=a * 2

//= a //= 2 # a = a // 2

%= a %= 2 # a = a % 2

-= a -= 2 #a = a - 2
+= a + =2 # a = a + 2
Example: [TTT] [Use Interactive mode]
1) What will be the value of a?
a=2
b=10
a *= b + 20 #it implies a=a*(b+20)
60
2)
>>>a=10
>>>b=20
>>>a, b = b, a
>>>a
20
>>>b
10
16. Relational Operators:
● These operators are used to compare two values, which are passed as an
operand to it.
● The result of the relational expression is always a boolean (i.e. True or
False)
● The precedence of == and != is lesser than the precedence of remaining
relational operators .
● The precedence of relational operator is less than Arithmetic operators
● These operators are:
● Note Python also supports multiple use of relational operators
[e.g: the value a should fall in the range 20-30 can be written as:
20<=a<=30
Note: Only for the VIVA VOCE]

Operator Meaning Example

== Equals to >>>a=5
(Note : >>>b=6
'=' >>>a == b
symbol False
has been >>>10==10
written True
twice)

!= Not equal to >>>a=5


>>>b=6
>>>a != b
True

> Greater than >>>a=5


>>>b=6
>>>a > b
False

< Less than >>>a=5


>>>b=6
>>>a < b
True

>= Greater than or >>>a=5


equal to >>>b=6
>>>a >= b
False

<= Lesser than or >>>a=5


equal to >>>b=6
>>>a <= b
True

17. Logical Operators : They are used to either negate or combine Relational
expressions and like relational expression the result is either True or False.
These operators are (As per their Precedence)

Operator Meaning Example

not Negates or reverses the >>>a=10


result of an expression, >>>not(a>=10)
which is passed as an False
operand.

and Join two conditional >>>a=10


statements and return >>>a>=10 and a<=20
true if both the True
statements are true

or Join two conditional >>>a=10


statements and return >>>a==10 or a==20
true if any of the True
statement is true
18. Python Comments
There are two ways to comment:

A comment is that part of a program, which is ignored during program


compilation and, therefore has no effect on the actual output of the code.
A comment starts with a hash symbol(#),and extends till the end of the line.
Eg.
#this is a single line comment
x=10
y=x+100 # value of x+100 is assigned to the variable y
print(y)
● Comments are useful as they make the code more readable
And understandable.
● They are not necessary in a script,but are highly recommended if the
Code is too complex or has to be viewed by multiple people.

1. Using doc string


A doc string is a string which is specified between triple single quotes or triple
double quotes.

19. Escape Sequence


~An Escape sequence is a sequence of two characters where the first
character is \.
~The meaning of the character that appears after backslash is escaped.
Eg.
i. To print ‘\’
print(“\\”)
ii. To print d:\python
print(“d:\\python”)
iii.To print a message “welcome”, where “” is part of the output
print("\"welcome\"")
or
print(‘"welcome"’)

Some of the popular escape sequences :


\t : tab
\n : new line
20. Inbuilt Function print()

1. Python built in functions are defined as functions whose functionality


is pre-defined.
2. print() is a built in function which displays a particular object on the
screen ,which is passed as a parameter to it.
3. The parameter can be a variable,constant or an expression.
4. eg.
>>>print(‘hello’)
hello
There are two more parameter with print()
1. sep(it has a default value space):It is activated when there are
more than one objects to be printed. You can change the default
value by using the parameter sep.
Eg.
a,b,c=10,20,30
print(a,b,c,)
2. end(default value \n):The character associated with \n is printed
after the print command is executed.(you must have noticed
after print command ,the curser appears in a new line.)
a,b,c=10,20,30
print(a,b,c)
print(a,b,c,sep='#')
print(a,b,c,)
print('The end')
10 20 30
10#20#30
10 20 30
The end
● Python is a case sensitive language, hence print() and Print()
are different.
● print() is in lowercase.
● print() function gives no value.
Eg.

>>>a=print(‘hello’)
>>>print(a)
hello
None
21 Inbuilt Function input()

1. An inbuilt function, which is used to accept data from the user.


2. Whatever data is entered by the user is thrown as String. So you
need to type cast it into the required type via using an inbuilt
function corresponding to that type. For example: to convert it
into integer, you have to use the inbuilt function ‘int()’, similarly
for converting it to float, you have to use the inbuilt function
‘float’.
Examples:
3. It has an optional parameter, which is displayed as a message to
the user, when the function is executed. Note that this
parameter can be of any type.
Examples:

You might also like