Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,150,547 members, 7,809,008 topics. Date: Thursday, 25 April 2024 at 09:03 PM

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

Nairaland Forum / Science/Technology / Programming / Common good python programming practices you should know (12655 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): 2:04am On Apr 18, 2020
When you use return keyword,it actually return a value and STOP the function, therefore if you have two return keywords in a function only one will work based on the condition usually if/else statement. therefore avoid use of if/else statment this way

#avoid this
def isodd(num):
if num%2==1:
return True
else: return False

#use this
def isodd(num):
if num%2==1:
return True
return False


Re: Common good python programming practices you should know by gbolly1151(m): 2:15am On Apr 18, 2020
For anyone interested in learning python from scratch you can pm me on 07060435624

hourly payment based,so you can quickly option out.
Re: Common good python programming practices you should know by gbolly1151(m): 10:25pm On Apr 19, 2020
HOW TO WORK WITH FILE

#avoid opening file this way
file=open('myfile.txt','r')
file.close()

#you might forgot to close the file which means operation can be done
#inside the file

#use this
with open('myfile.txt','r') as file:
#do something

#the indentation cover you up and no need to worry about closing the file

Re: Common good python programming practices you should know by Predstan: 10:55pm On Apr 19, 2020
gbolly1151:
I have started another thread,you can follow

Tutorial: Object Oriented Programming Paradigm For Beginners


Link
Re: Common good python programming practices you should know by gbolly1151(m): 12:04am On Apr 20, 2020
Re: Common good python programming practices you should know by gbolly1151(m): 2:50pm On Apr 20, 2020
ALWAYS CREATE VIRTUAL ENVIRONMENT FOR YOUR PROJECT

Virtual Environment is a an isolated environment from the main environment.Each projects in one way or the other will depend on external package,that need to be install before use.

If all packages for projects A and project B are downloaded in the same environment, it will be really difficult to manage when it is time to deploy. To manage your project dependency,virtual environment can handle the task for you where each projects will operate in different environment and there wont be any headache when need for obtaining information about dependency for each projects

To get started open your Command line and install virtualenv

#install the virtual environment
pip install virtualenv

#create directory for your project
mkdir projectA

#open the directory
cd project A

#create your virtual environment
#env - is the name you wish to give your environment
python3 -m venv projectAenv

#myprojectAenv directory will be created inside projectA dir

#now i have to activate the environment so that i can be working
#from the environment

projectAenv/bin/activate

#something like below will show which indicate the environment myprojectAenv
#has been activated
(myprojectAenv)

#minimize and start working on projectA
#To install dependency for projectA,come back to command prompt
#ensure that your environment for projectA is activated by looking at
#in our case (myprojectAenv) is our virtual environment for projectA
#so let install numpy package for projectA

(projectAenv) pip install numpy

#To test your installation
Python
>> import numpy
>>
#if no error it means installation is successful in projectA environment

#to deactivate the environment

(projectAenv) deactivate

#if you now import numpy after you deactivate the environment error will show
#because you are in new environment, i.e main environment




You can create many environment as many as you like,just know the project they are working for,the name you give the env can help.

1 Like 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 3:31pm On Apr 22, 2020

#To glance through a moudle and check availability method use this function
#dir(name of module) e.g dir(list)
print(dir(list))


You can also import a module and check the method available


import os
print(dir(os))


To check how to use a function use help() eg help(list.append)

Re: Common good python programming practices you should know by gbolly1151(m): 9:42am On Apr 23, 2020
How to setup dictionary with default value
Let say you have a list of players and want to create a script to count their goals.

The first action is to set their goal to default value 0 and keep up updating

As a coder,what will come to your mind to create dictionary with default value 0 is iterate the list


#naive approach
players=['messi','Ronaldo','ighalo']
goals={}
for player in players:
goals[player]=0

print('Goals:',goals)

Output:
Goals : {'messi':0, 'ighalo':0, 'Ronaldo':0}


#fast approach

players=['messi','Ronaldo','ighalo']
goals=dict.fromkeys(players,0) #dict.fromkeys(iterable-object,default-value)

print('Goals:'goals)

Output:
Goals : {'messi':0, 'ighalo':0, 'Ronaldo':0}



1 Like 1 Share

Re: Common good python programming practices you should know by gbolly1151(m): 6:36pm On Apr 24, 2020
Hi guys, if you are interested in learning python checkout for details here

