Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,149,822 members, 7,806,310 topics. Date: Tuesday, 23 April 2024 at 02:33 PM

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

Nairaland Forum / Science/Technology / Programming / Common good python programming practices you should know (12648 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) (3) (4) (5) (6) (7) (8) (Reply) (Go Down)

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


print('happy new year')

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

#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, 2020





'''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, 2020

#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, 2020
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, 2020
It been a while here,school has kept me busy for a while but with this coronavirus holiday let see what we can learn

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 9:48am On Mar 21, 2020
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, 2020
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, 2020
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

2 Likes

Re: Common good python programming practices you should know by gbolly1151(m): 9:32am On Mar 24, 2020
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, 2020
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, 2020
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, 2020
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

#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 will be 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.

1 Like 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 8:42pm On Mar 31, 2020
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, 2020
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, 2020
Let me quickly drop


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

The result is '12112'.
Re: Common good python programming practices you should know by gbolly1151(m): 4:49pm On Apr 01, 2020
CONDITIONAL EXPRESSION
conditional expression help to assign a value to a variable based on a
given condition. the syntax is
var=expr1 if condition else expr2

This simply mean our var value will be expr1 if condition is True,else our
var value will be expr2


#example1: we are given a task to output if a number is positive or negative
#old code is

num=-10
def remark(num):
if num >= 0:
return 'positive'
return 'negative'

print(remark(num))

output= negative

#using short code with conditional expression

num= -10
remark='postive' if num >= 0 else 'negative'
print(remark)

#you can use this condition in any function directly too,so let use it in print #function
num= -10
print('postive' if num >= 0 else 'negative')
Re: Common good python programming practices you should know by gbolly1151(m): 6:27pm On Apr 02, 2020
TIP TO LEARN OOP
To master OBJECT ORIENTED PROGRAMMING (OOP) start with CLASS DIAGRAM in UNIFIED MODELING LANGUAGE (UML),it will really help to know relationship between classes and make code writing easy.

1 Like 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 5:31pm On Apr 04, 2020
iter() and next() KEYWORD

Iter() - is just used to make an object iterable,iterable objects
are use for forloop operation. this keyword call __iter__() method from the object, if not available then it throw error

next() - this keyword is use to access __next__() method of the object

inbuit data type that has this method are list,dictionary,set and tuple

With that you can make your class iterable e.g let create a data type that return
reverse of the any string


class String:
def __init__(self,string):
self.string=string
self.i=1

def __iter__(self):
return self

def __next__(self):
if abs(self.i) == len(self.string)+1 :
raise StopIteration
else:
value=self.string[-self.i]
self.i+=1
return value

for char in String('cat'):
print(char)

Output:
t
a
c


What happen behind the scene is this:
var=String('cat')
While True:
try:
Print(next(var))
except StopIteration:
break

'''var=String('cat')
s=iter(var)
print(next(s))
print(next(s))
print(next(s))'''

2 Likes 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 11:18pm On Apr 05, 2020
Difference between yield and return

i will explain generator before going into yeild and return;

generator is a class that help to transform any object to work with
iter() and next()

Now what are yield and return?
Both keywords are used in returning value from a function but in different ways,

yield
1) release a generator object that called iter() method i.e
(yield = return genertor(object).__iter__()) and also
2) pause a function(it keep the state of function),then resume action when next() is called


return only help to terminate a function and release a value.


'''

       
#example of yield
def counter():
for i in range(10):
yield i**2
obj=counter() #generator object is return and state is kept for next call using
# next()
print(next(obj))
print(next(obj))
print(next(obj))
print('end my next call here')

'''
Recall that iter() and next() are brain behind for loop,therefore
we can use for loop on obj since it is iterable
'''

print('starting new next call with forloop')
for i in obj:
print(i)


#example of return

def counter():
for i in range(10):
return i

returnobj=counter()
print('return obj is',returnobj) #only 0 will be return then function terminate

1 Share

Re: Common good python programming practices you should know by Nobody: 12:38pm On Apr 06, 2020
I don't even understand a thing from here.
Nnaa ehn
Re: Common good python programming practices you should know by gbolly1151(m): 7:06pm On Apr 06, 2020
locust:
I don't even understand a thing from here.
Nnaa ehn
Which part and are you just learning python?
Re: Common good python programming practices you should know by Nobody: 7:18pm On Apr 06, 2020
gbolly1151:

Which part and are you just learning python?

Confused on which one to learn first; Java, python, Django, c# and the rest. I'm a rookie.

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 9:05pm On Apr 06, 2020
locust:


Confused on which one to learn first; Java, python, Django, c# and the rest. I'm a rookie.

Those tips are advance anyway but i will advice you to pick up on one and learn,master it,then you can move on easily with other programing language.
Re: Common good python programming practices you should know by Playforkeeps(m): 8:39pm On Apr 08, 2020
What im about to share isnt necessary a Practice, think of it as a tip. And it is how to setup a simple file server in python to be accessed by any client in your LAN. All you have to do is cd into the Server root directory and run
<code> python3 -m http.server <code/>
that will start a server on default port 8000 and if thats not suitable for you, you can pass in a custom port as an argument to the command.

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 7:58am On Apr 09, 2020
Playforkeeps:
What im about to share isnt necessary a Practice, think of it as a tip. And it is how to setup a simple file server in python to be accessed by any client in your LAN. All you have to do is cd into the Server root directory and run
<code> python3 -m http.server <code/>
that will start a server on default port 8000 and if thats not suitable for you, you can pass in a custom port as an argument to the command.
Nice one
Re: Common good python programming practices you should know by Playforkeeps(m): 10:20am On Apr 09, 2020
gbolly1151:

Nice one
Thanks man, you’re doing a great job here man, we need more active Python/Django communities

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 12:24pm On Apr 09, 2020
Playforkeeps:

Thanks man, you’re doing a great job here man, we need more active Python/Django communities
True...i am hoping to create a Nigerian forum for it
Re: Common good python programming practices you should know by gbolly1151(m): 12:24pm On Apr 09, 2020
Try and Except keyword
This is a wonderful keyword for controlling error output in python.
for example:
on a norm,dividing a number by 0(zero) is mathematical error,so if
you try to divide 2//0 in python,an awful error will be printed out
like this below,which cant be easily understood by user.


Traceback (most recent call):
2//0
ZeroDivisionError: interger division or modulou by zero


using Try and except keyword, you can control the output and print
out your desire output

let create two functions for out zero division error;
1.with try and except
2.without try and except


def div1(num):
try:
num=100//num
return num
except ZeroDivisionError:
return "Oop! You can't divide by zero"

#let divide 100/0
print('\noutput from div1 is "{0}"\n\n '.format(div1(0)))


def div2(num):
num=100//num
return num

#let divide 100/0
print('output from div2 is\n')
print(div2(0))



below pic show that,div1() give a nice output to the console than div2()
thanks to try and except for the job

1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 3:15pm On Apr 09, 2020
Tip for learning software development
Pick up python design patterns and learn
Re: Common good python programming practices you should know by gbolly1151(m): 8:56pm On Apr 12, 2020
HOW TO GENERATE ENGLISH ALPHABET
The keyword for this task is chr() which take in number as argument and return equivalent character. E g chr(97) return 'a',with this we can generate our 26
English alphabet

alphabet=[chr(97+num) for num in range(26)]
print(''.join(alphabet))

Output: abcdefghijklmnopqrstuvwxyz


For capital letters start from 65

1 Like 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 7:38pm On Apr 14, 2020
I have started another thread,you can follow

Tutorial: Object Oriented Programming Paradigm For Beginners

(1) (2) (3) (4) (5) (6) (7) (8) (Reply)

CODELAGOS: 337 Schools To Participate In Coding Competition / Can You Survive If You Stopped Working In Tech? / After 10days Of Coding With Html, Css And Javascript Forum4africa Is Ready

(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 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 81
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.