Found 10805 Articles for Python

What is the difference between attributes and properties in python?

Rajendra Dharmkar
Updated on 08-May-2023 12:03:59

5K+ Views

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods. A property decorator in Python provides getter/setter access to an attribute. You can define getters, setters, and delete methods with the property function. If you just want the read property, there is also a @property decorator you can add above your method. # create a class class C(object): ... Read More

What are required arguments of a function in python?

Pranathi M
Updated on 16-Sep-2022 07:29:41

2K+ Views

Functions accept arguments that can contain data. The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like. As the name implies, mandatory arguments are those that must be given to the function at the time of the function call. Failure to do so will lead to a mistake. Simply put, default function parameters are the exact opposite of required arguments. As we previously saw, while declaring the function, we give the function parameters a default value in the case of default arguments. The function automatically ... Read More

What are the allowed characters in Python function names?

Manogna
Updated on 12-Jun-2020 11:27:30

1K+ Views

Python IdentifiersIdentifier is the name given to entities like class, functions, variables etc. in Python. It helps in knowing one entity from another.Rules for writing identifiersIdentifiers can be a combination of lowercase letters (a to z) or uppercase letters (A to Z) or digits (0 to 9) or an underscore (_). Names like myClass, var_3 and print_to_screen, all are valid examples.An identifier cannot start with a digit. 2variable is invalid, but variable2 is perfectly correct.Keywords cannot be used as identifiers. The word ‘global’ is a keyword in python. So we get an invalid syntax error hereExampleglobal = "syntex" print globalOutputFile ... Read More

How do you test that a Python function throws an exception?

Manogna
Updated on 12-Jun-2020 11:30:14

239 Views

We write a unittest that fails only if a function doesn't throw an expected exception.We also test if a Python function throws an exception.For example, see the sample code we paste into the Python shell to test Python's type-safety:Exampleimport unittest class MyTestCase(unittest.TestCase):    def test_1_cannot_add_int_and_str(self):       with self.assertRaises(TypeError):          1 + '1'       def test_2_cannot_add_int_and_str(self):       import operator       self.assertRaises(TypeError, operator.add, 1, '1')  unittest.main(exit=False)Running the testsOutputAnd the terminal outputs the following − .. ---------------------------------------------------------------------- Ran 2 tests in 0.001s OKTest one uses assertRaises as a context ... Read More

Why does Python code run faster in a function?

Manogna
Updated on 30-Jul-2019 22:30:20

317 Views

It is found that if python code is run normally and then if it is run in a python function, it runs faster in the latter case. I want to know why python code runs faster in a function.It is generally found that it is faster to store local variables than global variables in a python function. This can be explained as under.Aside from local/global variable store times, opcode prediction makes the function faster.CPython is the original Python implementation we download from Python.org. It is called CPython to distinguish it from later Python implementations, and to distinguish the implementation of ... Read More

What are the basic scoping rules for python variables?

Pranathi M
Updated on 16-Sep-2022 07:37:34

334 Views

Variables are classified into Global variables and Local variables based on their scope. The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined. Local variables are those that are defined inside a function but have a scope that is only applicable to that function, as opposed to global variables, which are defined outside of any function and have a global scope. In other words, we may argue that although global variables are accessible ... Read More

How we can call Python function from MATLAB?

Rajendra Dharmkar
Updated on 27-Sep-2019 07:37:37

255 Views

The Python libraries are now available in MATLAB (since 2014b). We can run code directly in MATLAB if we are using version 2014b or later.This makes it possible to use python modules in MATLAB. Without any other changes, just prefix ‘py’ before the python library name you want to use. Let us use the Python calendar module as an example.py.calendar.isleap(2016); py.calendar.isleap(2017);OUTPUTans =1 ans = 0To run our own function, we can create a file in our current MATLAB working directory. Let’s say we created a file called ‘hello.py’ that contains these two lines:def world():     return 'hello world';#  In ... Read More

How we can store Python functions in a Sqlite table?

Rajendra Dharmkar
Updated on 13-Feb-2020 06:59:23

143 Views

In the following code, we import sqlite3 module and establish a database connection. We create a table and then insert data and retrieve information from the sqlite3 database and close the connection finally.Example#sqlitedemo.py import sqlite3 from employee import employee conn = sqlite3.connect('employee.db') c=conn.cursor() c.execute(‘’’CREATE TABLE employee(first text, last text, pay integer)’’’) emp_1 = employee('John', 'Doe', 50000 ) emp_2 = employee('Jane', 'Doe', 60000) emp_3 = employee('James', 'Dell', 80000) c.execute(‘’’INSERT INTO employee VALUES(:first, :last,   :pay)’’’, {'first':emp_1.first, 'last':emp_1.last, 'pay':emp_1.pay}) c.execute(‘’’INSERT INTO employee VALUES(:first, :last, :pay)’’’, {'first':emp_2.first, 'last':emp_2.last, 'pay':emp_2.pay}) c.execute(‘’’INSERT INTO employee VALUES(:first, :last, :pay)’’’, {'first':emp_3.first, 'last':emp_3.last, 'pay':emp_3.pay}) c.execute("SELECT * FROM employee WHERE ... Read More

How to pass a json object as a parameter to a python function?

Rajendra Dharmkar
Updated on 13-Feb-2020 06:58:27

8K+ Views

We have this code below which will the given json object as a parameter to a python function.exampleimport json json_string = '{"name":"Rupert", "age": 25, "desig":"developer"}' print type (json_string) def func(strng):     a =json.loads(strng)     print type(a)     for k,v in a.iteritems():            print k,v     print dict(a)       func(json_string) Output desig developer age 25 name Rupert {u'desig': u'developer', u'age': 25, u'name': u'Rupert'}

How to return a json object from a Python function?

Rajendra Dharmkar
Updated on 13-Feb-2020 06:57:35

1K+ Views

We return a json object from a python function as follows using given python dictionary.Exampleimport json a = {'name':'Sarah', 'age': 24, 'isEmployed': True } # a python dictionary def retjson(): python2json = json.dumps(a) print python2json retjson()Output{"age": 24, "isEmployed": true, "name": "Sarah"}

Advertisements