uses of python

1.How to convert string to integer in python?

  •  A string is a sequence of characters. It is a derived data type. Strings are immutable.  This means that once defined, and they cannot be changed. Many Python methods, such as replace(), join(), or split() modify strings. However, they do not modify the original string. They create a copy of a string which they modify and return to the caller.
          
  •  A string is a sequence of character with is represented within quotes(“ “)
  •  A string can be converted into an integer using the int() function.

 Example:

2.How to create a virtual environment in python?

  • To create a Python virtual environment for a project, we should install the recent version of python python3.7 and visual studio code.
  • Open windows PowerShell the command line user interface for windows that are often used as part of a Python programmer’s development environment.
  • Type python -m vene (name of the subdirectory), so I am typing python -m vene env; therefore, we set up the virtual environment.
  • Open a new folder like “project” and click on your directory and open the project directory using visual studio code; therefore, the file project is opened in virtual studio code.
  • Within that directory, create a sub-directory that is the name of the project where the python code is going to be placed.
  • Within the sub-directory, create a new python fill like hello.py.
  • Therefore the python extension fill is activated and will automatically detect the existing virtual environment inside that directory.

3.How to run a python program in cmd?

  • Command prompt allowing the user to type in instructions for immediate execution. All major operating systems (Windows, Mac, Unix, Linux, etc.) support command lines that programmers and power users can employ to perform file management operations directly and often more efficiently than by using a graphical user interface (GUI). To run a python program in command prompt. 
  • Open the note pad and type the program and save it using the .py extension (hello.py)

Example

  • Open command prompt and type “C:\Users\User_name\position_of_the_file\file_name.py”

Example

  • If the output is not shown, then again open the command prompt and type “C:\name_of_installed_python_folder”

“C:\User\User_name\Position_of_the_file\file_name.py”

Example

4.How to create a dictionary in python?

  • Dictionaries are Python’s implementation of a data structure. It is changeable, meaning that we can change, add or remove items after the dictionary has been created. Dictionary items are ordered, changeable, and do not allow duplicates. Dictionary items are presented in key: value pairs and can be referred to by using the key name. A dictionary can define by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value:

Example

5.How to open a file in python?

  • Open a new file and create a new text file with a unique directory name. 
  • Open python Compiler and type

Variable_name1=file_name.txt 

Variable_name=open(variable_name1,’r’)

In the above code, we are first specifying the directory to be opened with the .txt file extension, and then we are using the open command along with r-to read the text file.

The above code does not return any text. 

  • Whenever we open a file, it good to close the file, so we use the command line.

Variable_name.close()

Example 

6.How to clear the python shell?

  • Python interactive mode is a command-line shell that gives immediate feedback for each statement while running previously fed statements inactive memory.
  • Python shell can be used for quickly trying out Python commands and concepts. It can also be used as a simple calculator for doing arithmetic operations.
  • There is no in-built function for clear in python shell mode, but it can be done using the import os module, and it returns a null value.

Example

7.How to convert int to string in python?

  •  
    Python has three built-in function integers, floating-point numbers, and complex numbers. The name for the integer data type is called int.
  • An int is a whole number. It can be positive or negative without a decimal. There’s no limit to how large an integer can be      
  • An integer can be converted into a string using the str() function.

Example

8.How to find the length of the list in python?

  • A list is created by placing all the elements inside square brackets [ ], separated by commas.
  • Len() returns the number of items of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).    
  • To find the length of the list python, built-in function len() is used.

Example

9.How to get input from users in python?

  • Python has an input function that asks the user for some input text. The programming waits for the user to give input. In python2, you have a built-in function raw_input(), and in python3, you have input().
  • Input() function is a built-in function used to get input from the user in python. The input from the user is read as a string and can be assigned to a variable name. Then press the enter key, or the return key will display an interactive output.

Example

10.How to read a file in python?

There are two ways of reading a file in python.

Using read() method

  • Open a new file and create a new text file with a unique directory name. 
  • Open python Compiler and type

Variable_name1=file_name.txt 

Variable_name=open(variable_name1,’r’)

In the above code, we are first specifying the directory to be opened with the .txt file extension, and then we are using the open command along with r-to read the text file.

The above code does not return any text. 

  • To read the content of the file, we are using a method called read.

Variable_name2=variable_name.read()

The above code reads the text file content.

  • Whenever we open a file, it good to close the file, so we use the command line.

Variable_name.close()

Example

 Using headlines

  • To open a text file, we type

Variable_name=open(file_name,’r’)

  • To read the text file in python, we use the readlines method.

Variable_name1=Variable_name.readlines()

Print(Variable_name1)

Variable_name.close()

Example 

Also Read: What is Rest API in Python?

11.How to install matplotlib in python?

  • PIP is a package-management system written in python used to install and manage software packages. It comes pre-installed on 3.4 or older versions of Python, pip commands are used in the command prompt, and it allows you to install additional libraries and packages that are not part of the standard Python library, such as the ones found in the Python Package Index.
  • Matplotlib is a plotting python library used for creating static, animated, and interactive visualization in python. It is not a part of the Standard Libraries, which is installed by default when Python. Matplotlib. pyplot is used for 2D graphics. It can be used in python scripts, shell, web application servers, and other graphical user interface toolkits. 

Steps to install matplotlib in python

  • Open the terminal
  • Type pip3 install matplotlib

Example

To check

  • On the same terminal type, python-which set the environment for python.
  • Import matplotlib and check its version

Example

12.How to run python script?

  • Using interactive mode

Open the command prompt or terminal and type python3, and hit enter. Therefore you can now use python codes and commands in the command prompt.

Example

  • Using the command line

Open a command prompt and change it into a document folder with cd Documents. 

Then you can make a new directory with mkdir name_of_directory; then we are changing into that directory using cd name_of_directory

Now we are creating another new directory mkdir name_of_new_directory and again change into that directory cd name_of_new_directory

Next, type dir to open the empty directory in the command prompt. 

Then we type copy NUL name_of_file.py to create an empty file, and then we are going to open python idle to code by typing idle name_of_file.py

At last, the python IDLE gets opened to run the python script.

Example 

  • Using text editor

Open your text editor like notepad++ and type a basic program and save it with a .py extension file. 

Now open your command prompt and type cd location_of _file, so you are in the location where your file is stored.

Next type python saved_file_name.py

Example

13.What is lambda in Python?

  • A lambda function is a small anonymous function that refers to a function declared with no name. It can take any number of arguments but can have only one expression. It is used to return function objects. The lambda operator cannot have any statements. The lambda function is used when you want a function for a short period. In Python, we generally use it as an argument to a higher-order function. Syntax: lambda arguments: expression

Example

14.How to install packages in python?

  • The Python Package Index (PyPI) is the official third-party software repository for Python. It is analogous to CPAN, the repository for Perl. Some package managers, including pip, use PyPI as the default source for packages and their dependencies.
  • PIP is the standard package manager for Python. It allows you to install and manage additional packages that are not part of the Python standard library. Steps to install python packages in windows 

Using command prompt or terminal

  • To open the command prompt or terminal
  • Type the following code:

pip3 install (the_required_package)

Example

Example 

15.How to declare an array in python?

  • An array is a data structure that stores values of the same data type, such as integer and strings. In python, a list can contain values corresponding to different data types, and arrays can only contain values corresponding to the same data type. 
  • In python, NumPy is used to work with an array. It provides a high-performance multidimensional array object and tools for working with these arrays. 

Three ways of declaring an array

  • Python array module

Using the array module we can create an array in a python environment. 

Syntax: array.array(‘format_code’,[data])

Example:

  • Python list as an array

The list can be used to create and store the elements like an array dynamically.

Example

  • Python NumPy array

The NumPy module can be used to create single as well as multidimensional arrays in python.

Example

16.How to run python in windows?

  • Python is an interpreted, high-level and general-purpose programming language. It is open-source, which means it is free to use, Runs on a window in three different ways.
  • Using command prompt or terminal

Open the command prompt or terminal and type python3; it will open the python interface.

Example

  • Using the command line

Store a python script using the file extensions .py and save 

Open the python interface and type python file_name.py

Example

  • Using python IDLE

Open python idle and type the program, save and run, it is the easiest way to run a python program

Example

17.In python, what is returned when evaluating [n for n in range(10) if n % 2]?

      Program:

      Output: 

18.How to define a function in python?

  • Functions are named blocks of code that are designed to do specific tasks. A function can be defined as the organized block of reusable code, which can be called whenever required. Function block begins with the keyword def followed by the function name and parenthesis (). Any input parameters or arguments should be placed within the parenthesis 

        The statement return [expression] exits a function optionally passing back an expression to the caller.

                         Syntax: def function_name(parameters separated by comma):

  • Using functions, we can avoid rewriting We can call Python functions multiple times in a program and anywhere in a program.

Example

19.How to import CSV files in python?

  • Python has a cast library. One among the module is the CSV module which gives the python programmer the ability to parse CSV files.
  • A CSV file is a human-readable text file where each line has several fields separated by commas or some other delimiter.
  • Using pandas

Open your python command prompt and import pandas, so we type import pandas as PD 

Then we are creating an object and assigning it to read a file from the text of location, so we type Variable_name =pd.read_csv(the path of the file)

Now we have imported data in python

Next, we should print the data, so we just type the variable_name

20.What is an indentation in python?

  • Blank spaces at the beginning of a code line are referred to as indentation, it makes the code readable and neat. Indents can ignore some times in continuous code lines
  • Indentation error: occurs due to improper placing of spaces and tabs or both the tabs and spaces are placed in the code. the indentation in Python is very important. Python uses indentation to indicate a block of code. 

Example

Also Read : Python Panda Cheat Sheet

21.How to update python?

  • To update python go to Google and open python.org and click on downloads and search for the latest versions download it. 
  • The file gets downloaded will be seen at the bottom of  your desktop, now click on the downloaded file and open 
  • Next, click on continuous and agree with the policy 
  • Now you are updated to the new version of python

22.How to set a path in python?

  • Open my computer and click on c-drives, next open users and then click on app_data and then click on locals and the go-to programs on open python
  • Now click on to size and copy the path 
  • Then click and open the script and click on the size and copy its path
  • To set a path in python first open your c-drive and right-click on the screen to select properties 
  • Next, click on advanced system settings and click on environment settings
  • Click on the variable path and paste all the copied path and save
  • Now restart your command prompt and the path is set in python.

23.What is returned by datetime(1970, 1, 1).strftime(‘%y-%d-%b’) in python?

Before debugging 

Program

After debugging 

Program

24.How to take multiple inputs in python?

  • The basic usage of the input() method is to ask the user to enter values or strings and processes them in the program, the input function waits for the user to respond to the question and it returns the desired output.

To take multiple inputs from user their is three ways

  • Split() function

The split function is used to separate two or more input value given by the user and print it in the next line.

Example

  • Input() function

The input function is normally used to get input from the user but here we are using two or more inputs in a single expression. 

Example

  • Map() function 

The map function allows to transform and process all the item in iterable form without explicitly defining for loop

Syntax: var1,var2,var3=map(int, input().split())

Example

  • List comprehension 

List comprehension or set comprehension is used for creating new lists from other iterables, it is a very comprehensive way of describing sequence. List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. 

Syntax: x,y= [ x for x in input().split()]

Example

25.How to plot graphs in python?

  • Matplotlib is a comprehensive library for creating static, animated, and interactive visualization in python. Matplotlib. pyplot is a python package used for 2D graphics. 
  • Matplotlib is not a part of the Standard Libraries which is installed by default when Python, The library is extensive and capable of changing very minute details of a figure.

Steps to plot graph in python

  • Install or update to python3 to perform data visualization in python
  • Set up the required visualization package by 

Installing Matplotlib using the following code in your terminal

  • Import the matloptlib library for plotting
  • Enter the  values  to be plot and label the name of the x and y-axis
  • Use plt.plot() keyword to 

Example

26.How to check the python version in windows?

  • Python is an interpreted high-level and general-purpose programming language. It is open-source, which means it is free. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick, so as python is so advancing and important it is necessary to check the python version and update it.
  • Check version using windows 

Open command prompt  and type python3 to open python interface and in the second line the version of the python appears 

Example

  • Check version using python script on windows 

Open python idle or scripting mode and import a module sys to check the version 

Example

27.How to input a list in python?

  • A list is known as a “sequence data type”. Each value of a list is called an element. The elements of the list should be specified within square braces [] and each element has a unique value called index value begins with zero. A list is similar to an array but the list can hold any no of values of different data types and an array can only hold values of the same data type.
  • To form an input into a list in a program we use the keyword variable_name.split() and for loop is used for iteration.

Example

28.How to reverse a number in python?

  • Reversing a number in python is called a palindrome. Reversing a list of numbers can be done in both interactive as well as scripting mode.
  • Reversing using string slicing 

Syntax: variable_name[::-1]

(-1 indicates the reverse order of the input)

Example

  • Reversing using while loop

To reverse a list of numbers in scripting mode we use a while loop and three mathematical condition

Algorithm 

  1. Input Integer:  number  
  2. (1) Initialize variable revs_number = 0  
  3. (2) Loop while number > 0  
  4.   (a) Multiply revs_number by 10 and add the remainder of the number   
  1.       divide by 10 to revs_number   
  2.               revs_number = revs_number*10 + number%10;  
  3.      (b) Divide num by 10  
  4. (3) Return revs_number  

29.How to use for loop in python?

  • The main functionality of for loop is to iterate through a set of sequences like a list, tuple, dictionary, and string. It is most often used in situations where we have to execute a block of code several times. 

Syntax: for <sequence> in <variable>:

Example including strings

Example including integers

30)how to remove duplicates in list python

To remove duplicates in the list we use two python built-in function for loop and if statement, for loop to iterate through the entered sequence and if statement to include a condition to print a sequence with no duplicates values 

Example

Other ways of removing duplicates 

  • Using set 

To remove the duplicates from the list we are using one of pythons built-in function set()

Example

  • Using list comprehension

To remove duplicates we are using list comprehension, which creates a new sequence that is already defined.

Example

31.How to check the python version in cmd?

  • Python is an interpreted high-level and general-purpose programming language. It is open-source, which means it is free. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick, so as python is so advanced and important it is necessary to check the python version and update it.
  • Check version using terminal

Open the terminal and type python –version

Example

32.How long does it take to learn python?

  • Python is the most popular programming language and it is used in advanced projects like artificial intelligence, data analysis, and more, so right now is the best time to learn python. Python language is nearly equal to English therefore anyone can learn it if they are curious enough.
  • Now let dive into the question how long does it take to learn python, for a person with some amount of coding knowledge like if they know c,c++ or Java they learn the basic of python in a week time but for a person with level zero coding skill can learn python within 5 weeks
  • Advancing in python is a long journey but still, for people like us it is going to a happy journey, the period to advance in python is up to the person’s understanding capability, and interest in programming. 

33.How to remove an element from a list in python?

  •  A list is created by placing all the values within square braces [ ] and separated by commas. A list can is a compound data type which means you can have different data types under a list, for example, we can have integer, float, and string items in the same list. 

To remove an elements from a list we can use 3 keywords pop(), remove() and del() function

  • Using pop() function

the pop() function is used to delete a particular element using its index value, as soon as the elements are deleted, the pop() function shows the element which is not deleted. 

Syntax: variable_name. Pop(index_value)

Example

  • Using remove() keyword 

Remove() function is also used to delete a particular element from a sequence if the index value is not known 

Syntax: variable_name. remove(element)

Example

  • Using del() keyword 

del() function used to delete an element using the given index value

You can also slice a rage from the list using the del() function. The start/stop index from the list can be given to the del keyword, and the elements falling in the range will be removed.

Syntax: 

  1. del variable_name[start: stop]
  2. del variable_name[index_value]

Example

34.How to replace a character in a string in python?

  •  A string in python is a derived data type i.e if it is defined once it cannot be changed. We can create a string by enclosing the character within single, double, or triple quotes.replace() function create a new string where the selected character is replaced with a new character and place in its desired place.

Syntax: variable_name.replace(old, new,count)

             old- The old substring that you want to replace

             new- The new substring that will take the place of the old string

             count(optional)- if the given string has two or more same substring we should           specify the number of the substring to the replaced or as default, it will replace all the same substring

Example

35.How to execute a python program?

To execute a python program there are 3 ways

  • Using the python command line

Open a python command line on your desktop and get to interactive mode, then type the program 

Example 

  • Using Command prompt 

Open command prompt and type python3 to open python interface, then type the program to be executed

Example

  • Using Python IDLE

Open python idle and click on the new file to enter into script mode and then type your code, save it with .py file extension and execute.

Example 


36.How to install pil in python?

  • Open your command prompt and type pip install pillow
  • To check whether pil is installed type pil list

       So now we have installed pil

37.How to install cv2 in python?

  • Opencv is used for developing real-time computer virtual applications, it is an open-source library. The abbreviation of OpenCV is open-source computer vision. It is also used in machine learning, image processing, video capturing, and more.
  •  Open command prompt  and type pip install OpenCV-name of the python file

Example 

38.How to take array input in python?

  • First, we import from the array and * means for all, then we are creating a variable and assigning it  to an empty array and for loop is being used to iterate through the array

Example 

39.How to install Tkinter in python?

  • Python provides multiple options to create GUI and the Tkinter is a standard library for creating the graphical user interface for desktop-based applications. The fast and easy way to create GUI applications is by using python combined with Tkinter. It is open-source and available under the Python License.

To install Tkinter

  • We do not need to install Tkinter as the python installed from the website comes with a Tkinter package. All we have to do is check whether we have three packaged or not, so we import Tkinter and if it returns no answer then Tkinter is already installed if not you need to install it again in the python environment. 

Example 

40.How to connect python with MySQL?

  • The prerequisite is to install MySQL client, to install type pip install mysqlclient.
  • Next, install a web server and create a database
  • Now stars the real program open your pycharm and import mysqldb, so type import MSQLdb as MDB
  • Then create some variable and assign it to the way you want it to be called, so now we type 

DBNAME=” name of database”

DBHOST=” localhost”

DBPASS=” password of the database”

DBUSER=” the user name for the database”

  • Next, we are using the try and except method and in the try part we are including a  variable dp and assigning to MDB.connect(DBHOST, DB USER, DBPASS, DBNAME) and print(“successfully “)
  • And in the except part, we include MD. error as e and then print (“unsuccessful” +e)

Example

41.How to sort a dictionary in python?

  • A Dictionary in Python is the unordered and changeable collection of data values that holds key-value pairs. Dictionary Keys are Case Sensitive, elements key-value pairs are not in ordered form, No duplicates keys are allowed. Dictionary is immutable, it is optimized to retrieve values when the key is known. 
  • Sorting using keys and items

Syntax: sorted(variable_name. keys())

             sorted(variable_name. Items())

Example 

  • Sorting using values()

Syntax: sorted(variable_name.values())

Example:

42.How to create a matrix in python?

  • Numpy is a python library used for scientific computing. It provides a high-performance multidimensional array object and tools for working with these arrays. Python NumPy arrays provide tools for integrating C, C++, etc. It is also useful in linear algebra, random number capability, and more.
  • To create a matrix in python we should first install NumPy and using the command  pip3 install NumPy
  • Then import NumPy and assign the 2-dimensional matrix to a variable

Example

43.How to convert the list into a string in python?

  • To convert a list into a string we are should define a function to convert a list into an array
  • Next, we are using for loop to iterate through the array and print the output.

Example

44.How to read JSON files in python?

  • JSON (JavaScript Object Notation) is a standard text-based format for representing structured data based on JavaScript object syntax is in a string or text format 
  • Open python command prompt  and import JSON and enter your database
  • To load the json database in python we should type data=json.loads(key_variable)
  • Loads-Decode the JSON string
  • Then print the data, so now we have uploaded Json file in python

Example

45.How to define an array in python?

  •  An array is a data structure that stores values of the same data type such as integer and strings. In python, a list can contain values corresponding to different data types and arrays can only contain values corresponding to the same data type. 
  • To define an array we are first import the array module then we are assigning a variable to an integer type array and print it

Example

46.How to concatenate two strings in python?

  • Using operator

To concatenate two string we are using the ‘+’ operator to add up the two strings 

Example

  • Using join method

In this method, we are using a built-in function join() to add two strings.

Example

  • Using % operator

In this program, we are using ‘ %s’ to hold the place for the strings and print it

Example

  • Using format() function

Here {} is a place holder it holds the place for the string and is also used in other programs as a place holder.

Example

47.How to sort a string in python?

  • To sort a string we are using a list and a built-in function sort()

Example

48.How to uninstall python?

  • Uninstall using windows 

Open windows and enter into settings and search for programs and features 

It will take you to the location of the python program in your computer double click and uninstall python

  • Uninstall using pip

Open command prompt and type pip uninstall python3

Example

49.How to upgrade pip in python?

  • First, open the command prompt and type cd to ensure that your starting point has only the drive name
  • Then find the location of python software and copy the file “HTTP:”
  • Then type cd and paste the copied text without ”c:/”
  • Next type python -m pip install —upgrade pip, now we have the upgraded version on pip.

50.What is a decorator in python?

  • Decorators allow you to wrap one function into another function, it allows the user to modify the behavior of the function and extends the behavior of the wrapping function. Decorator is always called before defining the function. Decorators are more efficient than subclassing because the behavior of an object can be augmented without instantiating an entirely new object.
1

LEAVE A REPLY

Please enter your comment!
Please enter your name here

18 − 14 =