技术求助:单变量接收双用户输入并结合or逻辑运算符输出rentalPeriod
Solution for Combining Two User Inputs with Python's
or Operator Got it, let's break this down simply. The goal is to use one variable to hold either the number of weeks rented (if provided) or fall back to the number of days rented—all leveraging Python's or logical operator. Here's how to make it work:
# Capture weeks input first; if empty, use days input as fallback rental_period = input("Number of Weeks Rented:\n") or input("Number of Days Rented:\n") # Output the final selected rental period print("Final Rental Period:", rental_period)
How this logic works:
- In Python, the
oroperator returns the first "truthy" value it encounters. An empty string (from pressing Enter without typing anything) counts as "falsy", so if the user skips the weeks input, the code automatically triggers the days prompt instead. - If the user enters any value for weeks (even a number stored as a string), that value gets saved to
rental_periodimmediately, and the days prompt never runs at all.
Quick practical note:
If you need to perform numerical calculations with this value later (like calculating rental costs), remember to convert it to an integer using int(rental_period)—since the input() function always returns a string by default.
内容的提问来源于stack exchange,提问作者dspano
相关产品推荐
相关产品推荐

