• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

[Cheat Sheet] Basic Python 3 Syntax Explained with Code and Examples

Aniruddha Chaudhari/52677/10
CodePython

Table of Contents

  • Basic Python 3 Syntax
    • 1. Print Statement
    • 2. Comment
    • 3. Variable Declaration
    • 4. String Variable
    • 5. Arithmetic Operations
    • 6. if-else Statement
    • 7. for loop
    • 8. Definition/Function
    • 9. Taking User Input from Keyboard
    • 10. List in Python
    • 11. Tuple in Python
    • 12. Dictionary in Python
    • 13. __name__ and __main__ in Python
    • 14. File Handling (Read/Write Operations)
    • 15. Bitwise Operators in Python
  • Conclusion

Basic Python 3 Syntax

Each syntax is explained with a Python programming example.

Let’s dive in…

1. Print Statement

print('Hello, world!') #Hello, world!

Printing variable data:

strName = "Chris"
print('My name is', strName) #My name is Chris

2. Comment

The comment is the part of the code that does not get executed.

In programming, it is mainly used for describing the logic of the code and for other purposes.

One-line comment:

#this is my first comment

Multi-line comment:

'''
I am new to Python language.
It is an amazing programming language.
You should start learning.
'''

3. Variable Declaration

Python has a dynamic data type. You don’t need to specify the data type of the variable while declaring. The data type of the variable is decided based on the type of data passed to the variable.

Example:

var = 10 #integer variable

var = "Why does everyone love Python?" #string variable

4. String Variable

In programming, the string is the set of characters.

Declaring string variable:

myStr = 'My string'

Or

myStr = "This is the string"

Declaring Multi-line string variable:

myStr = ''' String is very useful data structure.
There are many functions available in Python
to manipulate the string variable.'''

5. Arithmetic Operations

varA = 20
varB = 6
 
#addition
print(varA+varB) #26
 
#subtraction
print(varA-varB) #14
 
#multiplication
print(varA*varB) #120
 
#division
print(varA/varB) #3.3333333333333335
 
#modular
print(varA%varB) #2

Here, division operation is interesting. In Python 3, 20/6 gives 3.3333333333333335. Whereas, in Python 2, 20/6 gives 3. All other arithmetic operations give the same result in Python 2 and Python 3 versions. Try executing code online to know things practically.

Apart from integer, there are various other numeric data types in Python.

6. if-else Statement

if statement:

var = 10
if var > 0:
    print("It is a positive number.")

if-else statement:

var = -10
if var > 0:
    print("It is a positive number.")
else:
    print("It is not a positive number.")

7. for loop

Loop is used to execute the same lines of code multiple times.

Example: Print the number from 1 to 9.

for i in range(1,10):
  print(i)

Read more about the range() method.

8. Definition/Function

There are two parts. First, you have to declare the function. Then call the function to execute the code written inside the function.

def myFirstFunc():
   print("Thanks for calling!")

myFirstFunction() #calling function

9. Taking User Input from Keyboard

You can also take the user input from the keyboard.

strName = input("Enter your good name:")
print(strName)

10. List in Python

The list is somewhat similar to the array in C/C++ programming. It stores multiple values in one variable.

Example: Create an employee list that stores the employee-id, name, and salary.

empList = [45, 'Alice', 2560]
 
print(empList[0]) #45
print(empList[1]) #Alice
print(empList[2]) #2560
 
#looping over all the elements in the list.
for i in empList:
    print(i)

11. Tuple in Python

The tuple is a little bit different from the list in Python.

Example: Create a Python tuple to store the employee data like employee id, name, salary.

empTup = (45, 'Alice', 2560)
 
print(empTup[0]) #45
print(empTup[1]) #Alice
print(empTup[2]) #2560

Read the difference between list and tuple in Python.

12. Dictionary in Python

The Dictionary variable stores the key-value pair.

Example: Create a dictionary that stores the employee id and his/her name.

empDict = {12: 'Mark', 45: 'Bob'}
 
#accesing dictionary value from its key
print(empData[12]) #Mark
print(empData[45]) #Bob

