Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python Syntax

Here, you will learn the basic syntax of Python 3.

Display Output

The print() funtion in Python displays an output to a console or to the text stream file. You can pass any type of data to the print() function to be displayed on the console.

Example: Display Output
name="Ram"                
print(name) # display single variable

age=21                          
print(name, age)# display multiple variables
print("Name:", name, ", Age:",age) # display formatted output
Try it

By default, a single space ' ' acts as a separator between values. However, any other character can be used by providing a sep parameter. Visit the print() funtion for more information.

Getting User's Input

The input() function is used to get the user's input. It reads the key strokes as a string object which can be referred to by a variable having a suitable name.

Taking User's Input

Note that the blinking cursor waits for the user's input. The user enters his input and then hits Enter. This will be captured as a string.

In the above example, the input() function takes the user's input from the next line, e.g. 'Steve' in this case.input() will capture it and assign it to a name variable. The name variable will display whatever the user has provided as the input.

The input() function has an optional string parameter that acts as a prompt for the user.

Taking User's Input

The input() function always reads the input as a string, even if comprises of digits. Visit input() function for more information.

Python Statements

Python statement ends with the token NEWLINE character (carriage return). It means each line in a Python script is a statement. The following Python script contains three statements in three separate lines.

Example: Python Statements
list = [1, 2, 3, 4
        5, 6, 7, 8,
        9, 10, 11, 12]

Please note that the backslash character spans a single line in one logical line and multiple physical lines, but not the two different statements in one logical line.

Use the semicolon ; to separate multiple statements in a single line.

Example: Multiple Statements in Single Line
print('id: ', 1);print('First Name: ', 'Steve');print('Last Name: ', 'Jobs')
Try it

Code Comments in Python

In a Python script, the symbol # indicates the start of a comment line. It is effective till the end of the line in the editor.

Example: Single Line Comment
# this is a comment
print("Hello World")
print("Welcome to Python Tutorial") #comment after a statement.

In Python, there is no provision to write multi-line comments, or a block comment. For multi-line comments, each line should have the # symbol at the start.

A triple quoted multi-line string is also treated as a comment if it is not a docstring of the function or the class.

Example: Multi-line Comments
'''
comment1
comment2
comment3
'''

Visit PEP 8 style Guide for Python Code for more information.

Indentation in Python

Leading space or tab at the beginning of the line is considered as indentation level of the line, which is used to determine the group of statements. Statements with the same level of indentation considered as a group or block.

For example, functions, classes, or loops in Python contains a block of statements to be executed. Other programming languages such as C# or Java use curly braces to denote a block of code. Python uses indentation (a space or a tab) to denote a block of statements.

Indentation Rules

  • Use the colon : to start a block and press Enter.
  • All the lines in a block must use the same indentation, either space or a tab.
  • Python recommends four spaces as indentation to make the code more readable. Do not mix space and tab in the same block.
  • A block can have inner blocks with next level indentation.

The following example demonstrates if elif blocks:

Example: Python if Block
if 10 > 5:  # 1st block starts
  print("10 is greater than 5") # 1st block
  if 20 > 10: # 1st block
    print("20 is greater than 10") # inner block
else: # 2nd block starts
  print("10 is less than 5") # 2nd block
Try it

A function contains all the same level indented statements. The following function contains a block with two statements.

Example: Python Function Block
def SayHello(name):
  print("Hello ", name)
  print("This is the second statement of the SayHello() function")
  print("This is the last statement of the SayHello() function")
print("This is not the part of the SayHello() function")

#calling a function
SayHello("Abdul")
Try it

The following example illustrates the use of indents in Python shell:

Python Block in Shell

As you can see, in the Python shell, the SayHello() function block started after : and pressing Enter. It then displayed ... to mark the block. Use four space (even a single space is ok) or a tab for indent and then write a statement. To end the block, press Enter two times.

Python Naming Convetions

The Python program can contain variables, functions, classes, modules, packages, etc. Identifier is the name given to these programming elements. An identifier should start with either an alphabet letter (lower or upper case) or an underscore (_). After that, more than one alphabet letter (a-z or A-Z), digits (0-9), or underscores may be used to form an identifier. No other characters are allowed.

  • Identifiers in Python are case sensitive, which means variables named age and Age are different.
  • Class names should use the TitleCase convention. It should begin with an uppercase alphabet letter e.g. MyClass, Employee, Person.
  • Function names should be in lowercase. Multiple words should be separated by underscores, e.g. add(num), calculate_tax(amount).
  • Variable names in the function should be in lowercase e.g., x, num, salary.
  • Module and package names should be in lowercase e.g., mymodule, tax_calculation. Use underscores to improve readability.
  • Constant variable names should be in uppercase e.g., RATE, TAX_RATE.
  • Use of one or two underscore characters when naming the instance attributes of a class.
  • Two leading and trailing underscores are used in Python itself for a special purpose, e.g. __add__, __init__, etc.

Visit PEP 8 - Prescriptive Naming Conventions for more information.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.