Python Programming

Python Programming Syntax Rules with Examples

Python programming:

Python Programming syntax:- Programming means giving instructions to a computer to perform a specific task. Such instructions must be given using a programming language, not human speaking languages. We can actually say there are two types of languages Natural languages and Artificial Languages. Natural languages are the languages used by humans for communication like English, Urdu, Spanish, German, Hindi, Chinese, Pushtu, etc. While the artificial languages are those languages which are used for the communication with machines. This is through the artificial languages humans can talk to machines and computers, etc.

There are a number of such languages ​​to choose from on the Raspberry Pi. e.g. bash, C, C++, Java or PHP. however, the focus is on the Python Programming language. It is considered the standard programming language for the Raspberry Pi and is preferably used when there are no good reasons for speaking another language. Python is easy to learn, does not require any complicated additional tools and is well suited to address the hardware functions of the Raspberry Pi. I have done so many projects using Raspberry Pi.

Raspberry Pi based Projects:


Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Elementary Python Programming syntax rules:

Instructions

Python statements are usually one-line. Unlike C/C++ or other programming languages there is no need to put a semicolon at the end of the line. In python we don’t use any line terminator.

Multi-line instructions are allowed if their beginning and end are enclosed in brackets, you can clearly see in the example code given below for function calls. Alternatively, multi-line Instructions can also be formed with the separator \

print ("abc",
"efg")
a = 1 + 2 + \
3 + 4

Instructions may end with a semicolon. Usually this semicolon is optional and has no effect on program execution. However, semicolons allow you to add several statements on one line formulate:

a = 1; b = 2; c = 3

You can also do the above triple assignment in another way, by specifying both the variables and the values ​​in groups whose

Components are separated by commas. Python-internal will be there Tuples formed. Both variants are correct, but the second variant is closer the language concepts of Python.

a, b, c = 1, 2, 3



Block elements

In Python, like in any other programming language, there are some language elements, which initiate a whole block of further instructions, e.g. branches with if, Loops with for and while or function definitions with function. In Python such language elements always end with a colon. All further Instructions belonging to the corresponding block must be indented. The brackets used in other languages ​​are omitted. So:

if xxx:

instruction1a

instruction1b

else:

instruction2a

instruction2b

instruction2c

If condition xxx is met, instructions 1a and 1b are executed; If it is not fulfilled, instructions 2a, 2b and 2c are executed instead. In Python, it is crucial that the code is not indented as in other programming languages is optional, but part of the syntax! For the amount of indentation there are no rigid rules: one character is enough, but common ones are because of the better ones Legibility four characters. Caution is advised in this context with editors, use the tabs to indent. Python assumes that the tab position is at multiples of eight characters. If you are in your Editor set a different tab width and tabs and spaces mix, then it can happen that Python interprets the indentations gets mixed up. Code may also be specified directly after a block element. In simple cases you can formulate single-line conditions or loops:

if xxx: statement

In a pinch, you can even run multiple statements on one line this way:

if xxx: instruction1; instruction2; instruction3

print

When getting to know Python and in the first test programs, the print Function omnipresent. This allows you to easily display variable content in the terminal or output test messages. The meaning of print will become more clear to you with time as you read this article: the more intensely you program, the less often you will spend perform with print – either write results directly to files, or you can use a simple graphical user interface to interact with the users. The syntax of print is simple: you pass one or more parameters to the function in parentheses. Print converts each of the parameters into strings around and outputs all strings. Thereby between the parameters put a space and a line break at the end so that each print Instruction starts on a new line. print is therefore very easy to use and can handle almost any type of Python object, including Lists, tuples and sets.

>>> print (1, 2, 3/4, 'abc', 2 == 3)
1 2 0.75 abc False
>>> print ('1/7 is', 1/7)
1/7 is 0.14285714285714285
>>> x, y, z = ['one', 'list'], ('one', 'tuple'), {'one', 'set'}
>>> print (x, y, z)
['one', 'list'] ('one', 'tuple') {'one', 'set'}