https://www.nairaland.com/5814602/learn-python-programming-affordable-price#88811892
Re: Common good python programming practices you should know by gbolly1151(m): 7:41pm On Apr 24, 2020
Example on how to use filter,lambda and dict to output highest goal scorer


scores={'messi':3,'Ronaldo':1,'ighalo':2,'Giroud':7,'kane':7}

def Highest_goal_scorer(scores):
goal=max(scores.values()) #highest goal
scorer_filter=filter(lambda player:scores[player] == goal,scores) #filter highest
scorer=[player for player in scorer_filter ]
return scorer
print(Highest_goal_scorer(scores))

Output:
['kane','Giroud']
Re: Common good python programming practices you should know by gbolly1151(m): 6:37pm On Apr 25, 2020
HOW TO ASSIGN ANY FUNCTION TASK TO A VARIABLE
This is the basics learning of decorator,you need to understand
that you can assign a task to another variable,example
let assign print function to another variable

var=print
var('hello world')

Output:
hello world

In example above,we are assigning the power of print to var no more no less and that is the main trick behind a decorator
Re: Common good python programming practices you should know by gbolly1151(m): 7:40pm On Apr 25, 2020
You can join my Facebook page @

https://m./2604470076495701
Re: Common good python programming practices you should know by scarplanet(m): 9:11pm On Apr 25, 2020
Well done chief

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 9:22pm On Apr 25, 2020
scarplanet:
Well done chief
Thanks sir
Re: Common good python programming practices you should know by gbolly1151(m): 12:06pm On Apr 30, 2020
HOW TO CHECK FOR EVEN AND ODD NUM IN 2 LINES OF CODE

num=int(input('your num '))
print('even' if (bin(num)).endswith('0') else 'odd')
Re: Common good python programming practices you should know by gbolly1151(m): 2:36pm On May 02, 2020
gbolly1151:
You can join my Facebook page @

https://m./2604470076495701

I dont really understand why Nairaland is keeping me on and off these days, while am still here you can join me my Facebook page...
Re: Common good python programming practices you should know by gbolly1151(m): 2:43pm On May 02, 2020
A SIMPLE DIFFERENCE BETWEEN repr() and str()


string='hello\nword' #note the special character \n

print('str format is')
print(str(string))
print('repr format is')
print(repr(string))

output:

str format is
>>hello
>>word

repr format is
>>'hello\nword'
Re: Common good python programming practices you should know by gbolly1151(m): 7:31pm On May 02, 2020
HOW TO USE GLOBALS() AND LOCALS() FUNCTION
In programming we have two types of variable namely:
1. Global variable
2. Local variable

Before we dive into those two varibles,you need to understand
that all your variable name and value in python are stored
in a dict data structure e.g


value=1
Good=True

the way python present this is,

{'value':1,'Good':True}


#Then how can we checked this structure? just use
print(globals())

output will be

{'__builtins__': <module 'builtins' (built-in)>,
'__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py',
'value': 1,'Good':True '__package__': None,
'__cached__': None, '__name__': '__main__', '__doc__': None}

you can see that your variables are stored in dict structure
'value':1 and 'Good':True

To get value use

print(globals()['value'])
output
1

for now dont mind other variables you saw in the global scope,they are needed for your program to work well

All variable that can be obtained through globals() are called global variable.These are variables that are in
__main__ i.e global enviroment of the program

Now let talk about local variable....

All variable you create after indentation,they are all
local variable example of structure that use indentation are
function,class,with ,if else et.c . Let check this;


def increment():
fund=36
return True


variable name 'fund' is written after an indentation,which is
local variable of increment function,this means only increment
has the power to perform operation on fund . To check and
print the local variable just use keyword locals() and
all local variable will be displayed


def increment():
fund=36
return locals()

print(increment())

output

{'fund': 36}


Let take a break from here and continue with global and nonlocal keyword later
Re: Common good python programming practices you should know by gbolly1151(m): 6:36am On May 07, 2020
I don't understand why nairaland is deleting my post please help ooo
Re: Common good python programming practices you should know by gbolly1151(m): 8:07pm On May 09, 2020
gbolly1151:

HOW TO USE GLOBALS() AND LOCALS() FUNCTION
In programming we have two types of variable namely:
1. Global variable
2. Local variable

