Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
os - clear screen function
Hello, I didnt get the clear screen function ? help please
Louise St. Germain19,424 Points
To do a very basic summary of what's happening with the clear screen function:
- Kenneth is importing a package called os, which helps Python interface with the operating system (can pass it commands, etc.)
- One thing you can do with os is to get it to clear the console window so that you have a fresh screen. However, the command you use for this depends on the operating system. "cls" works on Windows, and "clear" works on Linux and MacOS. There isn't a universal command that works for all of them.
- Through the os package (with os.name), Python knows which operating system is running.
- Use this to figure out which command to use to clear the screen. If it's Windows (note that os.name will be "nt" for any version of Windows, not specifically Windows NT), tell it to run "cls"; otherwise, tell it to run "clear".
Kenneth coded it as follows in the video:
import os def clear_screen(): os.system("cls" if os.name == "nt" else "clear")
He's using a one-line conditional expression, which is a format that hasn't been introduced yet at this point in the course, so he did jump the gun a little bit on this code. But the code above does the same thing as this:
import os def clear_screen(): if os.name == "nt": os.system("cls") else: os.system("clear")
I hope this helps a bit. But as Steven said, if you have a specific question, please clarify in a comment, and one of us can try to answer!
would kindly elaborate on the one-line conditional expression syntax?
MICHAEL PIE479 Points
I wanted to add that it does not work in PyCharm at all. It did however work in repl.it. So I guess for the OS function to work, it has to actually be in a real command line environment.
Thank you for the detailed answer .