Boolean Conditions and or
Lesson 9 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin conditions require Boolean; Python accepts truth values from objects. Empty containers, empty strings, zero, False and None test false. Kotlin Elvis ?: falls back only for null, whereas Python or falls back for any false-valued first operand and returns an operand. Kotlin || returns Boolean and cannot serve as an arbitrary-value fallback. In Python the nonempty string "0" tests true.
Kotlin
fun main() {
val limit: Int? = 0
println(limit ?: 10)
}Python
text = "0"
print(text or "Guest")
print(0 or 10)Porting trap
Replacing limit ?: 10 with limit or 10 loses a valid zero. Use 10 if limit is None else limit for a defined optional value.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
Challenge
BeginnerRead a display name and a limit token on two lines. The name may be empty; use Guest only for an empty name. The limit token is missing or an integer from 0 to 20. The scaffold parses it. Use a default limit of 10 only for None, preserving a real zero. Print the selected name and selected integer limit on separate lines.
Print only these lines, ending each with a newline. Keep the supplied input scaffold; it reads the stated values without prompts.
Your code goes in main.py. The locked driver.py starts your program and cannot be edited.
Try it yourself
# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module
run_module("main", run_name="__main__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler