Python Environment Setup
Download the Python interpreter from the official website: https://www.python.org/downloads/
For development, PyCharm IDE can be activated using verification codes from http://idea.lanyus.com/
Script Header Configuration
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Example
# Description: Multi-function script
# Created: 2018-08-13
# Execution: python script_name.py
Linux Package Manager Configuration
Configure pip source on Linux by creating or modifying ~/.pip/pip.conf:
[global]
timeout = 6000
index-url = http://pypi.douban.com/simple
trusted-host = pypi.douban.com
Python Script Execution Methods
Execute Python scripts using the Python interpreter directly. Python files can have any extension.
Character Encoding Systems
- ASCII: 8-bit character encoding
- Unicode: 16-bit universal character set
- UTF-8: Variable-length Unicode compression
- GBK: Chinese character encoding standard
Example: The Chinese characters "李杰" occupy 6 bytes in UTF-8 and 4 bytes in GBK encoding.
Comments
Single-line: # Comment text
Multi-line: """Comment text"""
Variable Declaration and Usage
#!/usr/bin/env python
# -*- coding: utf-8 -*-
username = 'admin' # Variable assignment
username # Variable reference
print(username) # Print variable value
Variable Naming Rules
- Variable names can contain letters, numbers, and underscores
- Cannot start with a number
- Avoid Python keywords:
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] - Use meaningful names
- Case-sensitive
- Recommended naming conventions: camelCase or snake_case
Basic Input/Output
# Simple input/output
user_input = input('Enter username: ')
pass_input = input('Enter password: ')
print(user_input, pass_input)
# Secure password input
import getpass
user_id = input('Username: ')
secure_pass = getpass.getpass('Password: ')
print(user_id, secure_pass)
# Authentication example
import getpass
stored_user = 'alex'
stored_pass = 'as123'
input_user = input('Username: ')
input_pass = input('Password: ')
if stored_user == input_user and stored_pass == input_pass:
print(f'Welcome {stored_user}!')
else:
print('Invalid credentials')
Loop Structures
For Loops
# Basic range iteration
for counter in range(10):
print('Iteration', counter)
# Range with parameters
for index in range(0, 10, 3):
print('Step', index)
# Continue statement
for value in range(10):
if value < 3:
print('Value:', value)
else:
print('Skipping...')
continue
print('Processing...')
# Nested loops with break
for outer in range(9):
print('Outer:', outer)
for inner in range(11, 50):
print('Inner:', inner)
if inner >= 22:
break
Data Types
Numeric Types
- int: Integer values (-9223372036854775808 to 9223372036854775807)
- float: Floating-point numbers (e.g., 3.23, 52.3E-4)
- complex: Complex numbers (e.g., -5+4j)
Boolean Values
- True or False (1 or 0)
Strings
Text sequences: "hello world"
Type Conversion Functions
int(x[, base]): Convert to decimal integerfloat(x): Convert to floating-pointstr(object): Convert to stringtuple(seq): Convert sequence to tuplelist(seq): Convert sequance to listchr(x): Integer to characterord(x): Character to integer valuehex(x): Integer to hexadecimal stringoct(x): Integer to octal string
Operators
Arithmetic Operators
+ # Addition
- # Subtraction
* # Multiplication
/ # Division
% # Modulus
** # Exponentiation
// # Floor division
Comparison Operators
== # Equal
!= # Not equal
> # Greater than
< # Less than
>= # Greater than or equal
<= # Less than or equal
Logical Operators
and # Logical AND
or # Logical OR
not # Logical NOT
Bitwise Operators
& # Bitwise AND
| # Bitwise OR
^ # Bitwise XOR
~ # Bitwise NOT
<< # Left shift
>> # Right shift
Operater Precedence
- ** Exponentiation
- ~, +, - (unary)
- *, /, %, //
- +, - (binary)
- <<, >>
- &
- ^, |
- Comparison operators
- Assignment operators
- Identity operators
- Membership operators
- Logical operators
Ternary Operator
result = value1 if condition else value2
Number Systems
- Binary: Base-2 (0-1)
- Octal: Base-8 (0-7)
- Decimal: Base-10 (0-9)
- Hexadecimal: Base-16 (0-9, A-F)
Programmming Exercises
Print Numbers 1-10 (Skip 7)
counter = 1
while counter < 11:
if counter != 7:
print(counter)
counter += 1
Sum of 1-100
total = 0
number = 1
while number < 101:
total += number
number += 1
print(total)
Even Numbers 1-100
value = 1
while value < 101:
if value % 2 == 0:
print(value)
value += 1
Alternating Sum 1-99
current = 1
result = 0
while current < 100:
if current % 2 == 0:
result -= current
else:
result += current
current += 1
print(result)
Login System with Retry
import getpass
correct_user = "zhao"
correct_pass = "123456"
attempts = 0
while attempts < 3:
input_user = input("Enter username: ")
input_pass = input("Enter password: ")
if input_user == correct_user and input_pass == correct_pass:
print("Access granted")
break
elif not input_user or not input_pass:
print("Fields cannot be empty")
attempts += 1
else:
print("Invalid credentials")
attempts += 1
Control Structures
Conditional Statements
# Basic if statement
value = 5
if value > 2:
print('Condition met')
# If-else structure
if value > 8:
print('High value')
else:
print('Low value')
# If-elif-else chain
if value > 8:
print('High')
elif value > 3:
print('Medium')
else:
print('Low')
For Loop Examples
# Iterate through range
for i in range(5):
print(i)
# List iteration
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
# Sum calculation
sum_total = 0
for x in range(101):
sum_total += x
print(sum_total)
Chicken Problem Solution
for roosters in range(1, 20):
for hens in range(1, 33):
chicks = 100 - roosters - hens
if (chicks % 3 == 0) and (roosters * 5 + hens * 3 + chicks / 3 == 100):
print(f"Roosters: {roosters}; Hens: {hens}; Chicks: {chicks}")
While Loop with Break/Continue
# Break example
n = 1
while n <= 100:
if n > 10:
break
print(n)
n += 1
# Continue example
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue
print(num)