You can perform various operations on the dictionary. Read detail in the Python dictionary tutorial.

13. __name__ and __main__ in Python

When you run your Python program, the interpreter does the following things.

  • It sets some important variable, one of that is __name__.
  • Set the value of __name__ variable as "__main__"
  • And then start executing the code in the file.

You might have seen this variable in most of the Python program files. Aren’t you?

Example:

def myFirstFunction():
    print("Thanks for calling.")

def mySecondFunction():
    print("I like Python Programming.")

if __name__ == "__main__":
    myFirstFunction()
    mySecondFunction()

What is the use and purpose of it in Python 3?

Every time we run this Python program, the “if” condition will be true and the code inside this block will be executed.

We can set the flow of our program by checking the value of a __name__ variable.

14. File Handling (Read/Write Operations)

I have explained all the syntaxes in another tutorial on file handling in Python.

It covers all the file-related operations in Python like – How to create and open a text file? How to read and write a text file?

Go through it.

15. Bitwise Operators in Python

There are basically 6 bitwise operators defined in Python – AND, OR, NOT, XOR, RIGHT SHIFT, and LEFT SHIFT.

Check Python bitwise operators where I have explained each operator with examples.

Conclusion

This is all about basic Python 3 syntax with the code.

If you are preparing for Job or any competitive programming contest, bookmark this page. Whenever required you can easily go through all these syntaxes.

You can never learn programming simply by going through these syntaxes. Try to use these concepts and code in your Python programming. Practicing is the only way of harnessing any computer programming language.

If you have any doubt or if you have any questions, ask me in the comment.

Happy Pythoning!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Sumanth
    July 4, 2019 at 4:18 pm

    Your blog is excellent, I request you to revisit and update the following sections

    6. if-else Statement

    Replace printf with print in both the statements

    7. for loop

    Replace colon with a comma in range method.

    • Reply
      Aniruddha Chaudhari
      July 4, 2019 at 5:42 pm

      Thanks for the correction, Sumanth!

      Edited. Please have a look.

      I am so glad you like my blog. Please give me a minute and submit your feedback (https://www.csestack.org/feedback/) about my Python tutorial.

  • Reply
    Janki Jodhani
    April 18, 2020 at 4:52 pm

    Your blog is excellent and I learn new things from this blog, I request you to revisit and update the following sections
    11. Tuple in python
    Replace print(empTup(0)) with print(empTup[0]) in all statement of tuple.

    • Reply
      Aniruddha Chaudhari
      April 19, 2020 at 9:49 am

      We fixed it.

      Thanks, Janki for your kind words!

      Take Care!

  • Reply
    Kyle Sallee
    July 6, 2021 at 5:23 am

    The arithmetic operator comments are incorrect.
    The integers when divided by print 3.3333333333333335
    is printed.

    • Reply
      Aniruddha Chaudhari
      July 8, 2021 at 3:31 pm

      Thanks for the correction.

  • Reply
    Russell Semen
    July 23, 2021 at 11:41 pm

    In both 10. List in Python and 11. Tuple in Python, empList([2]) is initialized as 2560 but the print of empList([2]) is transposed to 2506

    EmpList = [45, 'Alice', 2560]
    print(empList[2]) #2506
    
    • Reply
      Aniruddha Chaudhari
      September 14, 2021 at 6:15 pm

      It’s by mistake. Thanks for letting us know. Fixed it.

  • Reply
    Russell Semen
    July 24, 2021 at 7:39 am

    I get the following on the division in Python 2:
    Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
    [GCC 7.3.0] on linux2
    Type “help”, “copyright”, “credits” or “license” for more information.

    >>> print(20/6)
    3
    >>> six=6
    >>> twenty=20
    >>> print(twenty/six)
    3
    
    • Reply
      Aniruddha Chaudhari
      July 25, 2021 at 12:23 pm

      This is expected in Python 2.

      If you run the same code in Python 3, you will get the output as 3.3333333333333335.

      >>> 20/6
      3.3333333333333335
      

Leave a Reply Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard