Re: Common good python programming practices you should know by Brukx(m): 10:11am On May 11, 2020 |
gbolly1151:
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
Bro, can you recommend any good kivy book? |
Re: Common good python programming practices you should know by gbolly1151(m): 3:02pm On May 11, 2020 |
Brukx: Bro, can you recommend any good kivy book? I haven't try building mobile app before so don't know the best book out there but you can search for kivy tutorial on Google the first index still look ok |
Re: Common good python programming practices you should know by gbolly1151(m): 9:13am On May 14, 2020 |
HOW TO USE all() KEYWORDall() in python is a keyword that take iterable object as aguement and return true only when all the elements in this iterable are true ''' #Example 1 string=[True,False,True] print(all(string))
#output: False string=[True,True,True] print(all(string))
#output:True
''' Example 2 let say you want to validate user input from unknown source ''' required_field=['name','age','score'] user_value={'name':'peter','age':20,'score':300}
#native aproach #note that this only check for key and not value itself #but you can cook it to your taste
def is_valid(require,value): for field in required_field: if field not in user_value.keys(): return False return True print(is_valid(required_field,user_value))
#output: True #if you change the key,it will be false on run
#pythonic approch
print(all([field in user_value.keys() for field in required_field]))
#output:True #if you change the key in user_field it will turn False on run
|
Re: Common good python programming practices you should know by gbolly1151(m): 11:07am On May 16, 2020 |
WHAT IS if __name__=='__main__'?#short explanation if __name__=='__main__': print('hello')
then, you are telling the computer that if this python file is run by user or robot then print('hello') #full explanation Anytime you open python file,you are actually loading the file into the memory of the computer (i.e RAM). The name that will be given to that file at that point wont be the name of the file but a new name that is called '__main__' (i.e __name__='__main__') and it is stored together with other data in memory. To check that, open any python file and print global data using global keyword print(globals())
output ... {'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py', '__package__': None, '__cached__': None, '__name__': '__main__', '__doc__': None}
from that output above we can see that __name__= '__main__' so at runtime the name of any python file is '__main__'. This name is often use proffessionally in python for testing or running the functionality of a script at runtime. you might be wondering why we have underscore,This is because we dont want it to be in conflict when we use 'name' as variable name in our program now,if you use if __name__=='__main__': print('hello')
then, you are telling the computer that if this python file is run by user or robot then print('hello') you can acqually change the variable of __name__ e.g __name__='changed'
#now let see the changed name of the file at runtime print(globals())
#output {'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py', '__package__': None, '__cached__': None, '__name__': 'changed', '__doc__': None}
we can see that our __name__ has been assign another variable
|
Re: Common good python programming practices you should know by Predstan: 12:42pm On May 16, 2020 |
gbolly1151:
WHAT IS if __name__=='__main__'?
#short explanation
if __name__=='__main__': print('hello')
then, you are telling the computer that if this python file is run by user or robot then print('hello')
#full explanation Anytime you open python file,you are actually loading the file into the memory of the computer (i.e RAM). The name that will be given to that file at that point wont be the name of the file but a new name that is called '__main__' (i.e __name__='__main__') and it is stored together with other data in memory.
To check that, open any python file and print global data using global keyword
print(globals())
output ... {'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py', '__package__': None, '__cached__': None, '__name__': '__main__', '__doc__': None}
from that output above we can see that __name__= '__main__'
so at runtime the name of any python file is '__main__'.
This name is often use proffessionally in python for testing or running the functionality of a script at runtime.
you might be wondering why we have underscore,This is because we dont want it to be in conflict when we use 'name' as variable name in our program
now,if you use
if __name__=='__main__': print('hello')
then, you are telling the computer that if this python file is run by user or robot then print('hello')
you can acqually change the variable of __name__
e.g
__name__='changed'
#now let see the changed name of the file at runtime print(globals())
#output {'__builtins__': <module 'builtins' (built-in)>, '__file__': '/storage/sdcard0/qpython/scripts3/.last_tmp.py', '__package__': None, '__cached__': None, '__name__': 'changed', '__doc__': None}
we can see that our __name__ has been assign another variable
I finally learnt OOP. I have completed a project. Its coordinate of a line with slope, distance and to determine if a line is vertical or horizontal and if it is perpendicular or parallel to another. I also completed a Time project to display the julian day, the day of the week, of that date and gregorian date. Its interesting so far. I couldn't display the calendar without the normal calendar module. I am trying to create my own calendar module but I didnt get that. I'm also currently working on Polygon. 1 Like |
Re: Common good python programming practices you should know by gbolly1151(m): 1:41pm On May 16, 2020 |
Predstan:
I finally learnt OOP. I have completed a project. Its coordinate of a line with slope, distance and to determine if a line is vertical or horizontal and if it is perpendicular or parallel to another.
I also completed a Time project to display the julian day, the day of the week, of that date and gregorian date. Its interesting so far. I couldn't display the calendar without the normal calendar module. I am trying to create my own calendar module but I didnt get that.
I'm also currently working on Polygon.
Nice one bro...keep it up |
Re: Common good python programming practices you should know by iCode2: 11:55am On May 18, 2020 |
Hey guys, so, I'm trying my hands on this exercise: The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”) Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1. Here's my code: def collatz(number): if number % 2 == 0: return print(number // 2) elif number % 2 == 1: return print(3 * number + 1)
number =int(input()) while number != 1: collatz(number)
What am I not doing right? |
Re: Common good python programming practices you should know by Predstan: 12:33pm On May 18, 2020 |
iCode2: Hey guys, so, I'm trying my hands on this exercise:
The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”) Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1.
Here's my code:
def collatz(number): if number % 2 == 0: return print(number // 2) elif number % 2 == 1: return print(3 * number + 1)
number =int(input()) while number != 1: collatz(number)
What am I not doing right? First you need to return the number from the Collatz function as an integer not a print function... use: return number//2. Then you have to check that the return value from the Collatz is not equal to 1 if not, user keeps inputting number and the Collatz function is called on the number from user. def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: continue
Using Recursion:
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 def main(): number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: main() return print ("Callatz on", number, "is", Num) main()
2 Likes |
Re: Common good python programming practices you should know by gbolly1151(m): 4:44pm On May 18, 2020 |
Predstan:
First you need to return the number from the Collatz function as an integer not a print function... use: return number//2.
Then you have to check that the return value from the Collatz is not equal to 1 if not, user keeps inputting number and the Collatz function is called on the number from user.
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: continue
Using Recursion:
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 def main(): number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: main() return print ("Callatz on", number, "is", Num) main()
That code for recursion doesn't look like one and even the first method will still end up looping and wont end. Am thinking should look like this def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = number while Num != 1: Num=collatz(Num) print(Num)
|
Re: Common good python programming practices you should know by gbolly1151(m): 5:04pm On May 18, 2020 |
Or there is something i don't get? |
Re: Common good python programming practices you should know by Predstan: 5:40pm On May 18, 2020 |
gbolly1151:
That code for recursion doesn't look like one and even the first method will still end up looping and wont end. Am thinking should look like this
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = number while Num != 1: Num=collatz(Num) print(Num)
Ok, But on the other hand, look at this bolded part of the question. I was thinking, we should be checking that return value is not equal to 1 and not our input value iCode2: Hey guys, so, I'm trying my hands on this exercise:
The Collatz Sequence Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print number // 2 and return this value. If number is odd, then collatz() should print and return 3 * number + 1. Then write a program that lets the user type in an integer and that keeps calling collatz() on that number until the function returns the value 1. (Amazingly enough, this sequence actually works for any integer—sooner or later, using this sequence, you’ll arrive at 1! Even mathematicians aren’t sure why. Your program is exploring what’s called the Collatz sequence, sometimes called “the simplest impossible math problem.”) Remember to convert the return value from input() to an integer with the int() function; otherwise, it will be a string value. Hint: An integer number is even if number % 2 == 0, and it’s odd if number % 2 == 1. |
Re: Common good python programming practices you should know by gbolly1151(m): 7:05pm On May 18, 2020 |
Predstan:
Ok, But on the other hand, look at this bolded part of the question. I was thinking, we should be checking that return value is not equal to 1 and not our input value
Have you tried to run the code and it works as you expected? |
Re: Common good python programming practices you should know by iCode2: 7:44pm On May 18, 2020 |
Predstan:
First you need to return the number from the Collatz function as an integer not a print function... use: return number//2.
Then you have to check that the return value from the Collatz is not equal to 1 if not, user keeps inputting number and the Collatz function is called on the number from user.
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: continue
Using Recursion:
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1 def main(): number =int(input("Enter Number" )) Num = collatz(number) while Num != 1: main() return print ("Callatz on", number, "is", Num) main()
Thanks but it didn't give the right output. |
Re: Common good python programming practices you should know by iCode2: 7:45pm On May 18, 2020 |
gbolly1151:
That code for recursion doesn't look like one and even the first method will still end up looping and wont end. Am thinking should look like this
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = number while Num != 1: Num=collatz(Num) print(Num)
I got the correct output from this. Thanks 1 Like |
Re: Common good python programming practices you should know by Predstan: 8:05pm On May 18, 2020 |
iCode2: Thanks but it didn't give the right output. Oh Sorry, I hope I haven't confused you |
Re: Common good python programming practices you should know by iCode2: 8:16pm On May 18, 2020 |
Predstan:
Oh Sorry, I hope I haven't confused you Nope.. |
Re: Common good python programming practices you should know by iCode2: 8:17pm On May 18, 2020 |
Can anyone recommend good python books with a lot of exercises? I just started out with automate the boring stuff. 1 Like |
Re: Common good python programming practices you should know by gbolly1151(m): 8:30pm On May 18, 2020 |
iCode2: Can anyone recommend good python books with a lot of exercises? I just started out with automate the boring stuff. Download think python |
Re: Common good python programming practices you should know by iCode2: 10:48pm On May 18, 2020 |
|
Re: Common good python programming practices you should know by DanRay1: 8:55pm On May 19, 2020 |
gbolly1151:
That code for recursion doesn't look like one and even the first method will still end up looping and wont end. Am thinking should look like this
def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
number =int(input("Enter Number" )) Num = number while Num != 1: Num=collatz(Num) print(Num)
How does this code repeatedly prompt the user for input when the input line isn't in the while loop block? Or is it in the collatz function? Because it doesn't look like you put it there. If it's in the function, then indent it a bit to make it readable and clearer. |
Re: Common good python programming practices you should know by gbolly1151(m): 9:13pm On May 19, 2020 |
DanRay1: How does this code repeatedly prompt the user for input when the input line isn't in the while loop block? Or is it in the collatz function? Because it doesn't look like you put it there. If it's in the function, then indent it a bit to make it readable and clearer. We are only required to input a number then it will print out all the collatz number still 1 1 Like |
Re: Common good python programming practices you should know by gbolly1151(m): 9:27pm On May 19, 2020 |
DanRay1: How does this code repeatedly prompt the user for input when the input line isn't in the while loop block? Or is it in the collatz function? Because it doesn't look like you put it there. If it's in the function, then indent it a bit to make it readable and clearer. def collatz(number): if number % 2 == 0: return number // 2 elif number % 2 == 1: return 3 * number + 1
If __name__=='__main__': number =int(input("Enter Number" )) Num = number while Num != 1: Num=collatz(Num) print(Num)
Hope it is readable? 1 Like 1 Share |
Re: Common good python programming practices you should know by DanRay1: 1:40am On May 20, 2020 |
gbolly1151:
We are only required to input a number then it will print out all the collatz number still 1 Okay I get it now. |
Re: Common good python programming practices you should know by gbolly1151(m): 4:33pm On May 20, 2020 |
How to create a simple singleton without decoratorDecorator is one of the popular way of creating singleton in python but we wont be using decorator here. before i move to code let me define singleton,it is a way of creating a single object of a class or function. In a program where you only need a single instance of a class you can create a Singleton. class Test: def __init__(self): self.num=5 def fmethod (self,mynum): mynum *=2 return 'fmethod mynum is {0}'.format(mynum)
def singleton(func,*args,**kwargs): obj=globals()['__cached__'] if obj is None: globals()['__cached__']=func(*args,**kwargs) obj=globals()['__cached__'] return obj Testobj1=singleton(Test) Testobj2=singleton(Test)
print(Testobj1 == Testobj2) # output : True
Testobj1.num=10 print(Testobj2.num) #output : 10
|
Re: Common good python programming practices you should know by darepapi: 4:15pm On May 21, 2020 |
gbolly1151:
#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>
I'd prefer the dunder method "repr"....(__repr__) without explicitly calling the print function on the object, repr returns the object description.... I.e instead of print(obj) running "obj" alone works better 1 Like |
Re: Common good python programming practices you should know by gbolly1151(m): 2:32pm On May 22, 2020 |
REMINDER: Range has step argument range(start,stop,step) Note that start and step are optional How to use step in range to print odd and even for even in range(2,10,2): print(even)
#output : 2,4,6,8
for odd in range(3,10,2): print(odd)
#output: 3,5,7,9
|
Re: Common good python programming practices you should know by gbolly1151(m): 3:43pm On May 22, 2020 |
HOW TO SWAP AN OBJECT a,b = 4,7 print(a,b) #output : 4,7 a,b=b,a print(a,b) #output: 7,4
|
Re: Common good python programming practices you should know by iCode2: 7:14pm On May 22, 2020 |
Hi gbolly1151, you seem to be very good with Python. When did you start learning? And are you self-taught? 1 Like |
Re: Common good python programming practices you should know by gbolly1151(m): 9:39pm On May 22, 2020 |
iCode2: Hi gbolly1151, you seem to be very good with Python. When did you start learning? And are you self-taught? I started learning python few years ago and am a self-taught |
Re: Common good python programming practices you should know by gbolly1151(m): 7:02pm On May 24, 2020 |
HOW TO USE LAMBDAThe format of lambda is as below [lambda keyword] [arguments[seperated by comma]] [semicolon] [logic] e.g # with single argument lambda x: x*x
#multiple argument lambda x,y: x*y
now assign that with variable name
mul=lambda x,y:x*y
x=5 y=6 print(mul(x,y))
#output 30
|
Re: Common good python programming practices you should know by gbolly1151(m): 2:57pm On May 27, 2020 |
KEY DIFFERENCE BETWEEN is AND ==is operator is use to check if two object have the same id number == is use to check if two objects have the same value #e.g a=[1,2,3] b=[1,2,3] print(a is b) #output false ''' The above print expression will return false because a and b are two objects with different id number,let check their id '''
print(id(a)) print(id(b))
''' id output is different on different devices,my device print
3066478144 3065959488
'''Since the value are the same,when you use == the output will be True'''
print(a == b) #output True
|
Re: Common good python programming practices you should know by gbolly1151(m): 3:49pm On May 27, 2020 |
PLEASE AVIOD THIS MISTAKE IN YOUR CODE a=1 if a ==3 or 4 or 6: print('yes') else: print('no')
#The answer will always be Yes why?
Let me break it down here
a=1 print(a == 3) # False print(False or 4) # 4 (i.e True) print(4 or 6) # 4 (i.e True)
now
if a == 3 or 4 or 6: # this is equivalent to
if False or True or True: print('yes') else: print('No')
The condition is True so print('yes') will be executed
#solution to the problem a=1 if a in [3,4,6]: print('yes') else: print('no')
|