布尔条件
Coddy 面向 Python 开发者的 Dart 课程的第 7 课,共 48 课。
Python 会对集合和数字进行真值判断,而且 and/or 可以返回操作数。Dart 的条件和逻辑操作数必须是 bool。两者都会进行短路求值,因此被跳过的右侧操作数不会产生副作用。
条件和逻辑操作数必须是 bool。短路运算符的右侧只会在需要时运行,因此可能会完全跳过带有输出的回调。
完整的 Python 程序:
def probe():
print('probe')
return True
print('open' if False and probe() else 'closed')
完整的 Dart 程序:
bool probe(){print('probe');return true;}
void main(){if(false && probe()){print('open');}else{print('closed');}}挑战
简单实现 safe(int temperature, bool doorClosed):当温度在 10 到 80 之间(含边界)且门已关闭时,恰好返回 true。输入是温度和 true 或 false。返回小写的布尔文本。
不要从可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。
你的代码应写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(safe(40,true));check(!safe(40,false));
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 Dart中的所有课
自己练习: Dart 在线编译器