Scalar Conditions, Not Vectors
Lesson 9 of 48 in Coddy's Python for R Developers course.
R conditions need a single nonmissing logical value; numeric scalars can be coerced, with zero false and nonzero true. Python truth-tests many objects directly: empty strings, lists, and dictionaries are false, while nonempty containers are true. Python and/or short-circuit and return selected operands. R double-ampersand and double-bar are scalar short-circuit operators yielding logical results, while their single-character forms operate elementwise. Do not feed a vector-shaped result to a Python if expecting vectorized selection. NumPy arrays have their own rules, but this course teaches standard Python containers and scalar control flow, not NumPy.
R
cat(0 || 10, "\n", sep="")
cat(length(character(0)) == 0, "\n", sep="")Python
print(0 or 10)
print('' or 'empty')Porting trap
An empty Python list is false-valued. R logical(0) is not a valid scalar if condition, so port the desired emptiness test explicitly.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler