Welcome, Guest: Join Nairaland / LOGIN! / Trending / Recent / New
Stats: 2,444,047 members, 5,502,903 topics. Date: Wednesday, 01 April 2020 at 03:24 AM

Common good python programming practices you should know - Programming (2) - Nairaland

Nairaland Forum / Science/Technology / Programming / Common good python programming practices you should know (2425 Views)

A Thread For Tutorial On Python Programming / A Very Good Python Programmer Needed Asap / Recommend A Good Python Data Mining Book (2) (3) (4)

(1) (2) (Reply) (Go Down)

Re: Common good python programming practices you should know by gbolly1151(m): 12:39pm On Jan 01


print('happy new year')

Re: Common good python programming practices you should know by gbolly1151(m): 8:10am On Jan 07

#controlling print function
a='hello'
b='world'

print(a)
print(b)

#output
hello
world

#To remove newline

print(a,end=(' '))
print(b)

#output
hello world
Re: Common good python programming practices you should know by gbolly1151(m): 7:12pm On Jan 08





'''I want us to know that python is object oriented programming (OOP)
languague, all data type is as a result of creation of object from their respective
classes e.g int datatype can be worked on this way'''

a=int(5)
b=int(-6)

print("a-b=",a.__sub__(b)) #subtaction method of int class which mean a-b

print("b-a=",a.__rsub__(b)) #mean start operation from right side

print("a+b=",a.__add__(b)) #addition method of int class just like __sub__

print("b+a=",a.__radd__(b))

print("a*b=",a.__mul__(b)) #multiplication method of int class

''' To emulate above behaviour in our own way,
we will define our own class
'''

class myclass:
def __init__(self,x):
self.value=x

def __add__(self,other): #overriding addition method of int claas
return self.value + other.value

def __sub__(self,other): #overriding substration method of init class
return self.value - other.value

c=myclass(9)
d=myclass(10)

#normally using operantors (+,-,/) on our class objects will create error
#but we have overrided + and - operantors only so that these operantors
#can work on our class we defined
#note that /, * and other operantors wont work because we didnt
#override those operantors.To make them work just create new method
#like + and - operators

print('c+d =',c+d)
print('c-d=',c-d)
print('c*d=',c*d) # this will throw error

Re: Common good python programming practices you should know by gbolly1151(m): 12:32pm On Jan 13

#How to format your class output using __str__ method
class myclass:
def __init__(self):
pass

def __str__(self):
return 'my name is class'

print(myclass())

Output:
my name is class


#without __str__ method

class myclass:
def __init__(self):
pass

print(myclass())

Output:
<__main__.myclass object at oxbchjlidk>

Re: Common good python programming practices you should know by gbolly1151(m): 8:29pm On Feb 03
Wanna quickly drop this:

NAMING IN PYTHON ACCORDING TO PEP
-To name a class,start with Capital letters (preferably a noun). if multiple words,use CamelCase e.g class PersonalData

-To name a function start with small letters (preferably a verb,demonstrating the kind of action the function perform). if multiple words, use underscore e.g
def get_name

-parameters of class or function should be in small letters

-If constant variables are in your program,indicate the name in capital letters and use underscore if multiple words e.g PADDING_NUM
Re: Common good python programming practices you should know by gbolly1151(m): 9:06am On Mar 21
It been a while here,school has kept me busy for a while but with this coronavirus holiday let see what we can learn
Re: Common good python programming practices you should know by gbolly1151(m): 9:48am On Mar 21
What are private and protected variable?

Java programmers must understand those two keywords but for python programmer let me quickly explain them and how you can implement them in python.

Private variable are variable that can only be called within the class scope, a call from outside will throw an error

Protected variable are variable that can be called by the class and subclasses only.

In python,protected variable definition is not true but normal convention of creating it, is to start variable name with single underscore (e.g _name). Loophole we have in python is that this single underscore variable can be called from anywhere unlike java and c++ in which protected variable name can only be called by class and subclasses.

The private variable can be created using double underscore (e.g __name) and it is the one that work well with the definition in python.it can only be class within the class or function that create the variable


#protected variable example
class MyData:
'''program for personal data

name name
'''
def __init__(self,name):
self._name=name

def get_name(self):
return self._name

d=MyData('gbolly')

#this is a protected variable in python with single underscore
#calling _name attribute outside class scope will work

print(d._name)

Output: gbolly



#private variable example
class MyData:
'''program for personal data

name name
'''
def __init__(self,name):
self.__name=name

def get_name(self):
return self.__name

d=MyData('gbolly')

#this is a private variable in python with double underscore
#calling __name attribute will not work outside the class scope

print(d.__name)

Output: <'MyData' object has no attributes __name>


#to access your private member
class MyData:
'''program for personal data

name name
'''
def __init__(self,name):
self.__name=name

def get_name(self):
return self.__name

d=MyData('gbolly')

#call using a function of the class scope works

print(d.get_name())

Output: gbolly



This protected and private variable are used to hid the internal working of your code sometime from users.
Re: Common good python programming practices you should know by yemyke001(m): 9:59pm On Mar 21
Weldone boss.. Please we await more of your tutelage. It's really making sense!

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 10:49pm On Mar 21
yemyke001:
Weldone boss.. Please we await more of your tutelage. It's really making sense!

Thanks boss for the compliment... I will always do my best

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 9:32am On Mar 24
Good morning

To become a good programmer is not about knowing syntax is about how you structure your data and low time execution of your algorithm on large input, so continue mastering data structure and algorithm to become a good programmer
Re: Common good python programming practices you should know by scarplanet(m): 11:22am On Mar 24
When you can handle functions and classes effectively, only then can you say you have made great strides in Python.

Learn as much Python libraries as you can. Libraries can improve your algorithm's time and space complexity

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 6:45pm On Mar 24
Guys here is a little project i just play with using django as backend and bootstrap as frontend

/mydemoapp12345.herokuapp.com/ remove first and last slash
Re: Common good python programming practices you should know by gbolly1151(m): 11:28pm On Mar 27
Recursion is quite tricky and most programmer find it difficult to understand, in this post am going to try all my possible best to simplify the logic of this term.

Recursion in programming is a way of a function to call itself in its own function

#Example 1

def add(n):
return add(n-1)

Note: that if you initialize the function,you will end up with error,i will tell you why later

example 1 above is a recursion because the function add call itself (i.e add(n-1)) inside it own function.

If you run add(4) here is explanation on how it going to run:

1.when add(4) call get to return,it will call add(4-1) i.e add(3).
since add(4) return is calling a function add(3), it will wait still the function add(3) finish execution

2.add(3) will run still it get to line with return where it going to call (add(3-1)) i.e add(2). add(3) will Wait still add(2) finish execution too

3. add(2) will run until it get to return where it call add(2-1) i.e add(1), this let add(2) return to Wait for add(1) execution

4. This continue for add(0), add(-1), add(-2), add(-3) still recursive stack get filled up probably add(-496) where it throw error because that is the maximum call that can be made for recursive when it can't run further.

Then how are will going to control it? A way of controlling the call is through conditional statement.

IMPORTANT KEY TO KNOW IS THAT EVERY RECURSIVE FUNCTION MUST HAVE A CONDITION TO STOP THE CALL

Now let modify our example


Example 2
def add(n):
If n<=1:
return 1
return add(n-1)

print(add(4))

Output: 1


if n <= 1: return 1 ,will help us to stop add() call at n == 1

Here is how it will run

1.add(4) will call add(4-1) i.e add(3),which will call add(3-1) i.e add(2)

2.when getting a call for add(1),it will return 1 and no call is being made again

Now let modify our example to add numbers from 1 to n where n is positive integers


Example 3

def add(n):
If n<=1:
return 1
return n + add(n-1)

print(add(4))

Output: 10


Here is what happen behind the scene

1. add(4) return 4 + add(4-1) i.e add(3) output is 4 + add(3)
2. add(3) call return 3 + add(3-1) i.e add(2) output is 3 + add(2)
3. add(2) call return 2 + add(2-1) i.e add(1) output is 2 + add(1)
4. add(1) call return 1

Technically add(4) wait till there is no call i.e when n <= 1 which stop the call

Now add(4) call return 4 + 3 + 2 + 1 = 10

This bring us to the end of recursion, try to read again and digest then start building on it....if you have any question just drop them.
Re: Common good python programming practices you should know by gbolly1151(m): 8:42pm On Mar 31
HOW TO CHECK RUNNING TIME OF YOUR SCRIPT
After writing a long script, it is a good practice to check the running time of your script with numbers of input for optimization. There is a module in python for this purpose called cProfile, so let write some code and check the running time


import cProfile

def counter():
count=0
for count in range(10000):
count+=1
return count

if __name__== "__main__" :
cProfile.run("counter()" )



Check the output in the pic below


let define those column

ncalls : numbers of calls made by the function
tottime : total time taken for the function to excecute
percall : tottime/ncall
cumtime : commulative time for all the calls made on the function
percall : quotient of cumtime divided by primitive calls
filename lineno(function) : filename is the name of the file(eg test.py), lineno(eg
lineno for import cProfile is 7), function is the name of function

1 Share

Re: Common good python programming practices you should know by Grandlord: 9:28pm On Mar 31
gbolly1151:
[b]HOW TO CHECK RUNNING TIME OF YOUR SCRIPT[\b]
After writing a long script, it is a good practice to check the running time of your script with numbers of input for optimization. There is a module in python for this purpose called cProfile, so let write some code and check the running time


import cProfile

def counter():
count=0
for count in range(10000):
count+=1
return count

if __name__== "__main__" :
cProfile.run("counter()" )



Check the output in the pic below


let define those column

ncalls : numbers of calls made by the function
tottime : total time taken for the function to excecute
percall : tottime/ncall
cumtime : commulative time for all the calls made on the function
percall : quotient of cumtime divided by primitive calls
filename lineno(function) : filename is the name of the file(eg test.py), lineno(eg
lineno for import cProfile is 7), function is the name of function


Nice one.

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 11:37pm On Mar 31
Let me quickly drop


d = str.maketrans({'a':'1', 'b':'2'})
print('abaab'.translate(d))

The result is '12112'.

(1) (2) (Reply)

God as a Computer Programmer <joke> / Please Help. How To Create A Database For A Car Rental / Get Free Wordpress Website + Free Domain Name + Free Hosting For A Year

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2020 Oluwaseun Osewa. All rights reserved. See How To Advertise. 188
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.