A set of instructions to perform a specific task
A language used to write a program
It is dynamically typed Interpreted language.
Python versions:
1. 2.x
2. 3.x
Latest: Python 3.9.1 Preferred 3.8.6
Things needed in a program: 1. Input (i/p) 2. Output (o/p) 3. Values 4. Operator
[value] - optional parameter
Input from the user is obtained using the input statement
Syntax:
input(prompt = "")
IN [1]
# Example 1
a = input('Enter a number ')
# Example 2
b = input()
stdout
Enter a number 10
The output is displayed to the user using the print statement
Syntax:
print(values,..., end="\n", sep=" ")
IN [7]
# Example
print(a)
print()
print(a,b)
stdout
10
10 1
Data: Unorderd collection of information
Associated with number
Eg: 10, 2.1, -99.7, 3.1416(pi)
All characters that are defined by Unicode. Look the below chart for the list of characters allowed under ASCII (American Standard Code for Information Interchange) which are most commonly used.
They are denoted using single quotes (‘’)
Eg: ‘1’, ‘a’, ‘#’
Asserts if a condition is True or False
If denotion in Number:
1. True - number != 0
2. False - number = 0
If nothing is present
Above four primitive data types
Combination of above four data types
A collection of characters
Eg: ‘Prabhu’, ‘123’, “Hi”, “Hello Python”
Literals are data that are used or processed in a program.
There are certain rules to be followed while naming a variable:
- Should start only with an alphabet or underscore (‘_’)
- Can contain characters defined in ASCII except ( $, &, \, /, etc.)
- It should not be keyword
- No spaces
- Generally, uppercase alphabets are not used in the beginning of a variable name.
Naming Convention - Wikipedia article
For Easy readability
- Function or use as name
- first letter in lowercase
- name has Multiple words:
1. use underscore for space
2. joint writing with words from second in caps
- No Long names
Naming convention for multi word variable names: 1. Camel case (abcAbc) 2. Pascal case (AbcAbc) 3. Screaming case (ABC) 4. Lazy case (abc) 5. Kebab case (ab-ab) 6. Snake case(ab_ab)
E.g.: age, input_values, firstName, number, prime_num
Not: user name, number_to_find_prime
IN [3]
userName = input()
user_name = input()
stdout
a
Words used for a special purpose in program.
Eg: input, print, int, if, for, try, list, etc.
IN [None]
# Key words
try
for
while
input
print
Lines that are not executed. It used only for understanding by the programmers or users
’#’ is used to comment lines
''' ''' and """ """ define documentation strings.
Brief explanation of code.
IN [1]
"""
This line gives example of docstrings.
This doc strings can extend many lines
"""
print('Hi')
stdout
Hi
Convert one form of data into another
type() # function gives the data type of a variable
Method | Result | Syntax |
---|---|---|
int() | Converts Numeric data into integer | int(x [, base=10]) |
float() | Converts Numeric Data into float | float(x) |
str() | Converts Data into string | str([x]) |
ord() | Generates Unicode code point integer value of a character | ord(x) |
chr() | Returns the Unicode character of given value | chr(x) |
oct() | Returns octal value as a string | oct(x) |
bin() | Returns Binary value as a string | bin(x) |
hex() | Returns Hexadecimal value as a string | hex(x) |
list() | Returns the list form of given iterable | list([x]) |
tuple() | Returns the tuple form of given iterable | tuple([x]) |
set() | Returns the set form of given iterable | set([x]) |
dict() | Returns Key-value mapping | dict([x]) |
IN [10]
print(type('123.0'))
a = float('123.0')
type(a)
stdout
<class 'str'>
IN [12]
print(a)
int(a)
stdout
123.0
Used to perform arithmetic and logical operations
Perform arithmetic operations
Operator | Description | Example |
---|---|---|
Addition | 2 |
|
Subtraction | 2 |
|
Multiplication | 2 |
|
Division | 2 |
|
Floor Division (quotient) | 2 |
|
% | Modulo (returns remainder) | 2 % 3 = 2 |
Exponentiation | 2 |
|
Unary Plus | ||
Unary Minus |
Relations between two variables
Operator | Description | Example |
---|---|---|
Equal | a |
|
Not Equal | a |
|
Greater | a |
|
Greater or Equal | a |
|
Lesser | a |
|
Lesser or Equal | a |
Assigns value to a variable
Operator | Description | Example |
---|---|---|
Assign | c |
|
Add and assign | a |
|
Subtract and assign | a |
|
Multiply and assign | a |
|
Divide and assign | a |
|
Floor division and assign | a |
|
%= | Get remainder and assign | a %= b |
Exponentiation and assign | a |
|
Walrus operator (to define values from a function) | y |
Walrus operator came into python in version 3.8. It will not work in previous versions.
Perform Logical operations
Operator | Description |
---|---|
and | Logical Operator AND |
or | Logical Operator OR |
not | Logical operator NOT |
Perform bitwise operations
Operator | Description | Syntax | Example |
---|---|---|---|
& | Bitwise AND | x & y | 101 & 11 |
| | Bitwise OR | x | y | 101 | 11 |
~ | Bitwise NOT | ~x | ~1 |
^ | Bitwise XOR | x ^ y | 1 ^ 1 |
<< | Shifts y bits in x to the left (Left shift operator) | x << y | 111001 << 2 |
>> | Shifts y bits in x to the right (Right Shift Operator) | x >> y | 111001 >> 2 |
Check if an iterable object contains the element
Operator | Description | Syntax |
---|---|---|
in | True if element in iterable | x in y |
not in | True if element not in iterable | x not in y |
Checks if two operands point to same object
Operator | Description | Syntax |
---|---|---|
is | True if point to same object | a is b |
is not | True if they do not point | a is not b |
A statement that gives a finite value.
Types:
1. Infix expressions:
Example: 12 + 23
2. Prefix expressions:
Example: + 12 23
3. Postfix expressions:
Example: 12 23 +
Few special characters defined under ASCII for formatting strings/ output
Sequence | Explanantion |
---|---|
\ | Back slash |
\‘ | Apostrophe or Single quotes |
\n | new line or line feed |
\f | form feed |
\r | carriage return |
\t | horizontal tab |
\“ | Double quotes |
\0 | Null character |
\a | bell |
\v | vertical tab |
\u… | unicode character |
\o… | octal values |
\x… | hexa decimal values |
String formatting or output formatting is an important part of a program output. The display of output in user understandable form is important.
The following are the string formatting methods used (in the order of increasing preference): 1. Simple or no formatting 2. Formatting using format specifiers 3. Formatting using the format() method 4. f-strings
print('string', variable)
IN [16]
name = input('Enter your name ')
print('Hello', name,', Welcome')
# Input: Prabhu
stdout
Enter your name Prabhu
stdout
Hello Prabhu , Welcome
% symbol indicate format specifiers.
Types: 1. Integer: %d 2. Float: %f 3. Character: %c 4. String: %s
print('string format_specifier'%(order of variables))
IN [18]
name = input()
# printf("%d", a); in C
print('Hello %s, Welcome'%(name))
# Input: Sooriya
stdout
Sooriya
stdout
Hello Sooriya, Welcome
IN [20]
str1 = 'Python'
ver = 3.8
print('Hello %s, Welcome to %s%.1f'%(name, str1, ver))
print("Welcome to %s%.1f %s"%(str1, ver, name))
stdout
Hello Sooriya, Welcome to Python3.8
Welcome to Python3.8 Sooriya
Uses .format()
method
print("string {order}".format(variables))
IN [33]
print("Hello {}, Welcome".format(name))
stdout
Hello Midhun, Welcome
IN [21]
string1 = 'Python'
print("Hello {0}, Welcome to {2}{1}".format(name, string1, ver))
print("Hello {}, Welcome to {}".format(name, string1))
print("Welcome to {}{} {}".format(str1, ver, name))
stdout
Hello Sooriya, Welcome to 3.8Python
Hello Sooriya, Welcome to Python
Welcome to Python3.8 Sooriya
F-strings or formatted strings used to format strings using variables
f'string {variable}'
The f-strings came after Python 3.6
IN [22]
print(f'Hello {name}, Welcome to {string1}')
stdout
Hello Sooriya, Welcome to Python
IN [26]
print(f'Hello {name} '\
f'Welocme to {string1}{ver}')
stdout
Hello Sooriya Welocme to Python3.8
The format method is used to format integers and floats as required.
Leading zeroes adding to integers
Eg: 01 002
%d - integer
%0nd - no. of leading zeroes
= n - no. of digits in the integer
format(int_value, format)
{int_value:0nd}
Round off decimal places
Eg: 10.1234: 10.12
%f - float
%.2f - 2 decimal places
format(float_value, format)
f"{float_value:.nf}"
IN [None]
Python allows assignment of different variables in one line.
Syntax:
var1, var2, var3, ... = val1, val2, val3, ...
IN [3]
a, b, c, d = 10, 20, 30, 40
print(a)
print(b)
print(d)
print(c)
stdout
10
20
40
30