Before we dive into those two varibles,you need to understand
that all your variable name and value in python are stored
in a dict data structure e.g


value=1
Good=True

the way python present this is,

{'value':1,'Good':True}


#Then how can we checked this structure? just use
print(globals())

output will be

{'__builtins__': <module 'builtins' (built-in)>,
'__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py',
'value': 1,'Good':True '__package__': None,
'__cached__': None, '__name__': '__main__', '__doc__': None}

you can see that your variables are stored in dict structure
'value':1 and 'Good':True

To get value use

print(globals()['value'])
output
1

for now dont mind other variables you saw in the global scope,they are needed for your program to work well

All variable that can be obtained through globals() are called global variable.These are variables that are in
__main__ i.e global enviroment of the program

Now let talk about local variable....

All variable you create after indentation,they are all
local variable example of structure that use indentation are
function,class,with ,if else et.c . Let check this;


def increment():
fund=36
return True


variable name 'fund' is written after an indentation,which is
local variable of increment function,this means only increment
has the power to perform operation on fund . To check and
print the local variable just use keyword locals() and
all local variable will be displayed


def increment():
fund=36
return locals()

print(increment())

output

{'fund': 36}


Let take a break from here and continue with global and nonlocal keyword later
Alteratively, you can use vars() to get your key and data
Re: Common good python programming practices you should know by gbolly1151(m): 9:43am On May 10, 2020
IF YOU ARE CONFUSED ABOUT WHILE LOOP CHECK THIS OUT

n=True
while n==True:
print('hello')

it means you are telling the computer that as long as n value isTrue(n=True) continue printing 'hello' for me

Hope you can take it from there
Re: Common good python programming practices you should know by Predstan: 9:51am On May 10, 2020
gbolly1151:
IF YOU ARE CONFUSED ABOUT WHILE LOOP CHECK THIS OUT

n=True
while n==True:
print('hello')

it means you are telling the computer that as long as n value isTrue(n=True) continue printing 'hello' for me

Hope you can take it from there

Finally learnt OOP on LinkedIn learning (lynda)

I got some Covid-19 data for every countries and I will be visualizing some stuffs.
Re: Common good python programming practices you should know by gbolly1151(m): 11:49am On May 10, 2020
Predstan:


Finally learnt OOP on LinkedIn learning (lynda)

I got some Covid-19 data for every countries and I will be visualizing some stuffs.

Nice one bro
Re: Common good python programming practices you should know by Hotspotbro(m): 11:55am On May 10, 2020
Pls i want to know if there is a Android game package based on python.
Re: Common good python programming practices you should know by gbolly1151(m): 3:17pm On May 10, 2020
Hotspotbro:
Pls i want to know if there is a Android game package based on python.
To build android app with python use kivy
Re: Common good python programming practices you should know by Hotspotbro(m): 7:35pm On May 10, 2020
gbolly1151:

To build android app with python use kivy
kivy on Pydroid
Can you just give me a sample code?
Re: Common good python programming practices you should know by Nobody: 9:14pm On May 10, 2020
Good thread cool

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 4:50am On May 11, 2020
Hotspotbro:
kivy on Pydroid
Can you just give me a sample code?

from kivy.app import App
from kivy.uix.button import Button

class TestApp(App):
def build(self):
# display a button with the text : Hello QPython
return Button(text='Hello QPython')

TestApp().run()


Note that there is a documentation on how you can allow it to work on Andriod device

Go to google and search for kviy tutorial pdf or video to see how to compile your kivy python file to work with android,there are 2 or 3 ways to do that,you can pick the anyone you can easily grab
Re: Common good python programming practices you should know by gbolly1151(m): 4:51am On May 11, 2020
Antiausen:
Good thread cool
Thanks sir
Re: Common good python programming practices you should know by gbolly1151(m): 7:30am On May 11, 2020
ALWAYS USE .startswith() AND .endwith() FOR SLICING OF STRING
To aviod hardcoding of number into your code avoid the use of
slicing in your code and to compliance with PEP8

E.g to check if string "younger" start with 'you' use

word="younger"
if word.startswith('you'):
#do something
pass

#avoid this
if word[:3] == 'you':
#do something
pass

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

Can You Survive If You Stopped Working In Tech? / After 10days Of Coding With Html, Css And Javascript Forum4africa Is Ready / How Do You Overcome Laziness And Dizziness When Working

(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. 44
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.