Popular Posts

Saturday, March 4, 2023

PyQt Button - Event connection

Hello Python developer, hope you're good today!


Today, we will learn about PyQt button and event connection.

For button creation in your window, use 'QPushButton' class as following exercise.

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 400, 300)
        self.setWindowIcon(QIcon("PyQt window sample icon.png"))
       
        btn = QPushButton("Button 1", self)
       
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()


Code run result :

Can you click the "Button 1"? Yes, you can click it but threr is no action by button click.

Now, we will connect the 'Event' when we click this 'Button 1'.
Let's type and run following Python codes.

# PyQt Window Button - Event connection exercise

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QtWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 400, 300)
        self.setWindowTitle("PyQt Button Click event exercise")
        self.setWindowIcon(QIcon("PyQt window sample icon.png"))
       
        btn = QPushButton("Button 1", self)
        btn.move(10,10)
        btn.clicked.connect(self.btn_clicked)
       
    def btn_clicked(self):
        print("Button clicked")
       
app = QApplication(sys.argv)
window = QtWindow()
window.show()
app.exec_()

Code run result : Type "Button clicked" text when you click the 'Button 1".



Can you click the 'Button 1' and see the 'Button clicked' text in your terminal or Python execution window?


That's great! Let's learn more about PyQt GUI!



Tuesday, February 28, 2023

PyQt WIndow setting

Hello Python Developer!

How are you? Hope you're in the best condition today. Because we will exercise PyQt WIndow setup.


-PyQt wIndow Size adjustment

import sys
from PyQt5.QtWidgets import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200,200,400,300)
       
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()


Python codes running result


- PyQt titlebar & icon setting

* Note : An icon file "PyQt window sample icon.png" must be in the same folder with this Python code.  

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200,200, 300,150)
        self.setWindowTitle("PyQt exercise")
        self.setWindowIcon(QIcon("PyQt window sample icon.png"))
       
app = QMainWindow(sys.argv)
window = MyWindow()
window.show()
app.exec_()

Have you checked above PyQt exercise sample Python codes? Great job!

Let's learn more about PyQt window setup!

Thursday, February 23, 2023

PyQt - Python GUI module

Hello Python developer!

Do you want to code a window base GUI(Graphic User Interface) app like below image?


If you are 'Yes', let's learn about 'PyQt' library(a set of modules) for GUI programming.

'PyQt' made by Riverbank Computing and you can find latest news and more details about PyQt from the following link.

PyQt site : https://riverbankcomputing.com/software/pyqt/



For installation of PyQt library at your PC, please type following command in Windows command prompt.


 pip install pyqt5


Are you ready for the first PyQt coding?

Let's input following code for PyQt sample and run it!

import sys
from PyQt5.QtWidgets import *

app = QApplication(sys.argv)
label = QLabel(" Hello GUI by Python! ")
label.show()
app.exec_()


Result

Can you see the small window with " Hello GUI by Python! " Text? Congratulations!
Now you successfully coded the first Python GUI app, good job!

See you on the next Python course. Please take care and coding everyday! 


Tuesday, February 21, 2023

Python Class Initiate Method

Hello Python developer!

Hope you're good today with bright sunshine like our future!

Today, I would like to study Initializer method in Python Class.

Class initializer method was made for initiating class variables and methods.

Think about this, if you create an instance from the class and you want it to have each initiate values and functions.


For instance, we will make a calculator Python program. 

First, we will initialize the calculator result variable as 0 with initializer method using ' def __init__(self): ' statement.

Let's look into the following codes.

class Calculator:
def __init__(self):
self.result = 0

def add(self, var1, var2):
self.result = var1 + var2
return self.result

def sub(self, var1, var2):
self.result = var1 - var2
return self.result

test_add = Calculator()
test_sub = Calculator()

print(test_add.add(4, 7))

test_sub.sub(7, 2)
print(test_sub.sub(9,6))





If you want to transfer variables into initializer method, refer following statement.


def __init__(self, var1, var2):
self.first_var = var1
self.second_var = var2


Now, are you familiar with the class 'Initializer' method?

Then, let's analyze following Python exercise codes.

# Python initiate method exercise

class Smartphone:
def __init__(self, model, year): # initiate class 'Smartphone' with following variables and function
self.model = model
self.year = year
self.model_year = model + " " + str(year)


Apple_phone = Smartphone("iPhone 14", 2022)
Samsung_phone = Smartphone("Galaxy S23", 2023)

print(Apple_phone.model, Apple_phone.year)
print(Samsung_phone.model, Samsung_phone.year)

print(Apple_phone.model_year)
print(Samsung_phone.model_year)



