Min menu

Pages

How to write code in Python



 Principles of writing code in Python

In the beginning, you should know that all you will learn in this lesson is a theoretical explanation of the methods of writing code.
So in this lesson, you will learn how to write Python code correctly that the computer understands and anyone who tries to read the code that you will write in the future when building your own applications.

 

Python Case Sensitivity

Case Sensitivity It means that the programming language distinguishes between uppercase and lowercase letters.

Python treats the names we use carefully, whether we assign these names to variables, functions, classes, objects, etc.
Example:  note They  Note are not the same thing.

While in other programming languages ​​like HTML It doesn't matter if the letters are uppercase or lowercase.
Example:  note and  Note and  they are one NoTe and the  NOTE same thing.



  class name in python

Always start the class name with a capital letter, and if the class name consists of more than one word, make the first letter of each word capitalized.


Examples

In the event that the name of the class consists of one word.

                    first class:
		

In the event that the name of the class consists of more than one word.

                    class FirstPythonClass:
		


  variable name in python 

Use lowercase letters when placing names for variables, and if the variable name consists of more than one word, put it  _ between every two words.

.

Examples

In the event that the variable name consists of one word.

                    average = 10
		

If the variable name consists of more than one word.

                    total_score = 20
		


  function name in python 

Use lowercase letters when placing names for functions, and if the name of the function consists of more than one word, put  _ between each two words.

 

Examples

If the function name consists of one word.

                    def display():
		

If the function name consists of more than one word.

                    def display_user_info():
		


  Comments in Python 

We use comments to make notes about the code we wrote just so we don't forget how we programed the code in case we want to review or modify it after a long time.
Comments do not affect the written code placed in the program, and an unlimited number of comments can be placed.


To put a comment, put the code  # and then write what you want.

Remember:  you are not obligated to put comments in your programs. But we recommend that you always put comments to help you understand the code you wrote.

Example

                    # This is a one-line comment that does not affect the code at all
		  # This is another comment.. As you can see, you can put as many comments as you want
	

Note: Commenting  can be done in other ways in Python, but the Python developers on their official site recommend this method only for commenting.



Writing more than one command on the same line in Python 

By default, Python considers each command to be written on one line.
If you want to write more than one command on the same line, put a semicolon  ; between each of the two commands, so the Python interpreter will understand that the line contains more than one command.

Example

Here we put three commands on one line. Actually, every command here is about defining a variable and assigning it a value.

                    x = 1; y = 2; z = 3
		


Writing a single command on more than one line in Python 

If you want to write one command on more than one line, put the code  \ at the end of each line, so the Python interpreter will understand that the command consists of more than one line.

first example

Test.py
                    # Here we have defined three variables
		  item_1 = 10
		  item_2 = 20
		  item_3 = 30
	  
		  # The next three lines are one command
		  # total and put the result in the variable item_3 , item_2 and item_1 if here the values ​​of the variables will be summed
		  total = item_1 + \
		  item_2 + \
		  item_3
	  
		  # total Here we have shown the value of the variable
		  print("total contains:", total)
	

We will get the following result when running.

total contains: 60

Note:  Sentences containing symbols  [] , OR  () ,  {} can be written directly on multiple lines. Ie you do not need  \ at the end of each line.

second example

Here we have defined an array of texts.

Test.py
                    # The next four lines are one command
		  seasons = ['Autumn',
		  'Winter',
		  'Spring',
		  'Summer']
	  
		  # seasons Here we have shown the values ​​stored in the array
		  print("Seasons contains:", seasons)
	

We will get the following result when running.

Seasons contains: ['Autumn', 'Winter', 'Spring', 'Summer']

 Characters used to put names in Python

Any name we give to a variable, function, class, object etc.. is called identifier in programming.
In Python, for each component we want to create, we have to give it a special name, that is, we need to specify the identifier for him.
So the elements in Python are distinguished by their names, i.e. by the Identifiers.


