r/AskAnythingPython • u/kitkatmafia • Sep 08 '23
if else in one line!
just wanted to share something cool I found, - you can write the if-else statement in one line!
so instead of
age =20
if age>=18:
print("You can drive")
else:
print("Sorry, you cant drive")
you can write them in one line - this is called a terinary conditional operator. Means you need three operands (The 2 print statements and the test condition)
print("You can drive") if age>=18 else print("Sorry, you cant drive")
The syntax is as follows
a if condition else b
1
Upvotes
View all comments
Show parent comment
2
u/Tabakalusa Sep 09 '23
Rust is great, but remember that it's a systems-programming language. And while it gives you the tools to avoid a lot of the foot-guns that something like C or C++ are famous for, you still have to do the right thing. Though the compiler is actually pretty helpful at guiding you there. So while you can't have data races on objects you've shared between threads, or can't return a potential dangling reference, you're still going to need to know how and when to use mutexes or how to annotate lifetimes on functions occasionally.
Personally I think it's a great experience, especially if you haven't had the opportunity to work with a language with a very strong, strict and expressive type system before. It's also a great view (albeit a limited one) into the world of functional programming. Those two things combined make for a very eye-opening experience. Sure something like C++ or Java can do those things as well these days, but it's different when it's the default and has first class language support, instead of something that was tacked on after the fact and comes with awkward syntax and gotchas.
Definitely worth checking out, but something like F# or Scala can serve a similar purpose, if you want to avoid dealing with all the low level cruft that comes with a systems programming language.