Type Conversion Essentials
メニューを表示するにはスワイプしてください
Type conversion lets you move between core Python types so values can be compared, calculated, or displayed.
Converting to int
int(x) makes an integer.
- From an int: returns the same number;
- From a float: truncates toward zero (for example,
int(2.9)returns2,int(-2.9)returns-2); - From a string: the string must represent an integer (optional spaces and sign are ok).
Python also allows underscores inside digits, such as
"1_000"— but only if:- The underscore is between digits;
- It is not at the beginning or end (
"_100","100_"); - It is not repeated or adjacent to a decimal point (
"1__000","1_.5").
Valid Conversions
1234567age_input = " 42 " print(int(age_input)) # 42 print(int(2.9)) # 2 print(int(-2.9)) # -2 print(int("7")) # 7 print(int(" -15 ")) # -15 print(int("1_00_0")) # 1000
These Raise ValueError
12int("2.5") # ValueError - not an integer string int("42a") # ValueError
Converting to float
float(x) makes a floating-point number.
- Works for ints and decimal or scientific-notation strings (
"3.14","1e2","5E-3"); - Commas are not decimal points in Python (
"2,5","2.5"); - Python allows underscores inside digits in numeric strings, but only if:
- The underscore is between digits;
- It is not at the beginning or end (
"_3.14","3.14_"); - It is not adjacent to the decimal point or repeated (
"3_.14","3.__14"); - Scientific notation also must follow these rules (
"1e_3").
Valid Conversions
1234print(float(3)) # 3.0 print(float("2.5")) # 2.5 print(float("1e3")) # 1000.0 print(float("1_000.1_234")) # 1000.1234
These Raise ValueError
1float("2,5") # ValueError - use a dot, not a comma
Converting to str
str(x) makes a human-readable string representation. Prefer f-strings when you are building messages.
123print(str(42)) # "42" print(str(3.5)) # "3.5" print(f"Ada scored {98} points.")
Converting to bool
bool(x) follows Python truthiness rules.
- Numbers:
0isFalse, any other number isTrue; - Strings:
""(empty) isFalse, any non-empty string isTrue(even"0"and"False").
12345print(bool(0)) # False print(bool(7)) # True print(bool("")) # False print(bool("0")) # True print(bool("False")) # True
Mistakes to Avoid
int("2.5")raisesValueError- parse asfloat()first, then truncate or round;- Locale habit:
"2,5"is invalid - use"2.5"; - Truthiness surprise:
bool("0")isTrue- compare string contents explicitly if needed, for examples == "0".
1. Which call raises a ValueError?
2. Pick the correct statement.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 4. 章 1
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 4. 章 1