print knows three optional parameters:

  • sep sets the character string that is output between the parameters By default ‘ ‘.
  • end defines the character string that is output after the last parameter by default ‘\ n’.
  • file determines where the output is performed. Usually the Outputs redirected to standard output. file gives you the option to edit the Write output to a text file.
>>> print (1, 2, 3, sep = '---')
1 --- 2 --- 3
>>> print (1, 2, 3, sep = ';', end = '. \ nEOF \ n')
1; 2; 3.
EOF
>>> f = open ('out.txt', 'w')
>>> print (1, 2, 3, file = f)
>>> f. close ()


print in Python 2

This article basically refers to Python version 3. If you want to print But we make an exception: No other language construct has been used when switching Changed from Python 2 to Python 3 so much and obviously. In Python 2 is print is not a function, but an elementary keyword. Therefore the Brackets:

# applies to Python 2

>>> print 1, 2, 3

1 2 3

The output always ends with the line break \ n, unless at the end of print a comma is specified without any further parameters. Between the parameters is as with print (), a space is always output – but there is an exception here too:

When Python detects that the previous parameter with a tab or line break ends, i.e. with \ t or \ n, then there is no additional space built-in. The syntax variant print >> file, para1, para2 … enables To redirect output to a file:

# applies to Python 2

f = open (‘out .txt’, ‘w’)

print >> f, 123

close ()

input

Processed in the same way as you can use print to output in a terminal window input text input. (If you are using Python 2, instead of input use the raw_input function.) input first outputs and expects the text specified in the optional parameter then an entry that must be completed with (pressing enter button).

name = input (‘Enter your name:’)

print (‘Your name is:’, name)

Empty entries, i.e. a (press enter) without text, acknowledges input with an EOFError. If Your program loads the readline module, then there are repeated entries Editing functions are available. For example, the user of your program then use the cursor keys to reuse previously entered character strings and to change.


Modules and import

For beginners, Python often looks very large and complex, but in reality it is the number of functions directly implemented in Python is quite manageable. All conceivable additional functions are not in the core language of Realized in Python, but in the form of modules that are programmed in Python themselves were. These modules must be imported before they can be used. Therefore, there are various syntax variants, of which we only mention the most important ones:

  • import module-name: This instruction reads the module. Then you can all functions defined therein in the notation module name.function name () use. With import m1, m2, m3 you can also import several modules at once import.
  • import module name as m: With this variant, the functions defined in the module can be used in the form m.function-name (). Especially with long ones This minimizes the typing effort and makes the code clearer.
  • from module name import f1, f2: With this variant you can use the functions f1 and use f2 without prefixing the module name.
  • from module name import *: This instruction imports all symbols from the specified Module whose name does not start with __ (i.e. with two underscores). Caution: With this variant it can happen that you inadvertently read the content overwrite variables of the same name!

Internally in Python, import causes the module name.py file to be read and executed becomes. Many modules simply contain the definition of various functions; so are These functions are now known to Python and can be used. Modules can but also contain code that is executed immediately, for example for initialization work perform.

It is common practice to always put import statements at the beginning of a Python script. Modules can import additional modules themselves. Python remembers which Module has already read it in and thus avoids a new import activated modules.

When searching for the module files, import evaluates sys.path and takes it into account all directories named there. The first entry with the empty string means that the local directory is also searched.

>>> import sys
>>> print (sys. path)
['',
'/ usr / lib / python3 .2',
'/ usr / lib / python3 .2 / plat - linux2',
'/ usr / lib / python3 .2 / lib - dynload',
'/ usr / local / lib / python3 .2 / dist - packages',
'/ usr / lib / python3 / dist - packages']


Comments

Simple comments are introduced with the # character and extend up to End of line:

#a comment

print (“abc”) # one more comment

With “” “you can form multiline comments:

“”” a long

Comment “” “

If such comments are placed correctly (e.g. immediately after the definition a function or a class), they count as so-called docstrings and are evaluated by the Python internal documentation system.

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button