if __name__ == '__main__': # If file is not imported, this will be executed
main()
$ python3
$ pip3 install <package-name>
$ python3 <filename>.py
$ time python3 <filename>.py
import <filename>
- Input
input("Input: ")
- Output Python automatically points the cursor to a new line. We need not specify explicitly.
print("Output")
In python, we need not specify the datatype of a variable. The interpreter interprets the value and assigns a suitabe datatype for that.
number = 0
org = "GitHub"
In python, we do not write a block of code in a pair of paranthesis.
We write it after :
followed by an indentation in the next line.
The conditional statements include if
, if-else
, nested if
and so on...
x,y = 0,1
if x < y:
print("x is less than y")
else:
print("x is not less than y")
Note that the colon (:) following is required.
Similarly, the nested if
also works.
As other programming languages, we have
for loop
for i in range(5):
print(i)
The range
function starts off with 0 till the number(excluded).
while loop
i=0
while(i < 10):
print("{} is less than 10".format(i))
i += 1
.format()
is a type of printing.
# These are all inplace operations returns a None value
<list>.append(<ele>) # Add an element to the end of the list
<list>.sort() # Sorts the given list
<list>.pop([<ele>]) # Removes the last element if no argument else removes the element at the index given
<list>.clear() # Makes it an empty list
<list>.insert(<index>, <ele>) # Adds the element before the index
<list>.extend(<iterator>)
<list>.reverse() # Reverse a given list
# These are not inplace operations and has a return value
<list>.copy() # Makes a shallow copy of the list
<list>.index(<ele>) # Returns the index of the given element
<list>.count(<ele>) # Returns the number of occurrences of the element
key-value pairs.
<dict> = {'Google':100, 'Facebook':80, 'Apple':90}
<dict>['Amazon'] = 85 # Adding a key along with the value
# Accessing the dictionary
for key in <dict>:
print("{key} -> {x}".format(key=key, x=<dict>[key]))
<dict>.keys() # Print all the keys
<dict>.values() # Print all the values
len(<dict>) # Find the length of the dictionary
<dict>.pop(<key>) # Removes the item with the specified key name
<dict>.copy() # Make a copy of a dictionary
A dictionary can also contain many dictionaries, this is called nested dictionaries.
$ sudo pip3 install pandas # Installing pandas module in Ubuntu
import pandas as pd
<dataframe>.head([<n>]) # Display the first n rows of the Dataframe, default value is 5 rows
<dataframe>.tail([<n>]) # Display the last n rows of the Dataframe, default value is 5 rows
<dataframe>.info() # Gives some information like, row and column datatypes, non-null count, and memory usage
<dataframe>.describe() # Provides some descriptive statistics about the numerical rows in the dataframe
$ sudo pip3 install nltk # Installing nltk module in Ubuntu
import nltk
# Before trying any function download the word list
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')