Python Basic Syntax Fundamentals
Literals
Literals are fixed values explicitly written in code. Python supports six common literal types. String literals must be enclosed in double quotes ("), meaning any quoted text is a string.
Output literals using print():
print(42)
print(-7)
print("Greetings, Python")
Output:
42
-7
Greetings, Python
By default, print() adds a newline. Use end='' to prevent this:
print("Hi", end='')
print("World", end='')
Output: HiWorld
Comments
Comments explain code and are ignored during execution. They enhance readability.
Single-Line Comments
Start with #, followed by explanatory text (recommended to separate # and text with a space):
# Define an integer literal
42
# Define a float literal
3.14
# Define a string literal
"Greetings, Python"
# Output literals via print
print(42)
print(3.14)
print("Greetings, Python")
Output:
42
3.14
Greetings, Python
Multi-Line Comments
Enclose text in triple double quotes ("""):
"""
Demonstrates outputting literals using print statements
"""
# Output literals
print(42)
print(3.14)
print("Greetings, Python")
Output same as above.
Variables
Variables store runtime data, avoiding repetition. Their values can change. Define with variable_name = value.
Example:
# Track account balance
balance = 100
print("Current balance:", balance, "units")
# Buy coffee: spend 15 units
balance = balance - 15
print("Remaining balance:", balance, "units")
Output:
Current balance: 100 units
Remaining balance: 85 units
Data Types
Common beginner types: integers, floats, strings. Strings have three definition styles:
# Double quotes
greeting = "I am a string"
# Single quotes
message = 'I am also a string'
# Triple quotes (multi-line)
multiline_text = """I am a string
spanning multiple lines"""
print(greeting)
print(message)
print(multiline_text)
Output:
I am a string
I am also a string
I am a string
spanning multiple lines
Check types with type():
- Direct print:
print(type("Hello"))
print(type(42))
print(type(3.14))
Output: <class 'str'>, <class 'int'>, <class 'float'>
- Store result in variable:
str_type = type("Hello")
int_type = type(42)
float_type = type(3.14)
print(str_type, int_type, float_type)
- Check variable-stored data type:
username = "Alice"
name_type = type(username)
print(name_type) # <class 'str'>
Note: Variables have no inherent type; they reflect the type of stored data.
Type Conversion
Convert between types for input processing, calculations, or storage. Conversoin creates new objects; original data remains unchanged.
Common conversions:
- Any type → string:
str(x) - Numeric string → int/float:
int(x),float(x)(string must contain only numbers) - Float → int: discards decimal part
Examples:
# Number to string
str_num = str(25)
str_float = str(7.89)
print(type(str_num), str_num) # <class 'str'> 25
print(type(str_float), str_float) # <class 'str'> 7.89
# String to number
int_val = int("25")
print(type(int_val), int_val) # <class 'int'> 25
# Float to int (precision loss)
int_from_float = int(12.89)
print(type(int_from_float), int_from_float) # <class 'int'> 12
Identifiers
Identifiers name variables, classes, or functions. Follow rules and conventions.
Rules
- Allowed characters: letters (A-Z/a-z), digits (0-9), underscores (_). No digits at start. Avoid Chinese (potential issues).
- Case-sensitive:
Age≠age. - Avoid keywords (reserved words like
if,for,class).
Keyword examples (case-sensitive):
| Keyword | Purpose |
|---|---|
| True/False | Boolean values |
| None | Null value |
| if/elif/else | Conditionals |
| for/while | Loops |
| def/class | Define function/class |
| return/yield | Return values |
| import/from | Module imports |
Example (valid vs invalid):
# Valid
UserAge = 30
user_name = "Bob"
# Invalid (keyword)
class = 5 # SyntaxError
Conventions
- Descriptive names:
account_balanceoverab - Snake_case:
total_scoreinstead oftotalScore - Lowercase letters:
username, notUserName
Opertaors
Perform operations on data.
Arithmetic Operators
print(f"5 + 3 = {5 + 3}") # 8
print(f"10 - 4 = {10 - 4}") # 6
print(f"7 * 2 = {7 * 2}") # 14
print(f"15 / 3 = {15 / 3}") # 5.0
print(f"17 // 5 = {17 // 5}") # 3 (floor division)
print(f"17 % 5 = {17 % 5}") # 2 (modulo)
print(f"3 ** 4 = {3 ** 4}") # 81 (exponent)
Compound Assignment Operators
count = 5
count += 3 # 8
count *= 2 # 16
count -= 4 # 12
count /= 3 # 4.0
print(count)
Input Handling
Use input() to capture keyboard input (always returns a string). Convert types as needed.
Example:
username = input("Enter your username: ")
print(f"Welcome, {username}!")
# Convert input to integer
user_age = input("Enter your age: ")
age_num = int(user_age)
print(f"Age (numeric): {age_num}, type: {type(age_num)}")
Input "Alice" then "30" outputs:
Welcome, Alice!
Age (numeric): 30, type: <class 'int'>