Mandatory rules when giving names

  1. the Identifiers They must begin with a capital letter between  A-Z or a lowercase letter between  a-z or a sash  _.

  2. It is forbidden to use any of the reserved words Keywords ).

  3. Don't forget that Python applies the principle the Case Sensitive.


Focus on the first letter only

Examples of  allowed nouns  :  H armash  ,  n ame  ,  _ number

Examples of  prohibited nouns  :  1 st  ,  - cash  ,  @user

  Reserved words in Python

All of the following words are reserved for Python, which means they cannot be used Identifiers.

and
assert
break
class
continue
def
del
elif
else
except
exec
False
finally
for
from
global
if
import
in
is
lambda
None
nonlocal
not
or
pass
print
raise
return
True
try
while
with
yield

  Code ordering rules in Python

Initially if you are using a program PyCharm It will alert you if you break any of the mandatory Python coding rules.
The rules for writing code in Python are the following:

  • Do not add any empty space using the button  TAB because the space given by this button is not allowed in Python language.

  • Use  4  blank spaces  Space when nesting code.

  • Put at least a blank line between the line where the class is defined and the functions defined within it.

  • Put at least a blank line between each of the two functions.

  • Put a blank line between every two blocks you add inside the functions.

  • Put a blank space around the control and condition clauses.

  • When placing comments, it is preferable to use the symbol  # at the beginning of each line, even if the comment consists of several lines.

  • The maximum number of characters that can be placed in each line is  79  characters.


technical terms

  • Block:  It is a set of logically sequential commands placed in a specific place and there are no empty lines between them.

  • Indentations:  It is the blank spaces that are added to arrange and coordinate each block that is added.

  Solve the problem of using the button  TAB in Python

program PyCharm It allows you to use the button  TAB to add  4  blank spaces at once and without problems, provided that you set it manually.

To make the button  TAB add  4  blank spaces when clicked instead of adding a large space in a program PyCharm, follow these steps:

  1. Click  S +  Alt +  Ctrl to open the settings page.

  2. tap on Code Style then Python Then be sure to choose the same properties as in the image.

    Solve the problem of using the TAB button in Python

method of converting each TAB contained in the python file to  4  blank spaces

When you copy the code and paste it into a file, you notice that the blank spaces that were in the file are automatically converted to TAB.
Therefore, this . must be converted TAB Blank spaces again so as not to violate the terms of writing code in Python.

program PyCharm It allows you to convert everything  TAB in the code to  4  blank spaces at once and without problems, provided that you set it manually.

To make each  TAB turn into  4  blank spaces in a program PyCharm, Follow these steps:

Convert every TAB in a Python file to 4 blank spaces

  Examples of how to write code in Python

The purpose of the following example is to show how Python code should be arranged, not how it works.

first example

Test.py
                    # Its value is 14 note Here we have defined a variable named
		  note = 14
	  
		  # greater or equal to 10 the print command placed inside it will be executed note here we set a condition that means that if the value of the variable is
		  if note >= 10:
		  print("Congratulations.. you passed the test!")
	  
		  # greater or equal to 10 the print command placed inside it will be executed note here for us that if the value of the variable is not
		  else:
		  print("Sorry.. you failed the test!")
	

We will get the following result when running.

Congratulations.. you passed the test!

In case you intend to put all of the above code inside a class, you must add  4  blank spaces before each line.
Remember:  The purpose of the following example is to show how Python code should be arranged, not how it works.

second example

Test.py
                    # Test Here we have defined a class named
		  class Test:
	  
		  # Its value is 14 note Here we have defined a variable named
		  note = 14
	  
		  # greater or equal to 10 the print command placed inside it will be executed note here we set a condition that means that if the value of the variable is
		  if note >= 10:
		  print("Congratulations.. you passed the test!")
	  
		  # greater or equal to 10 the print command placed inside it will be executed note here as if we said that if the value of the variable is not
		  else:
		  print("Sorry.. you failed the test!")
	

We will get the following result when running.

Congratulations.. you passed the test!