Here is above Python source codes in Github(https://github.com/Cevastian/Python-Developer-start-today/blob/master/Python_initiate_method.py)


Hope you get the right answer and level up your Python class understanding.

See you at the next post! Take care! 

Sunday, February 19, 2023

Python Class Inheritance exercise part 2

Hello Python developer!


Today, we will look into class 'inheritance' with my test codes. Because I want to understand about 'class inheritance'.


Let's see following codes and type in Python IDE for execution!

Source codes(Multi_Inheritance.py)

Github link : https://github.com/Cevastian/Python-Developer-start-today/blob/master/Multi_Inheritance.py

class Lion():
color = "yellow"
classification = "animal"

def hunting(self):
print("Lion is hunting")

def attack_claw(self):
print("Claw attack")


class Eagle():
color = "brown"
classification = "bird"

def hunting(self):
print("Eagle is hunting")

def attack_beak(self):
print("Beak attack")


class Shark():
color = "blue"
classification = "fish"

def hunting(self):
print("Shark is hunting")

def attack_teeth(self):
print("Teeth attack")


class Monster(Lion, Eagle, Shark):
color = "green"
classification ="beast"

def playing(self):
print("Monster is playing")

def attack_tail(self):
print("Tail attack")


monster = Monster() # Class instance generating
monster.playing() # monster instance playing method calling
monster.hunting() # monster instance 'Lion' class 'hunting' method by inheritance
monster.attack_teeth() # monster instance 'Shark' class 'attack_teeth' method by inheritance

Executed result


'Monster' class inherited from 'Lion', 'Eagle' and 'Shark' classes. It also has its own method ' playing' and 'attack_tail'. As you know, child class can use parent classes' attributes and methods. Python meet calling of class method, it tried to search in its own class and it fails to search it, Python tried to search it out in the first parent classes' attributes and methods. It still fails to find out the called attributes and method from the first class, Python tried to search it in second parent class.


So, 'monster.hunting' method execution result was 'Lion' classes' method excution result. Because there is no 'hunting' method in 'Monster' class so Python search 'hunting' method from the parent classes by 'Lion', 'Eagle' and 'Shark' sequence by Monster(Lion, Eagle, Shark) class inheritance.


Developer, did you understand 'class inheritance' with above example?

Hope you're fine today with Python codes!


Wednesday, February 15, 2023

Current Date & Time expression

Hello, Python developer!

Hope you're fine today! Do you know how can we express the current time in Python program?

Python has 'datetime' module for dealing with the date and time.

Let's test the it with following codes.


import datetime                                                # Load 'datetime' module
current_date_time = datetime.datetime.now( )        # Get current date & time
print(current_date_time)                                    #Print current date & time

Run result



If you want to add time or date about current date & time by datetime.now( ) function, please use 'timedelta' function. 

Here are 'timedelta' function examples.


import datetime
current_date_time = datetime.datetime.now( )
print( current_date_time + datetime.timedelta(seconds = 75))    # Add 75 seconds
print( current_date_time - datetime.timedelta(minutes = 25))    # Sub 25 minutes
print( current_date_time + datetime.timedelta(hours =7))        # Add 7 hours
print( current_date_time - datetime.timedelta(days=100))        # Sub 100 days
print( current_date_time + datetime.timedelta(weeks = 8))        # Add 8 weeks


Run result

As you recognized the above result, 'timedelta' function automatically converts seconds to minutes, minutes to hours, hours to days and days to weeks.

Please refer following 'datetime' reference documentation from Python official site.


In this reference page, you also find 'datetime' and 'timedelta' function explanation as following.

I hope you get to know and deal with date & time in Python.

Please take care and have a nice day, Python developer!  

Tuesday, February 14, 2023

Bitcoin Price Checker Ver 1.0

Hello Python developer,

Today, I will code Bitcoin price checker with requests module.

Python module is file set of python codes - functions.

I showed module declaration from the Python Glossary

(https://docs.python.org/3/glossary.html#term-module)


You can use codes in the Python module using 'import' keyword.


import Python module name


We will use 'requests' module for web-scrapping from the 'Binance' cryptocurrency exchange.

Here is the executed result.


'requests.get' code get the current Bitcoin price with USDT symbol from the Binance server.

There are two ways to print out the Bitcoin price.

 - Print content variable from the current_price 

 - Using JSON module with json function to print out the current Bitcoin price 


I also uploaded this code in my GibHub.



I hope you to enjoy above codes.

Have a nice day, Python developer!

Thursday, February 9, 2023

Understanding Python Class

Hello, Developer!


Today, I will exercise about Python 'Class'.

Class is based on OOP(Objective Oriented Programming) and I need to exercise it with several examples about class for clear understanding.


Did you remember about 'Class'?

It consists of two parts - Data and Function as following image. Normally, developers call 'data' in class as 'attribute' and 'function' in class as 'method'.

You can create a class with following construct.

class Class_Name:
    data
    function(method)

Example

class MyClass():
 Color = Green                Data(Attribute) part
 def painting(self):            Function(Method) part
      paint(shape)

You can created a object(=instance) from class as following.

paint_shape = MyClass()      Create 'paint_shape' object from the 'MyClass' class

You can use a function in the created object(=instance) as following.

paint_shape.painting()         Call painting function(method) from paint_shape object.

You can inherit from parent classes(father & mother). 

If you create a Child class and inherits Class Father & class Mother, Child instance can use data and methods of Father and Mother classes.

Let's see following example.

Class father has attribute "hard" and method "work"
Class mother has attribute "kind" and method "cook"
Calss child inherits Father and Mother classes and has own method "sleep"

'child' class can use "work" method from 'father' class and use "cook" method from 'mpther' class and use its own "sleep" method.

You can easily inherit from other classes by adding class names in class definition line as following.

Class inherite example 
 
class child(father, mother):       # 'child' class inherits 'father' class 'mother' class

This is how classes work in Python. Let's study more about class together!

Tuesday, January 31, 2023

Anaconda - Python distribution package installation guide

 Hello, Python developer!


I would like to introduce "Anaconda" - a Python develop distribution package.


Anaconda distribution package is powerful tools for Python development. It includes several useful toolds and modules for Python programming. It helps you to save time and focus on your Python codes development without searching and installing required Python modules and packages.


Let's install Anaconda package on your PC with following steps.

1. Run the web-browser(i.e. Chrome, Edge, Firefox, Safari and etc.) and connect to Anaconda website with following link.

- Anaconda download link: https://www.anaconda.com/products/distribution


2. Download Anaconda Distribution package by click the "Download" button.


3. Run the downloaded Anaconda Distribution package installation file with "Administrator permission".




4. Click "Next" button for Anaconda set up.


5. Click "I agree" button to agree about "License Agreement of Anaconda".


6. Select "All Users" for Installation Type and click "Next" button.

7. Click "Next" button about "Choose Installation Location". If you want to install Anaconda with specificified path and folder, please click "Browse" button and select available path and folder for Anaconda installation.

8. Click "Install" button for installation of Anaconda and"Register Anaconda3 as the system Python 3.9"


9. Anaconda installation is in progress. It may take few minutes.


10. Installation is completed. Click "Next" button.

11. Click "Next" button.

12. Click "Finish" button for finish Anaconda installation.



This Anaconda installation guide is based on the Anaconda version on January 2023. The installation of Anaconda could be updated at later versions.

Have you installed Anaconda package on your PC without issue?

We hope your successful Python development journey. Good luck!

Monday, January 30, 2023

Python Beginner: Python Interpreter

 Hello, Developer! Long time no see and I am really pleased to meet you again!


Last 2-years, I had worked differnt field and I was not able to make chance for Python coding... I only had some chances for searching and studying for Python language.


I am really sorry for leaving Python post for a long time. But it's time to coding again!

 

Today, we will learn the "Python Interpreter".


You can use a Python interpreter as a direct text interactive environment through execution of python interpreter in your operating system(Windows, Mac, Linux, etc.) command prompt mode.




This function helps you can write and test Python codes in interative mode with command lines.


I hope you use this mode for short Python code tests.


Let's test Python codes with interpreter mode.

Monday, September 14, 2020

Python Beginner: Class inheritance

 Hello, Developer! 😄


Today, we will learn the "Inheritance". The "Inheritance" function allows you to use other class functions without codes copy. If you inherit other classes' properties, you can improve programming productivity through this function.


Class Inheritance Form

class Sample_class_name(Inheritance parent class): 

    def additional_property # You can add additional properties on parents' all properties

    def override_property # If you want to override parent properties, you can redefine property with the same property name


I showed all exercise codes and execution result as following.

Chef.py

class Chef:

def make_chicken(self):
print("The chef makdes a chicken.")

def make_salad(self):
print("The chef makes a salad.")

def make_special_dish(self):
print("The chef makes bbq ribs.")

ChineseChef.py

class ChineseChef: # ChineseChef can do everything which Chef can do

def make_chicken(self):
print("The chef makdes a chicken.")

def make_salad(self):
print("The chef makes a salad.")

def make_special_dish(self):
print("The chef makes soup noodle.")

def make_fried_rice(self):
print("The chef makes fried rice.")

InheritanceChineseChef.py

from Chef import Chef

class IchineseChef(Chef):

def make_special_dish(self):
print("The Chef makes a orange chicken.")


def make_fried_rice(self):
print("The Chef makes a fried rice.")

Inheritance.py

from Chef import Chef
from ChineseChef import ChineseChef
from InheritanceChineseChef import IchineseChef

myChef = Chef()
myChef.make_special_dish()

myChineseChef = ChineseChef()
myChineseChef.make_special_dish()

ImyChineseChef = IchineseChef()
ImyChineseChef.make_fried_rice()

Execution Result

Can you see the same result on your PC? Congratulations! Now you can utilize class inheritance function in the Python.


Alright, let's see in the next post, Python developer! 😊

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...