Python3 basic syntax


As a matter of course, Python 3 source documents are encoded with UTF-8 and all strings are unicode strings. Obviously you can likewise indicate distinctive encodings for source records:

# - *-coding: cp-1252 - *-

The above definition permits the utilization of character encoding in the Windows-1252 character set in the source record, comparing to the Bulgarian, White, Macedonian, Russian, and Serbian dialects.


  • The first character must be a letter in the letters in order or an underscore _ .
  • The rest of the identifier comprises of letters, numbers, and underscores.
  • Identifiers are case delicate.

In Python 3, non-ASCII identifiers are likewise permitted.

python held words

Held words are catchphrases, and we can't utilize them as any identifier name. Python's standard library gives a catchphrase module that yields every one of the watchwords of the present rendition:


Single-line remarks in Python begin with #, as appeared in the accompanying precedent:

Instance (Python 3.0+)

#!/usr/container/python3 # first comment print ("Hello, Python!") # second comment

Execute the above code, the yield is:

Hello, Python!

Multi-line remarks can have different # numbers, just as ''' and """:

Instance (Python 3.0+)

#!/usr/bin/python3 # first comment # second comment ''' Third comment Fourth note ''' """ Fifth comment Sixth comment """ print ("Hello, Python!")

Execute the above code, the yield is:

Hello, Python!

Lines and indents

The most unmistakable component of Python is the utilization of space to speak to code hinders, without the utilization of supports {} .

The number of indented spaces is alterable, yet explanations in a similar square should contain a similar number of indented spaces. Models are as per the following:

Instance (Python 3.0+)

if True : print ("True") else: print ("False")

The number of spaces indented in the last line of the accompanying code is conflicting, causing a runtime error:

if True:
print ("Answer")
print ("True")
print ("Answer")
print ("False") # 

The above program is inconsistent due to indentation, and the following error will occur after execution.:

 File "test.py", line 6
print ("False") # Inconsistent indentation can lead to runtime errors
IndentationError: unindent does not match any outer indentation level

Multiline statements

Python usually writes a single statement in a row, but if the statement is long, we can use a backslash (\) to implement a multi-line statement, for example:

total = item_one + \
        Item_two + \

Multiple lines in [], {}, or () do not require a backslash (\), for example:

total = ['item_one', 'item_two', 'item_three',
        'item_four', 'item_five']

Number type

There are four sorts of numbers in python: whole numbers, booleans, buoys, and complex numbers.

  • int (whole number, for example, 1, just a single whole number sort int, communicated as a long whole number, without a Long in python2.
  • bool (Boolean, for example, True.
  • float (skim, for example, 1.23, 3E-2
  • complex (plural, for example, 1 + 2j, 1.1 + 2.2j

String (String)

  • In python, single statements and twofold statements are utilized precisely the equivalent.
  • Use three quotes (''' or """) to indicate a multi-line string.
  • escape character '\'
  • Backslashes can be utilized to get away, and r can be utilized to escape oblique punctuation lines. . On the off chance that r"this is a line with \n" at that point \n will appear, not a newline.
  • Cascading strings truly, for example, "this" "is" "string" is naturally changed over to this is string.
  • Strings can be combined with the + administrator and rehashed with the * administrator.
  • Strings in Python have two ordering strategies, beginning with 0 from left to right and beginning with - 1 from appropriate to left.
  • Strings in Python can't be changed.
  • Python does not have a different character type, a character is a string of length 1.
  • The language structure of the interference of a string is as per the following: variable [header subscript: tail subscript: advance size]
word = 'String'
Sentence = "This is a sentence."< Span class="pln">
Paragraph = """This is a paragraph,
Can consist of multiple lines """

Instance(Python 3.0+)

#!/usr/bin/python3 str='Welookups' print(str) # Output string... print(str[0:-1]) # Output all characters from the first to the second last print(str[0]) # Output string output string first character print(str[2:5]) # Output characters from the third to the fifth print(str[2:]) # Output all characters after the third start print(str * 2) # Output string twice print(str + 'Hello there') # Connection string print('------------------------------') print('hello\nWelookups') # Use backslash (\)+n to escape special characters print(r'hello\nWelookups') # Add an r in front of the string to represent the original string, no escaping

Here r means raw, which is raw string.

The output is:

WelookupsHello there

empty line

The work or the strategy for the class is isolated by a clear line, demonstrating the start of another bit of code. The class and capacity sections are likewise isolated by a clear line to feature the start of the capacity passage.

A clear line is not quite the same as code space. A clear line isn't a piece of the Python sentence structure. When you compose without embeddings a clear line, the Python translator won't turn out badly. Be that as it may, the job of clear lines is to isolate two distinct capacities or implications of code for future support or refactoring.

Remember: Blank lines are likewise part of the program code.

Wait for client input

Execute the accompanying project and sit tight for client contribution subsequent to squeezing the Enter key:

Instance (Python 3.0+)

#!/usr/canister/python3 input("< Span class="hl-special">\n\nPress the enter key to exit.")

In the above code, "\n\n" will yield two new clear lines before the outcome is yield. When the client presses the enter key, the program will exit.

Show different articulations on the equivalent line

Python can utilize different proclamations on a similar line, isolated by semicolons (;), coming up next is a straightforward model:

Instance (Python 3.0+)

#!/usr/bin/python3 import sys; x = 'Welookups'; /span>sys.stdout.write(x + '\n ')

Use the script to execute the above code, the output is:


Execute using the interactive command line, the output is:

>>> import sys; x = 'Welookups'; sys.stdout. write(x + '\n')

The 7 here is the number of characters.

Multiple statements form a code group

Indenting the same set of statements constitutes a block of code, which we call a code group.

Composite statements like if, while, def, and class. The first line begins with a keyword and ends with a colon ( : ). One or more lines of code after the line form a code group.

We refer to the first and subsequent code groups as a clause.

Example below:

if expression :
elif expression :
else :

Print output

print The default output is a newline. If you want to implement no line breaks, you need to add end="" at the end of the variable:

Instance (Python 3.0+)

#!/usr/bin/python3 x="a" y="b" # Line feed output print( x ) print( y ) print('---------') # No line feed output print( x, end=" " ) print( y, end=" " ) print()

The above example execution result is:

a b

import and from...import

Use import or from...import in python to import the appropriate module.

Import the entire module (somemodule) in the format: import somemodule

Import a function from a module in the format: from somemodule import somefunction

Import multiple functions from a module in the format: from somemodule import firstfunc, secondfunc, thirdfunc

Import all the functions in a module in the format: from somemodule import *

Import sys module

import sys print('================Python import mode=========================='); print ('The command line argument is:') for i in sys.argv: print (i) print ('\n python Path is',sys.path)

Import the argv of the sys module, path member

from sys import argv,path # Import specific members print('================python from import===================================') print('path:',path) # Since the path member has been imported, there is no need to add it when referring here.sys.path

Command line parameters

Many programs can perform some operations to view some basic information. Python can use the -h parameter to view help information for each parameter:

$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

[ etc. ]

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.