Fundamentals 11 min read

Master Python Basics: Syntax, Operators, and Control Flow Explained

This article introduces Python's basic syntax, execution order, coding conventions, common operators, input/output handling, conditional statements, ternary expressions, and loop structures, and demonstrates a simple dice‑guessing game that highlights the use of break and continue.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Basics: Syntax, Operators, and Control Flow Explained

Python Basic Syntax

Execution Order

Top to bottom

Left to right

Code Conventions

Module and package names should be lowercase; use underscores to separate words.

Avoid using built‑in names such as doc, txt, etc.

Keep each line reasonably short.

Do not use ambiguous single‑letter variable names like i, l, o because they can be confused with numbers.

Do not shadow Python built‑in identifiers; you can check them with the keyword module:

import keyword
print(keyword.kwlist)

Most editors provide automatic formatting (e.g., PyCharm: Ctrl+Alt+L, VS Code: Alt+Shift+F).

Before formatting the code may look messy, but after formatting it becomes clean and readable.

Unformatted code
Unformatted code
Formatted code
Formatted code

Indentation

Python uses indentation, not braces, to define code blocks. Mixing tabs and spaces is discouraged.

Indentation example
Indentation example

Common Operators

# Arithmetic operators
+ - * /      # addition, subtraction, multiplication, division
**          # exponentiation, e.g., 2**3 -> 8
%           # modulo, e.g., 9%2 -> 1
//          # floor division, e.g., 9//2 -> 4
# Membership
in          # check presence
not in      # check absence
# Logical operators
not         # negation
and         # both True
or          # either True
# Comparison operators
==  !=  <>  >  >=  <  <=
# Identity operators
is          # compare object IDs

Human‑Computer Interaction

# Prompt the user for a name and greet them
name = input('Please enter your name:')
print('Hello ' + str(name) + '!')
Input example
Input example

Conditional Statements

Simple if statement

# Assume the input is a numeric string
num = input('Enter a number:')
num = int(num)
if num % 2 == 0:
    print('The number you entered is even')
print('Program ends')

if...else... statement

age = int(input('Please enter your age:'))
if age > 0:
    print('Your age is', age)
else:
    print('Please do not joke around')
print('Program ends')

if...elif...else statement

score = int(input('Enter your score (0‑100):'))
if score > 100:
    print('Impossible score!')
elif score >= 90:
    print('Great performance, you get a trip')
elif score >= 80:
    print('Good, celebrate with a nice meal')
elif score >= 70:
    print('Average, keep trying')
elif score >= 60:
    print('Score is risky')
elif 0 <= score < 60:
    print('Fail, prepare for consequences')
else:
    print('Negative score?')

Ternary Expression (Conditional Expression)

# Syntax: value_if_true if condition else value_if_false
age = int(input('Enter your age:'))
res = 'You can be an uncle now' if age >= 30 else 'Still a kid, just an older brother'
print(res)

Loops

range(start, stop[, step])

for i in range(10):
    print(i)
for i in range(10, 30):
    print(i)
for i in range(10, 30, 2):
    print(i)
# Change end character
for i in range(10):
    print(i, end=' ')
for i in range(10):
    print(i, end='\t')

Simple for loop over a string

str1 = 'hello world'
for ch in str1:
    print(ch, end='')
# Replace spaces with commas
for ch in str1:
    if ch == ' ':
        ch = ','
    print(ch, end='')

Simple while loop

count = 0
res = 0
while count < 11:
    res += count
    count += 1
else:
    print('Loop ended normally')
print('Program continues')
print('Sum of 1‑10 is:', res)

Infinite loop

while True:
    print('Running forever')
print('This line is never reached')
# Stop with Ctrl+C

Loop control statements

pass

: do nothing continue: skip to next iteration break: exit the loop

for i in range(10):
    if i > 3:
        pass
    else:
        print('Number ≤3:', i)

for i in range(10):
    if i == 2:
        continue
    print(i)

for i in range(10):
    if i == 2:
        break
    print(i)

Dice‑Guessing Game (Practice)

# Import module
import random
while True:
    random_num = random.randint(1, 6)
    print(random_num)
    while True:
        num = input('Enter a number (1‑6):').strip()
        if len(num) >= 2 or not num.isdigit():
            print('Please enter a single digit between 1 and 6')
            continue
        if int(num) > 6 or num == '0':
            print('Please enter a number between 1 and 6')
            continue
        print(num)
        if random_num != int(num):
            print(num + ' is not correct')
            continue
        print('Congratulations, {} is correct!'.format(num))
        break
    decide = input('Enter N to quit, any other key to continue:')
    if decide.upper() != 'N':
        continue
    break
print('Program ends')
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonsyntaxLoopsoperatorsControl Flow
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.