Python Basics: Comments, Indentation, Variables, Data Types, Operators, Strings, Lists, Conditionals, Loops, and Functions
This comprehensive tutorial introduces Python fundamentals, covering comments, indentation, variable naming rules, core data types, type conversion, arithmetic and comparison operators, string manipulation, list operations, conditional statements, loop constructs, and custom function definitions with clear examples and code snippets.
Before diving into statistical analysis with Python, it is essential to master the basic syntax and common operations of the language. This guide consolidates the most frequently used Python constructs to help beginners quickly become familiar with core concepts.
1. Comments and Indentation
Comments
Comments do not affect program execution and improve readability.
Single‑line comments start with # :
<code># comment on its own line
print("Python statistical analysis") # print output</code>Running the above prints:
<code>Python statistical analysis</code>Indentation
Python uses indentation to define code blocks. The PEP 8 style guide recommends four spaces per level and discourages mixing spaces with tabs.
Although any number of spaces or tabs can technically be used, it is strongly recommended to follow the PEP 8 guideline of using 4 spaces as the indentation unit.
All statements in the same block must have the same indentation:
<code>if True:
print("True")
else:
print("False")</code>Inconsistent indentation causes a runtime error:
<code>if True:
print("Answer")
print("True")
else:
print("Answer")
print("False") # Indentation mismatch</code>2. Variable Naming
Python variables are created by assignment without explicit type declaration:
<code>x = 10 # integer
y = "Python statistical analysis" # string
z = 3.14 # float</code>Rules
Names may contain letters (A‑Z, a‑z), digits (0‑9), and underscores ( _ ).
The first character must be a letter or underscore; it cannot be a digit.
Variable names are case‑sensitive ( myVariable ≠ myvariable ).
Names cannot be Python reserved keywords (e.g., for , if , while , class ).
Use meaningful names; follow PEP 8 by using lowercase words separated by underscores, e.g., employee_name instead of EmployeeName or employeename .
3. Data Types
Numeric Types
int : arbitrary‑size integers, e.g., 123 , -456 .
float : floating‑point numbers, e.g., 3.14 , -2.0 .
complex : numbers with real and imaginary parts, e.g., 3+2j .
Boolean
Two values: True and False .
String ( str )
Text enclosed in single or double quotes, e.g., "Hello, World!" .
Sequence Types
list ( [] ): ordered, mutable collection, e.g., [1, 2, "three"] .
tuple ( () ): ordered, immutable collection, e.g., (1, 2, 3) .
Mapping Type
dict ( {} ): unordered key‑value pairs, e.g., {"name": "Alice", "age": 25} .
Set Type
set ( {} for non‑empty sets, set() for an empty set) stores unordered, unique elements.
Other Special Types
NoneType ( None ) represents the absence of a value.
4. Type Conversion
Implicit Conversion
When mixing types, Python automatically promotes to the higher‑precision type:
<code>num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("num_int type:", type(num_int))
print("num_flo type:", type(num_flo))
print("num_new value:", num_new)
print("num_new type:", type(num_new))</code>Explicit Conversion
Use built‑in functions such as int() , float() , str() :
<code>x = int(1) # 1
y = int(2.8) # 2
z = int("3") # 3
print(x, type(x))
print(y, type(y))
print(z, type(z))
</code>5. Operators
Arithmetic
Assuming a = 10 and b = 21 :
Operator
Description
Example
+
Addition
a + b → 31
-
Subtraction
a - b → -11
*
Multiplication
a * b → 210
**
Exponentiation
a ** b → 10⁽²¹⁾
/
Division
b / a → 2.1
//
Floor division
b // a → 2
%
Modulo
b % a → 1
Comparison
With a = 10 , b = 20 :
Operator
Description
Result
==
Equal
(a == b) → False
!=
Not equal
(a != b) → True
>
Greater than
(a > b) → False
<
Less than
(a < b) → True
>=
Greater or equal
(a >= b) → False
<=
Less or equal
(a <= b) → True
Assignment
Common operators include = , += , -= , *= , /= , %= , **= , //= .
6. Strings
Creation
<code>str1 = 'Hello, World!'
str2 = "This is also a string."
</code>Access
<code>greeting = "Hello!"
first_char = greeting[0] # 'H'
</code>Slicing
<code>sub_str = greeting[0:5] # 'Hello'
</code>Length
<code>length = len(greeting) # 6
</code>Concatenation and Repetition
<code>name = "Alice"
message = "Hi, " + name + "!"
repeated = "Python " * 3 # 'Python Python Python '
</code>Formatting
<code>num = 42
formatted = f"The answer is {num}" # f-string
</code>Common Methods
lower() , upper()
strip()
split()
join()
find() , index()
replace(old, new)
7. Lists
Creation
<code>empty_list = []
numbers_list = [1, 2, 3, 4, 5]
mixed_list = [1, "apple", True, None]
another_list = list(("a", "b", "c"))
</code>Access and Slicing
<code>lst = ["apple", "banana", "cherry"]
first_item = lst[0] # 'apple'
last_item = lst[-1] # 'cherry'
sublist = lst[1:3] # ['banana']
</code>Modification
<code>lst[0] = "grape"
lst.append("date")
lst.insert(0, "kiwi")
removed = lst.pop() # last element
lst.pop(0) # remove first element
lst.remove("apple")
lst.extend([6,7])
lst.sort()
lst.reverse()
len_lst = len(lst)
count = lst.count("banana")
</code>8. Conditional Statements
<code>if condition:
# true block
elif other_condition:
# else‑if block
else:
# false block
</code>Example:
<code>temperature = 25
if temperature > 20:
print("It's warm outside.")
</code>9. Loop Statements
while Loop
<code>count = 0
while count < 5:
print(count)
count += 1
</code>for Loop
<code>numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
</code>Control keywords:
break – exit the loop immediately.
continue – skip the rest of the current iteration.
<code>for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i) # prints odd numbers
j = 0
while j < 10:
j += 1
if j == 5:
break # exit when j reaches 5
print(j)
</code>10. Custom Functions
<code>def greet(name):
print(f"Hello, {name}!")
greet("Bob") # Output: Hello, Bob!
</code>Function definition uses the def keyword, optional parameters, default values, and variable‑length arguments ( *args , **kwargs ). Functions may return a value with return ; otherwise they return None .
Parameter Types
Required positional parameters.
Keyword parameters (named arguments).
Default parameters with preset values.
Variable‑length parameters: *args for extra positional arguments, **kwargs for extra keyword arguments.
<code>def add_numbers(*nums):
total = sum(nums)
return total
result = add_numbers(1,2,3,4)
print(result) # 10
</code>References
Python 3 Tutorial | 菜鸟教程
Python Official Documentation
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.