Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,224 members, 7,818,765 topics. Date: Monday, 06 May 2024 at 01:14 AM

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

Nairaland Forum / Science/Technology / Programming / Common good python programming practices you should know (12721 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): 9:44pm On Jun 18, 2020
iCode2:
Oh I just checked again now. I misunderstood the question. I was working on returning an item in the list as a string separated by comma with an and before the last item. Something like... Returning the first index as 'a, p, p, l, e, and s'.

Will that work?
Sure it will work
Re: Common good python programming practices you should know by gbolly1151(m): 9:59pm On Jun 18, 2020
iCode2:
Oh I just checked again now. I misunderstood the question. I was working on returning an item in the list as a string separated by comma with an and before the last item. Something like... Returning the first index as 'a, p, p, l, e, and s'.

Will that work?
Dont mind my naming

spam = ['apples', 'bananas', 'tofu', 'cats']

def printlist(List):
last=List.pop()
last=' and '+last
List.append(last)
return ','.join(List)

def wordlist(List):
for word in List:
print(printlist(list(word)))


wordlist(spam)
Re: Common good python programming practices you should know by iCode2: 10:15pm On Jun 18, 2020
gbolly1151:

Dont mind my naming

spam = ['apples', 'bananas', 'tofu', 'cats']

def printlist(List):
last=List.pop()
last=' and '+last
List.append(last)
return ','.join(List)

def wordlist(List):
for word in List:
print(printlist(list(word)))


wordlist(spam)

Hmmmm you've so grabbed Python concept. I hope to be like you when I grow up.
Re: Common good python programming practices you should know by gbolly1151(m): 7:35am On Jun 19, 2020
iCode2:
Hmmmm you've so grabbed Python concept. I hope to be like you when I grow up.
It is not about the language, it is about data structure and algorithm sir
Re: Common good python programming practices you should know by iCode2: 9:12am On Jun 19, 2020
gbolly1151:

It is not about the language, it is about data structure and algorithm sir
Did you take any course on that or you got to understand it over time?

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 1:23pm On Jun 19, 2020
iCode2:
Did you take any course on that or you got to understand it over time?
No course just pdf
You can download this pdf Data Structures and Algorithms in Python by Michael T. Goodrich

3 Likes

Re: Common good python programming practices you should know by Predstan: 2:45pm On Jun 19, 2020
gbolly1151:

No course just pdf
You can download this pdf Data Structures and Algorithms in Python by Michael T. Goodrich

I am using one by Rance D. Necaise. Do you have the link to the pdf?
Re: Common good python programming practices you should know by gbolly1151(m): 3:49pm On Jun 19, 2020
Predstan:


I am using one by Rance D. Necaise. Do you have the link to the pdf?

It should be first on Google search sir
Re: Common good python programming practices you should know by Predstan: 3:55pm On Jun 19, 2020
gbolly1151:


It should be first on Google search sir

Keeps directing me to buy the book. I dont know if its because of my Location
Re: Common good python programming practices you should know by iCode2: 5:32pm On Jun 19, 2020
gbolly1151:

No course just pdf
You can download this pdf Data Structures and Algorithms in Python by Michael T. Goodrich
Okay thanks. Which area do you major? Web dev or data science?
Re: Common good python programming practices you should know by gbolly1151(m): 6:08pm On Jun 19, 2020
Predstan:


Keeps directing me to buy the book. I dont know if its because of my Location

Sorry bro...i should have sent the link

https://www.google.com/url?sa=t&source=web&rct=j&url=http://predmet.singidunum.ac.rs/pluginfile.php/14584/mod_folder/content/0/Data%2520Structures%2520and%2520Algorithms%2520in%2520Python%2520%255BGoodrich%252C%2520Tamassia%2520%2520Goldwasser%25202013-03-18%255D.pdf%3Fforcedownload%3D1&ved=2ahUKEwiqvev2rY7qAhXS2aQKHYGzDeoQFjAAegQIBhAB&usg=AOvVaw0_J9ADcYtLK-LBzI7uQkuW


Or search for

Data Structures and Algorithms in Python Michael T. Goodrich Department of Computer Science University of California, Irvine Roberto Tamassia Department of Computer Science Brown University Michael H. Goldwasser Department of Mathematics and Computer Science Saint Louis University pdf
Re: Common good python programming practices you should know by gbolly1151(m): 6:11pm On Jun 19, 2020
iCode2:
Okay thanks. Which area do you major? Web dev or data science?

I really want to specialize in software development (in Blockchain space)

1 Like

Re: Common good python programming practices you should know by Predstan: 6:19pm On Jun 19, 2020
gbolly1151:


Sorry bro...i should have sent the link

https://www.google.com/url?sa=t&source=web&rct=j&url=http://predmet.singidunum.ac.rs/pluginfile.php/14584/mod_folder/content/0/Data%2520Structures%2520and%2520Algorithms%2520in%2520Python%2520%255BGoodrich%252C%2520Tamassia%2520%2520Goldwasser%25202013-03-18%255D.pdf%3Fforcedownload%3D1&ved=2ahUKEwiqvev2rY7qAhXS2aQKHYGzDeoQFjAAegQIBhAB&usg=AOvVaw0_J9ADcYtLK-LBzI7uQkuW


Or search for

Data Structures and Algorithms in Python Michael T. Goodrich Department of Computer Science University of California, Irvine Roberto Tamassia Department of Computer Science Brown University Michael H. Goldwasser Department of Mathematics and Computer Science Saint Louis University pdf

Thanks Boss.. This is Okay
Re: Common good python programming practices you should know by iCode2: 8:44pm On Jun 19, 2020
gbolly1151:


I really want to specialize in software development (in Blockchain space)
Nice! You're set for it.

1 Like

Re: Common good python programming practices you should know by gbolly1151(m): 8:50pm On Jun 19, 2020
iCode2:
Nice! You're set for it.
Not fully set,but moving closer

1 Like

Re: Common good python programming practices you should know by rastaxarm(m): 3:17am On Jun 21, 2020
iCode2:
spam = ['apples', 'bananas', 'tofu', 'cats']

Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with and inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list value passed to it.


def join_list(items) :
return ",".join(items)


print(join_list(spam))
Re: Common good python programming practices you should know by rastaxarm(m): 3:20am On Jun 21, 2020

Re: Common good python programming practices you should know by gbolly1151(m): 3:36pm On Jun 21, 2020
REMINDER: bool of empty string is False and bool of
any string or character is True
'''

x=''
y='hello'
print('bool of x is ',bool(x)) #output: False
print('bool of y is ',bool(y)) #output: True
Re: Common good python programming practices you should know by gbolly1151(m): 2:01pm On Jun 26, 2020
How To Use Index Method In List

To find the first position of a particular element in a list,index
method get you covered;

the syntax is
list.index(element [,start[,end]]) (start and end are optional)
'''

