Function Parameter Passing
In Python, passing parameters to a function is essentially an assignment operation.
def func(arr):
arr = 1
print(arr)
a = 2
func(a)
print(a)
- First, there are two variables
arranda, and two objects1and2. ais bound to2, andfunc(a)assigns the object2bound toatoarr.- At this point, object
1has not been created yet, and object2is labeled with bothaandarr. - The operation
arr = 1removes thearrlabel from2, creates object1, and assigns it toarr. - Output:
1
2
Input and Output
The print() Function
>>> print("string")
string
>>> print("str1", "str2", "str3")
str1 str2 str3 # Spaces replace commas
print(a + b ** c) # Computes the value first, then prints
print(sum(a, b / c)) # Executes the sum() function first
Prototype:
sepparameter: Separator between multiple outputs (return values). Default is a space, but can be manually set.endparameter: How to end the print. Default is\n(newline), can be set to' 'to avoid line breaks.
The input() Function
Gets user input and saves it as a string.
If the input is a number, it can be converted to an integer using int().
>>> age = input("Please input your age: ")
Please input your age: 18
>>> print(age)
'18' # type(age) == <class 'str'>
>>> age = int(age)
>>> print(age)
18
input()can take a string argument, which is printed as a prompt.- When using
int(), extra spaces can be removed with thestrip()method. This also applies when saving string objects. input()can be used to consume a newline and pause program execution.
[[Data Types and Operators#String Formatting]]
Utility Functions
id()
Example:
[[Data Types and Operators#Assignment Methods]]id(variable_name) returns the memory address of the object bound to the variable.
If the object bound to the variable changes, the query result changes, but the original object’s memory address remains unchanged.
type()
- With one argument, returns the type of the object.
- With three arguments, returns a new object type:
type(name, bases, dict)name— The name of the class.bases— A tuple of base classes.dict— A dictionary, the namespace variables defined within the class.
# One argument example
>>> type(1)
<type 'int'>
>>> type('runoob')
<type 'str'>
>>> type([2])
<type 'list'>
>>> type({0: 'zero'})
<type 'dict'>
>>> x = 1
>>> type(x) == int # Check if types are equal
True
# Three arguments
>>> class X(object):
... a = 1
...
>>> X = type('X', (object,), dict(a=1)) # Creates a new type X
>>> X
<class '__main__.X'>
next()
[[Basic Data Structures#Iterator Objects]]
String Functions
Built-in String Methods
- Remove leading/trailing spaces or characters:
lstrip(),rstrip(),strip()
str = " 人生苦短,我用Python。 "
print(str.lstrip()) # Remove left spaces and print
print(str.rstrip()) # Remove right spaces and print
print(str.strip()) # Remove both left and right spaces and print
str_1 = '333与君相别离,不知何日是归期,我如朝露转瞬晞。333'
print(str_1.strip('3')) # Remove all '3' characters from both ends and print
Note: These functions essentially return a new substring rather than modifying the original object.lstrip() returns a new string with leading spaces or specified characters removed.
str = " 人生苦短,我用Python。 "
str.lstrip() # Only calls the function without assignment or output
print(str)
'''
Output remains:
人生苦短,我用Python。
With spaces on both ends, indicating the object is unchanged.
'''
- Check if a string starts/ends with a substring:
startswith(),endswith()
ReturnsTrueif yes,Falseotherwise.
str = "山有木兮木有枝,心悦君兮君不知。"
print(str.startswith("山")) # Returns True and prints
print(str.endswith('不知')) # Missing '。', returns False and prints
Format strings:
$$f"string content {other_string_variable} string content"$$
Returns the formatted string.
To be filledSplit strings:
split()
Splits a string into substrings using a delimiter (excluded from substrings) and returns a list.
str = '根,紧握在地下,叶,相触在云里,每一阵风过,我们都互相致意。'
strP = str.split(',') # Note Chinese punctuation
print(str) # Outputs the original string
print(strP) # Outputs the split string list
print(strP[1]) # Outputs "紧握在地下"
Numeric Functions
- Absolute value:
abs() - Integer conversion:
int() - Rounding (returns integer):
round() - Check size or truthiness (Boolean functions):
bool()
[[Data Types and Operators#Boolean Values and Null]]
Type Conversion Functions
- $$int(x [, base])$$
xis the original object,baseis optional (default 10 for decimal). - $$float(x)$$
- $$complex(real[, imag])$$
realis the real part,imagis the optional imaginary part. - $$str(x)$$
- $$repr(x)$$
Convertsxto an expression string (readable by the Python interpreter). - $$chr(x)$$
Converts an integer to a character. - $$ord(x)$$
Converts a character to its integer value. - $$hex(x)$$
Converts an integer to a hexadecimal string. - $$oct(x)$$
Converts an integer to an octal string. - $$eval(str)$$
Evaluates a string as a Python expression and returns an object. - $$tuple(s)$$
Converts sequencesto a tuple. - $$list(s)$$
- $$set(s)$$
Converts sequencesto a mutable set. - $$frozenset(s)$$
Converts sequencesto an immutable set. - $$dict(d)$$
Converts a sequencedof (key, value) tuples to a dictionary.
High and Low Data Types
- “Higher” and “lower” data types refer to precision in implicit type conversion.
- Precision reflects the amount of information a data type can represent.
- Higher types can represent more information (e.g., floats > integers).
- Order: Boolean (
bool) < Integer (int) < Float (float) < Complex (complex).
Can Data Types Be Converted Freely?
While Python provides functions like int(), float(), str(), etc., not all conversions are possible. It depends on whether the data contains enough information for the target type.
Examples:
- Integers can be converted to strings (e.g.,
123→"123"). - Numeric strings (e.g.,
"123") can be converted to integers or floats.
Exceptions:
- Non-numeric strings (e.g.,
"Hello") cannot be converted to numbers. - Lists or tuples can be converted to sets (if elements are immutable) but not to integers.
Conditional and Loop Statements
if, elif, else Statements
if condition1:
# Execute if condition1 is True
elif condition2:
# Execute if condition1 is False and condition2 is True
else:
# Execute if both conditions are False
Example:
name = input('Who are you?')
age = input('How old are you?')
if name == '朱冰倩' and age >= 19:
print('Daring, long time no see.')
elif name == '朱冰倩' and age == 18:
print('Thank you for being in my life.')
else:
print('こんにちわ。')
- Falsy values:
None, empty lists, empty sets, empty dicts, empty tuples, empty strings,0,False. - Truthy values: Non-empty sequences, non-zero numbers,
True.
for, break, continue Statements
Basic Loop
for x in sequence: # list, dict, string, tuple, etc.
# Code block
foriterates over the sequence, assigning each element tox.
Indexed Loop
- Use
enumerate()to get both index and value. enumerate(sequence, [start=0]):sequence: Iterable object.start: Optional starting index (default 0).
galgames = ['咖啡馆', '千恋万花', '天使骚骚']
for index, galgame in enumerate(galgames, 1):
print(f'Today, play the {index}th game: {galgame}.')
Output:
Today, play the 1th game: 咖啡馆.
Today, play the 2th game: 千恋万花.
Today, play the 3th game: 天使骚骚.
break
Exits the current loop. Different levels of break exit different loops.
continue
Skips the rest of the loop and proceeds to the next iteration.
for-else
- An
elseblock afterforexecutes if the loop completes normally (withoutbreak). continueis considered normal.
while
while condition:
# Code block
Executes the code block while condition is True.
Avoid infinite loops by ensuring the condition can be broken or break is triggered.
while-else
Similar to for-else, the else block executes if the loop exits normally (without break).

When will I have a drink and discuss the details again?