Check out a free preview of the full Intermediate Python course

The "Command Line" Lesson is part of the full, Intermediate Python course featured in this preview video. Here's what you'd learn in this lesson:

Nina introduces how to take only necessary arguments from the arguments collected using slicing, and how to ask for input from the user.

Preview
Close

Transcript from the "Command Line" Lesson

[00:00:00]
>> Nina Zakharenko: I also wanna talk to you about how to write basic command line tools and scripts in Python. We wanna know how to accept command line arguments. It's pretty useful for a script, right? You want to interact with the user. We saw sys.argv. So that's one way of accepting input from,

[00:00:25]
>> Nina Zakharenko: Input from the user.
>> Nina Zakharenko: A nice trick for sys.argv, we can use slicing to remove the name of the file because we usually don't care about it, right? So I can say arguments equal, and where would I start my slice?
>> Nina Zakharenko: Which is the first value that we care about, at what index?

[00:00:52]
>> Speaker 2: One.
>> Nina Zakharenko: Index one, and go to the very end. We care about the rest of them. Now, if I,
>> Nina Zakharenko: Oops, I'm sorry. It was arguments sys.argv.
>> Nina Zakharenko: So I'll comment that out. Now, if I run this again,
>> Nina Zakharenko: We'll see that, okay, this is actually useful.

[00:01:18]
I didn't get any arguments. And now I can say, 123 hello goodbye, and it'll only print out the arguments that were actually useful to me.
>> Nina Zakharenko: Make a new file here, we're gonna call it,
>> Nina Zakharenko: Input_example.py.
>> Nina Zakharenko: To get and interact with user input, we can use the built-in input function in Python.

[00:01:52]
So I'm gonna say that name equals, call the built-in input function. And the argument here is what you want the prompt to look like. So say, Hello human, what is your name? Generally you wanna put a space here so that there's a little bit of spacing. You can even put a colon or something to kind of signify that you want some input here.

[00:02:20]
And then you can say, print out, hello, (name) nice to meet you!
>> Nina Zakharenko: Running this from the command palette, we'll see that my prompt has changed. It's a block now, it's waiting for input. So I can type my name in here and get my response back. Note that if you just press Enter, you'll get back an empty string.

[00:02:58]
So when you're accepting user input, it's generally a good idea to do some validation on it or some syntax checking.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now