fruits = ['banana','orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
#let get first position of banana
print(fruits.index('banana')) #output: 0

#To specify where searching to begin,add optional arguement start position

print(fruits.index('banana',5)) #output: 7

# The searching start from kiwi i.e fruits[5:]

#you can also specify where searching should stop

print(fruits.index('banana',1,5)) #output:4

#here searching begin at position 1 (orange) and end at position 5(kiwi)
Re: Common good python programming practices you should know by gbolly1151(m): 8:49pm On Jun 27, 2020
What is sentinel?

Sentinel in programming is a value that help to stop the execution of a sequence.

E.g

age=1

while age > 0:
age=input('enter your age:')
print('your age is ',age)
Re: Common good python programming practices you should know by gbolly1151(m): 10:14pm On Jun 30, 2020
TYPICAL MICRO BUG YOU MUST AVOID IN PYTHON

There is often hidden bug that most begginers
do encounter when using conditional statement

example

sex='F'
if sex == 'M' or 'm':
print('Male')
else:
print('Female')

#ouput : Male

"""
hmm...but why is the output Male? This is how python evaluate the
if statement above.

it evaluate from left to right starting with

sex == 'M' which return False,then evaluate the
result with next condition,

False or 'm' which is True,

if you are worried how we evaluate bool and str, here
is how it works bool('m') return True,so in real sense
we are evaluating False or True which make us arrive
at True,now sex == 'M' or 'm' result to True which
make code under if triggered. the way python see above
code is this

sex = 'F'
if True:
print('Male')
else:
print('Female')



to correct the bug, just rewrite the code this way"""

sex='F'

if sex == 'M' or sex == 'm':
print('Male')
else:
print('Female')

#output: Female
Re: Common good python programming practices you should know by gbolly1151(m): 9:23am On Jul 01, 2020
ACCESS CLASS ATTRIBUTE IN FEW LINES OF CODE USING VARS()

Let assume you have class profile and its attributes,
you can access them in two lines of code compare compare
to what we know before

example:

'''

class Profile:
def __init__(self,name,age,sex,nationality):
self.name=name
self.age=age
self.sex=sex
self.nationality= nationality


obj=Profile('sam',20,'M','Nigeria')
#it is boring to access each attribute using attribute name like this
print(obj.name)
print(obj.age)
print(obj.sex)
print(obj.nationality,'\n')

'''
output:
sam
20
M
Nigeria

problem with that approch is that,it is boring
to update and write for large attribute,the lines of
code to use is equal to number of attributes
'''

# A fast approach is using vars()

for key,value in vars(obj).items():
print(value)

'''
output:
sam
20
M
Nigeria

wow we achieve same result in just two lines of code
regardeless of the number of attributes

Note: side effect of this approch is that,it is unordered
'''
Re: Common good python programming practices you should know by gbolly1151(m): 7:57pm On Jul 02, 2020
DO YOU KNOW THAT else KEYWORD WORKS WITH while AND
for LOOP?

the purpose of else statement in for and while loop
is to get executed when loop ended without break
statement

example1
this for loop statement end with the help of break so
else statment wont be excecuted

for i in range(1,5):
print(i)
if i == 4: break
else:
print('hi')

output:
1
2
3
4

example2
this for loop statement end without the help of
break,so else statement get executed

for i in range(1,5):
print(i)
else:
print('hi')

output:
1
2
3
4
hi

example3
using while loop

start=1
while True:
print(start)
start += 1
if start == 5: break
else:
print('hi')


output:
1
2
3
4

start=1
while start < 5:
print(start)
start += 1
else:
print('hi')

output:
1
2
3
4
hi
Re: Common good python programming practices you should know by gbolly1151(m): 9:21am On Jul 06, 2020
HOW TO USE hasattr,getattr AND setattr
>>hasattr is to check if a particular object/class has a
particular attribute.
syntax hasattr(obj,attribute_name), it return True or false

>>getattr is use to get the value of an object(function,variable,class and other object),
if available else it return AttributeError
syntax is getattr(obj,attribute_name)

>>setattr is used to set the attribute of an object
syntax is setattr(obj,attribute_name,value)


Example:
class Person:
p=locals()
def __init__(self,fname,lname,age):
self.fname=fname
self.lname=lname
self.age=age

def fullname(self):
return '{0} {1}'.format(self.fname,self.lname)

Bob=Person('bob','alex',20)
print(hasattr(Bob,'fname')) #return True
print(hasattr(Bob,'lname')) #return True
print(hasattr(Bob,'fullname')) #return True
print(hasattr(Bob,'age')) #return True
print(hasattr(Bob,'DOB')) #return False

print(getattr(Bob,'lname')) #same as Bob.lname return alex
print(getattr(Bob,'fullname')) #return function object like <bound object....at 0xefbad> same as Bob.fullname
print(getattr(Person,'fullname')) #same as Person.fullname

setattr(Bob,'age',40) #same as bob.age=40
print(Bob.age) #return 40
Re: Common good python programming practices you should know by gbolly1151(m): 11:37am On Jul 11, 2020
KEY DIFFERENT BETWEEN return AND yield IN PYTHON

Return - this keyword terminate a function
Yield - pause the execution of a function
Re: Common good python programming practices you should know by gbolly1151(m): 2:37pm On Jul 12, 2020
CHECK OUT THIS PYTHON FLOW


l=[2]
l.append(l.append(1))
print(l)
#TRY GUESSING.....
#output: [2,1,None]

'''
WHY None?
reason behind this output is that
append() is a method that only add value at the
end of the list,so it does not have return value.
By default,None is returned if you dont specify
return value in a function

e.g
'''
def fun():
v=5

print(fun()) #output: None

'''
so we can break it like this
'''
l=[2]
v=l.append(1) # v = None
l.append(v)
print(l) #output: [2,1,None]
Re: Common good python programming practices you should know by gbolly1151(m): 1:49pm On Jul 19, 2020

#EXAMPLE OF MISTAKE YOU MUST AVOID AS A BEGINNER USING PYTHON

print('example 1',1 is (not None)) # return False
print('example 2',1 is not None) # return True

'''
Before i explain why both statement return different value,Remenber that
'is' keyword in python is used to check if two objects have
the same id() and Note that, it is different from ==
which check if two objects have the same value

now let break down example 1;
1 is (not None)
(not None) in python will return True and
1 is True will return false because
1 and True represent different objects store with different id()
'''
print(not None) #return True

'''
Now example 2, 1 is not None
this check if id(1) is not id(None) and the answer
is True
'''
print(id(1),id(None))
Re: Common good python programming practices you should know by gbolly1151(m): 7:25am On Aug 11, 2020
Quite an age here
Re: Common good python programming practices you should know by Predstan: 3:39am On Aug 12, 2020
gbolly1151:
Quite an age here
Yeah, where have you been? I don day use tensorflow
Re: Common good python programming practices you should know by gbolly1151(m): 4:20am On Aug 12, 2020
Predstan:

Yeah, where have you been? I don day use tensorflow
Wao!!!...that is cool bro,keep moving
Re: Common good python programming practices you should know by gbolly1151(m): 7:39pm On Oct 14, 2020
It been a while here

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

Can You Survive If You Stopped Working In Tech? / How Do You Overcome Laziness And Dizziness When Working / Dr. Chinedu Emeka Invents Computer Software To Track Criminals

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