Menu
CoddyTech

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 icon

Challenge

Beginner

Read 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__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for R Developers

Practice on your own: Online Python compiler