Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Continuing With Basic Patterns

00:00 You saw before that as is, your REPL can handle statements but doesn’t know what to do with expressions. So your REPL can read, but it doesn’t evaluate and print.

00:08 Not yet. Thankfully, there’s a tool for that. You can use the built-in eval() function as a complement to exec(). If you pass ast.parse() an argument called mode, it can distinguish between valid Python statements, which you’ll want to execute, and Python expressions, which you’ll want to evaluate.

00:26 Rewrite your valid() function as follows: Add a second argument mode and in the call of ast.parse(), pass mode as the keyword argument mode.

00:38 Now, when the valid() function is called, you will either supply the word eval or exec to mode, and that will change the mode of ast.parse().

00:47 This is how you’ll decide whether you’re looking at a statement or an expression. Lastly, you have to make some changes to your case clauses.

00:55 Add the following clause after the command exit or command.click clause. And because the clause will handle expressions and expressions in Python are also considered statements, it needs to come before the clause handling statements.

01:08 Case clauses should always be defined in decreasing order of specificity. case expression if valid(expression, "eval") In this case, eval is the mode.

01:21 _ = eval(expression)

01:26 If _ is not None, print(_).

01:32 What this is going to do is capture the user input, check whether it’s a valid expression, and if so, eval() will return its value. If the value is anything other than None, print it.

01:43 Storing the value in _, and here it is _, not wildcard, is a convention in the REPL that allows you to access the value of the most recently evaluated expression.

01:54 Now you just need to add the mode exec to the guard with the statement capture pattern,

01:59 and you’re ready to save your file and run the REPL again to see how it goes.

02:09 Let’s try 5 + 5 again. Alright, expression evaluated. Okay, you’ve got a good handle on the basics of structural pattern matching now. Meet me in the next lesson to see some of the advanced patterns you can create.

Become a Member to join the conversation.