search
HomeBackend DevelopmentPython TutorialBasic Concepts – Operators and More

Getting Started with Python Syntax and Basic Constructs

Now that you’ve got Python installed and ran your first program, let’s dive into some fundamental concepts that form the backbone of every Python program. In this post, we’ll cover Python’s syntax, operators, and input/output operations, laying the foundation for writing functional code.

1. Basic Syntax and Structure

Python’s syntax is designed to be clean and easy to read, but there are a few essential rules you need to know before diving into more complex coding.

Indentation

Unlike many other programming languages, Python uses indentation to define code blocks, not braces ({}) or keywords. This makes your code visually cleaner but also means you must be consistent with your spacing.

Code Example: Using Indentation

# Correct indentation  
if True:  
    print("This is properly indented!")  

# Incorrect indentation (will cause an error)  
if True:  
print("This is not properly indented!") 

Basic Concepts – Operators and More

Comments

Comments are used to make your code more readable and to document what it does. Python uses the # symbol for single-line comments.

# This is a single-line comment  
print("Python ignores comments when running the code.")  

For multi-line comments, use triple quotes:

"""  
This is a  
multi-line comment.  
"""  

Keywords and Identifiers

Keywords: Reserved words in Python, like if, else, for, and def. You cannot use them as variable names.

Identifiers: Names used for variables, functions, or classes. They must start with a letter or an underscore (_) and can’t include special characters.

2. Operators in Python

Operators are symbols used to perform operations on variables and values. Python offers a wide variety of operators.

Arithmetic Operators

Used for basic mathematical operations:

a = 10  
b = 3  

print(a + b)  # Addition  
print(a - b)  # Subtraction  
print(a * b)  # Multiplication  
print(a / b)  # Division  
print(a % b)  # Modulus  
print(a ** b)  # Exponentiation  
print(a // b)  # Floor division 

Comparison Operators

Compare two values and return a Boolean (True or False):

print(a > b)   # Greater than  
print(a = b)  # Greater than or equal to  
print(a 



<p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/173253464048351.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="Basic Concepts – Operators and More"></p>

<p><strong>Logical Operators</strong></p>

<p>Combine conditional statements:<br>
</p>

<pre class="brush:php;toolbar:false">x = True  
y = False  

print(x and y)  # Logical AND  
print(x or y)   # Logical OR  
print(not x)    # Logical NOT  

3. Input and Output

Taking Input

Python’s input() function allows you to interact with users by receiving input during program execution.

Code Example: Simple Input

name = input("What is your name? ")  
print(f"Hello, {name}!")  

Basic Concepts – Operators and More

Displaying Output

The print() function is used to display information. You can also use f-strings for formatted output:

# Correct indentation  
if True:  
    print("This is properly indented!")  

# Incorrect indentation (will cause an error)  
if True:  
print("This is not properly indented!") 

4. Mini Project: Basic Calculator

Let’s put everything together to create a simple calculator program that takes user input, performs basic operations, and displays the result.

Code Example: Basic Calculator

# This is a single-line comment  
print("Python ignores comments when running the code.")  

Basic Concepts – Operators and More

Practice Exercises

To solidify what you’ve learned, try these additional exercises:

  1. Even or Odd Checker: Create a program that takes a number as input and prints whether it is even or odd.
"""  
This is a  
multi-line comment.  
"""  
  1. Extended Calculator: Enhance the basic calculator by adding support for modulus and exponentiation. For example:
a = 10  
b = 3  

print(a + b)  # Addition  
print(a - b)  # Subtraction  
print(a * b)  # Multiplication  
print(a / b)  # Division  
print(a % b)  # Modulus  
print(a ** b)  # Exponentiation  
print(a // b)  # Floor division 

Conclusion

Understanding Python’s syntax, operators, and input/output operations is the first step toward becoming a confident programmer. With these foundations in place, you’re ready to tackle more advanced topics and projects.

Give the Practice Exercises a try, and let us know how you did in the comments below! We’d love to see your results and help you if you get stuck.

The above is the detailed content of Basic Concepts – Operators and More. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python's Execution Model: Compiled, Interpreted, or Both?Python's Execution Model: Compiled, Interpreted, or Both?May 10, 2025 am 12:04 AM

Pythonisbothcompiledandinterpreted.WhenyourunaPythonscript,itisfirstcompiledintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).Thishybridapproachallowsforplatform-independentcodebutcanbeslowerthannativemachinecodeexecution.

Is Python executed line by line?Is Python executed line by line?May 10, 2025 am 12:03 AM

Python is not strictly line-by-line execution, but is optimized and conditional execution based on the interpreter mechanism. The interpreter converts the code to bytecode, executed by the PVM, and may precompile constant expressions or optimize loops. Understanding these mechanisms helps optimize code and improve efficiency.

What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor