Basic syntax from the python programming language
The print function is used to display or print output as follows
print("Content that you wanna print on screen")
The input function is used to take input as string or character from the user as follows:
var1 = input("Enter your name: ")
print("My name is: ", var1)
To take input in form of other datatypes we need to typecaste them as follows:-
To take input as an integer:-
var1=int(input("enter the integer value"))
print(var1)
To take input as an float:-
var1=float(input("enter the float value"))
print(var1)
range function returns a sequence of numbers, eg, numbers starting from 0 to n-1 for range(0, n)
range(int_start_value,int_stop_value,int_step_value)
Here the start value and step value are by default 1 if not mentioned by the programmer. but int_stop_value is the compulsory parameter in range function
example-
#Display all even numbers between 1 to 100
for i in range(0,101,2):
print(i)
Comments are used to make the code more understandable for programmers, and they are not executed by compiler or interpreter.
# This is a single line comment
'''This is a
multi-line
comment'''
An escape sequence is a sequence of characters; it doesn't represent itself (but is translated into another character) when used inside a string literal or character. Some of the escape sequence characters are as follows:
Newline Character
print("\n")
It adds a backslash
print("\\")
It adds a single quotation mark
print("\'")
It gives a tab space
print("\t")
It adds a backspace
print("\b")
It represents the value of an octal number
print("\ooo")
It represents the value of a hex number
print("\xhh")
Carriage return or \r will just work as you have shifted your cursor to the beginning of the string or line.
print("\r")
Python string is a sequence of characters, and each character can be individually accessed using its index.
You can create Strings by enclosing text in both forms of quotes - single quotes or double quotes.
variable_name = "String Data"
Example:
example_str = "Shruti"
print("string is ", example_str)
The position of every character placed in the string starts from the 0th position and steps by step, it ends at the length-1 position.
Slicing refers to obtaining a sub-string from the given string. The following code will include index 1, 2, 3, and 4 for the variable named var_name.
Slicing of the string can be obtained by the following syntax:
string_var[int_start_value:int_stop_value:int_step_value]
var_name[1:5]
Here start and step value are considered 0 and 1, respectively if not mentioned by the programmer.
Returns True if all the characters in the string are alphanumeric, else False.
string_variable.isalnum()
Returns True if all the characters in the string are alphabets.
string_variable.isalpha()
Returns True if all the characters in the string are decimals.
string_variable.isdecimal()
Returns True if all the characters in the string are digits.
string_variable.isdigit()
Returns True if all characters in the string are lowercase.
string_variable.islower()
Returns True if all characters in the string are whitespaces.
string_variable.isspace()
Returns True if all characters in the string are uppercase.
string_variable.isupper()
Converts a string into lowercase equivalent.
string_variable.lower()
Converts a string into uppercase equivalent.
string_variable.upper()
It removes leading and trailing spaces in the string.
string_variable.strip()
A List in Python represents a list of comma-separated values of any data type between square brackets.
var_name = [element1, element2, ...]
These elements can be of different data types.
The position of every element placed in the list starts from the 0th position and step by step, it ends at length-1 position.
List is ordered, indexed, mutable, and the most flexible and dynamic collection of elements in Python.
This method allows you to create an empty list.
my_list = []
Returns the index of the first element with the specified value.
list.index(element)
Adds an element at the end of the list.
list.append(element)
Add the elements of a given list (or any iterable) to the end of the current list.
list.extend(iterable)
Adds an element at the specified position.
list.insert(position, element)
Removes the element at the specified position and returns it.
list.pop(position)
The remove() method removes the first occurrence of a given item from the list.
list.remove(element)
Removes all the elements from the list.
list.clear()
Returns the number of elements with the specified value.
list.count(value)
Reverses the order of the list.
list.reverse()
Sorts the list.
list.sort(reverse=True|False)
Tuples are represented as comma-separated values of any data type within parentheses.
variable_name = (element1, element2, ...)
These elements can be of different data types.
The position of every element placed in the tuple starts from the 0th position and step by step, it ends at length-1 position.
Tuples are ordered, indexed, immutable, and the most secured collection of elements.
Lets talk about some of the tuple methods:
It returns the number of times a specified value occurs in a tuple.
tuple.count(value)
It searches the tuple for a specified value and returns the position.
tuple.index(value)
A set is a collection of multiple values which is both unordered and unindexed. It is written in curly brackets.
var_name = {element1, element2, ...}
var_name = set([element1, element2, ...])
Set is an unordered, immutable, non-indexed type of collection. Duplicate elements are not allowed in sets.
Set Methods
Adds an element to a set.
set.add(element)
Remove all elements from a set.
set.clear()
Removes the specified item from the set.
set.discard(value)
Returns intersection of two or more sets.
set.intersection(set1, set2, ... etc)
Checks if a set is a subset of another set.
set.issubset(set)
Removes an element from the set.
set.pop()
Removes the specified element from the set.
set.remove(item)
Returns the union of two or more sets.
set.union(set1, set2, ...)
The dictionary is an unordered set of comma-separated key:value pairs, within {}, with the requirement that within a dictionary, no two keys can be the same.
<dictionary-name> = {<key>: value, <key>: value ...}
Dictionary is an ordered and mutable collection of elements. Dictionary allows duplicate values but not duplicate keys.
By putting two curly braces, you can create a blank dictionary.
mydict = {}
By this method, one can add new elements to the dictionary.
<dictionary>[<key>] = <value>
If a specified key already exists, then its value will get updated.
<dictionary>[<key>] = <value>
The `del` keyword is used to delete a specified key:value pair from the dictionary as follows:
del <dictionary>[<key>]
Below are some of the methods of dictionaries.
It returns the length of the dictionary, i.e., the count of elements (key: value pairs) in the dictionary.
len(dictionary)
Removes all the elements from the dictionary.
dictionary.clear()
Returns the value of the specified key.
dictionary.get(keyname)
Returns a list containing a tuple for each key-value pair.
dictionary.items()
Returns a list containing the dictionary's keys.
dictionary.keys()
Returns a list of all the values in the dictionary.
dictionary.values()
Updates the dictionary with the specified key-value pairs.
dictionary.update(iterable)
In Python, indentation means the code is written with some spaces or tabs into many different blocks of code to indent it so that the interpreter can easily execute the Python code.
Indentation is applied on conditional statements and loop control statements. Indent specifies the block of code that is to be executed depending on the conditions.
The if, elif, and else statements are the conditional statements in Python, and these implement selection constructs (decision constructs).
if (conditional expression):
statements
if (conditional expression):
statements
else:
statements
if (conditional expression):
statements
elif (conditional expression):
statements
else:
statements
if (conditional expression):
if (conditional expression):
statements
else:
statements
else:
statements
Example:
a = 15
b = 20
c = 12
if (a > b and a > c):
print(a, "is greatest")
elif (b > c and b > a):
print(b, " is greatest")
else:
print(c, "is greatest")
A loop or iteration statement repeatedly executes a statement, known as the loop body, until the controlling expression is false (0).
for <variable> in <sequence>:
statements_to_repeat
Example:
for i in range(1, 101, 1):
print(i)
while <logical-expression>:
loop-body
Example:
i = 1
while (i <= 100):
print(i)
i = i + 1
The break statement enables a program to skip over a part of the code. A break statement terminates the very loop it lies within.
for <var> in <sequence>:
statement1
if <condition>:
break
statement2
statement_after_loop
Example:
for i in range(1, 101, 1):
print(i, end=" ")
if (i == 50):
break
else:
print("Mississippi")
print("Thank you")
The continue statement skips the rest of the loop statements and causes the next iteration to occur.
for <var> in <sequence>:
statement1
if <condition>:
continue
statement2
statement3
statement4
Example:
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
A function is a block of code that performs a specific task. You can pass parameters into a function. It helps us to make our code more organized and manageable.
def my_function():
# statements
The `def` keyword is used before defining the function.
my_function()
Whenever we need that block of code in our program, simply call that function name whenever needed. If parameters are passed during defining the function, we have to pass the parameters while calling that function.
Example:
def add(): # function definition
a = 10
b = 20
print(a + b)
add() # function call
The function return statement returns the specified value or data item to the caller.
return [value/expression]
Arguments are the values passed inside the parenthesis of the function while defining as well as while calling.
def my_function(arg1, arg2, arg3, ... argn):
# statements
my_function(arg1, arg2, arg3, ... argn)
Example:
def add(a, b):
return a + b
x = add(7, 8)
print(x)
File handling refers to reading or writing data from files. Python provides some functions that allow us to manipulate data in the files.
var_name = open("file name", " mode")
r - to read the content from the file
w - to write the content into the file
a - to append the existing content into the file
r+ - To read and write data into the file. The previous data in the file will be overridden.
w+ - To write and read data. It will override existing data.
a+ - To append and read data from the file. It won’t override existing data.
var_name.close()
The read function contains different methods: read(), readline(), and readlines()
read() # return one big string
It returns a list of lines
readlines() # returns a list
It returns one line at a time
readline # returns one line at a time
This function writes a sequence of strings to the file.
write() # Used to write a fixed sequence of characters to a file
It is used to write a list of strings
writelines()
An exception is an unusual condition that results in an interruption in the flow of a program.
A basic try-catch block in Python. When the try block throws an error, the control goes to the except block.
try:
# [Statement body block]
raise Exception()
except Exceptionname:
# [Error processing block]
The else block is executed if the try block has not raised any exception, and the code has been running successfully.
try:
# statements
except:
# statements
else:
# statements
The finally block will be executed even if the try block of code has been running successfully or the except block of code is executed. The finally block of code will be executed compulsorily.
try:
# statements
except:
# statements
else:
# statements
finally:
# statements
It is a programming approach that primarily focuses on using objects and classes. The objects can be any real-world entities.
The syntax for writing a class in Python:
class class_name:
pass # statements
Instantiating an object can be done as follows:
<object-name> = <class-name>(<arguments>)
The self parameter is the first parameter of any function present in the class. It can be of a different name, but this parameter is a must while defining any function in the class, as it is used to access other data members of the class.
Constructor is a special function of the class used to initialize the objects. The syntax for writing a class with a constructor in Python:
class CodeWithHarry:
# Default constructor
def __init__(self):
self.name = "CodeWithHarry"
# A method for printing data members
def print_me(self):
print(self.name)
By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class.
It provides the re-usability of the code.
class Base_class:
pass
class Derived_class(Base_class):
pass
The filter function allows you to process an iterable and extract those items that satisfy a given condition.
filter(function, iterable)
Used to find whether a class is a subclass of a given class or not, as follows:
issubclass(obj, classinfo) # returns true if obj is a subclass of classinfo
Here are some of the advanced topics of the Python programming language like iterators and generators.
Used to create an iterator over an iterable.
iter_list = iter(['Harry', 'Aakash', 'Rohan'])
print(next(iter_list))
print(next(iter_list))
print(next(iter_list))
Used to generate values on the fly.
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
Decorators are used to modifying the behavior of a function or a class. They are usually called before the definition of a function you want to decorate.
@property
def name(self):
return self.__name
It is used to set the property 'name'
@name.setter
def name(self, value):
self.__name = value
It is used to delete the property 'name'
@name.deleter # property-name.deleter decorator
def name(self, value):
print('Deleting..')
del self.__name