Conditions, loops, and other statements
Re-talk about print and import
Print multiple parameters
Print can be used to print an expression that is either a string or will automatically convert the string.
Multiple expressions can be printed at the same time, provided they are separated by commas:
>>> print('Age:',42) Age: 42
As above, a space character is inserted between the parameters.
This behavior is helpful when you need to merge text and variable values without using string formatting.
>>> name = 'Gumby' >>> salutation = 'Mr.' >>> greeting = 'Hello,' >>> print(greeting, salutation, name) Hello, Mr. Gumby
If the string variable greeting does not contain commas, add the following to the result:
>>> print(greeting,',' , salutation, name) Hello, , Mr. Gumby
The above execution adds a space before the comma. The following scenarios can be solved:
>>> print(greeting +',' , salutation, name) Hello,, Mr. Gumby
It adds a comma to a variable greeting.
Customizable separators:
>>> print("I","wish","to","register","a","complaint",sep="_") I_wish_to_register_a_complaint
You can also customize the end string to replace the default line break.
Rename on import
When importing from a module, you typically use
import somemodule
Or use
from somemodule import somefunction
or
from somemodule import somefunction, anotherfunction, yetanotherfunction
or
from somemodule import *
Use the last method only when you are sure you want to import everything in the module.
If there are two modules, both contain the function open;
You can import these two modules in the first way by calling functions as follows:
module1.open(...) module2.open(...)
Another option is to add an as clause at the end of the statement and specify an alias.
Here is an example of importing an entire module and aliasing it:
>>> import math as foobar >>> foobar.sqrt(4) 2.0
The following is an example of a person-specific function with an alias:
>>> from math import sqrt as foobar >>> foobar(4) 2.0
For the previous functions open, you can import them as follows:
from module1 import open as open1 from module2 import open as open2
Assignment Magic
Sequence unpacking
Multiple variables can be assigned simultaneously (in parallel):
>>> x,y,z = 1,2,3 >>> print(x,y,z) 1 2 3
You can also swap values of multiple variables in this way.
>>> x,y = y,x >>> print(x,y,z) 2 1 3
The operation performed here is called sequence unpacking (or object unpacking). A sequence (or any object that can be iterated) is unpacked and the resulting values are stored in a series of variables.
The following examples illustrate:
>>> values = 1,2,3 >>> values (1, 2, 3) >>> x,y,z = values >>> x 1
This is useful when using functions or methods that return tuples (or other sequences or iterative objects).
To easily get (or delete) a key-value pair from a dictionary, use the method popitem, which randomly gets a key-value pair and returns it as a tuple.
Next, you can unpack the returned tuples directly into two variables.
>>> scoundrel = {'name':'Robin','girlfriend':'Marion'} >>> key, value = scoundrel.popitem() >>> key 'girlfriend' >>> value 'Marion'
This allows the function to return multiple values packaged into tuples, which can then be easily accessed through an assignment statement.
The sequence to unpack must contain the same number of elements as the target number listed to the left of the equal sign, or Python will throw an exception.
>>> x,y,z = 1,2 Traceback (most recent call last): File "<pyshell#555>", line 1, in <module> x,y,z = 1,2 ValueError: not enough values to unpack (expected 3, got 2) >>> x,y,z = 1,2,3,4 Traceback (most recent call last): File "<pyshell#556>", line 1, in <module> x,y,z = 1,2,3,4 ValueError: too many values to unpack (expected 3)
You can use the asterisk operator (*) to collect redundant values without having to ensure the same number of values and variables as follows:
>>> a,b, *rest = [1,2,3,4] >>> rest [3, 4]
You can also place variables with asterisks in other places.
>>> name = "Albus Percival Wulfric Brian Dunbledore" >>> first, *middle, last = name.split() >>> middle ['Percival', 'Wulfric', 'Brian']
The right side of an assignment statement can be any type of sequence, but an asterisked variable always ends up with a list.
This is also true when the number of variables and values is the same.
>>> a, *b, c = "abc" >>> a,b,c ('a', ['b'], 'c')
Chained assignment
Chain assignment is a shortcut for associating multiple variables to the same value.
Similar to parallel assignment, but involving only one value:
x = y = somefunction()
Equivalent to
y = somefunction() x = y
Not Equivalent to
x = somefunction() y = somefunction()
Enhancement assignment
Instead of writing code x = x + 1, you can write x += 1 by moving the operator (in this case, +) in the right expression before the assignment operator (=).
This is called enhanced assignment and applies to all standard operators, such as *, /,%and so on.
>>> x = 2 >>> x += 1 >>> x *= 2 >>> x 6
Enhanced assignments can also be used with other data types (as long as the binary operators used can be used with these data types).
>>> fnord = 'foo' >>> fnord += 'bar' >>> fnord *= 2 >>> fnord 'foobarfoobar'
By using enhanced assignments, you can make your code more compact, concise, and, in many cases, more readable.
Code Block: The fun of indentation
A code block is a set of statements that can be executed when conditions are met (if statements), multiple times (loops), and so on.
Code blocks are created by indenting the code (that is, by adding spaces before it).
Be careful: You can also indent code blocks using tabs. Python Interpret tabs as moving to the next tab position (8 spaces apart from adjacent tabs). However, the standard (and better) practice is to indent with only spaces (not tabs) and four spaces at each level.
Within the same code block, each line of code must have the same indentation.
The following demonstrates how to indent:
this is a line this is another line: this is another block continuing the same block the last line of this block phew, there we escaped the inner block
In many languages, a special word or character, such as begin or {, is used to identify the starting position of the code block, and another special word or character, such as end or}, is used to identify the ending position.
Python China, using a colon (:) to indicate that the next block of code is followed, and each line of code in that block is randomly identical.
When you find that the indentation is the same as before, you know that the current block of code is over.
Conditions and Conditional Statements
So far, in programs written, statements have been executed one by one.
Further, let the program choose whether to execute a specific block of statements.
That's where Boolean values come in
True values, also known as Boolean values, are named after George Boole, who has made a significant contribution to the truth.
When used as a Boolean expression, such as a condition in an if statement, the following values are treated as false by the interpreter:
False None 0 "" () [] {}
Standard values False and None, values 0 of various types (including floating point numbers, complex numbers, and so on), empty sequences (such as empty strings, empty tuples, and empty lists), and empty maps (such as empty dictionaries) are all considered false, while all other values are considered true, including the special value True.
>>> True True >>> False False >>> True == 1 True >>> False == 0 True >>> True + False + 42 43
So if you see an expression that returns 1 or 0, you know that it actually means True or False.
Boolean values True and False are of type bool, and bool, like list, str, and tuple, can be used to convert other values.
>>> bool('I think, therefore I am') True >>> bool(42) True >>> bool('') False >>> bool(0) False
Any value can be used as a Boolean value, so no explicit conversion is required.
Conditionally execute and if statements
Run the following script:
name = input('What is your name?') if name.endswith('Gumby'): print('Hello, Mr.Gumby')
This is an if statement that conditionally executes code.
This means that if the condition (the expression between if and colon) is true as previously defined, a subsequent block of code (here is a print statement) is executed; If the condition is false, it will not be executed.
else clause
You can use an else clause to add a choice (clause is called because else is not a stand-alone statement, but part of an if statement).
name = input('What is your name?') if name.endswith('Gumby'): print('Hello, Mr.Gumby') else: print('Hello, stranger')
Here, if the first code block is not executed (because the condition is false), the second code block will be entered.
There is a "relative" similar to the if statement, which is the Python version of the trinomial operator in C.
The following expression uses if and else to confirm its value:
status = "friend" if name.endswith("Gumby") else "stranger"
If the condition (immediately after if) is true, the result of the expression is the first value provided (friend here), otherwise the second value (stranger here).
elif clause
To check multiple conditions, use elif.
elif is the abbreviation of else if and is a combination of an if clause and an else clause, that is, an else clause containing conditions.
num = int(input('Enter a number:')) if num > 0: print('The number is positive') elif num < 0: else: print('The number is zero')
Code Block Nesting
You can put an IF statement in another if statement block, as follows:
name = input('What is your name?') if name.endswith('Gumby') if name.startswith('Mr.') print('Hello,Mrs.Gumby') else: print('Hello, Gumby') else: print('Hello, stranger')
Here, if the name ends with Gumby, the name is also checked to start with, which is done using a separate if statement in the first block of code.
Elf is also used. The last grouping (the else clause) has no criteria specified - if no other branch is selected, the last branch is selected.
Both else clauses can be omitted if needed. If the else clause inside is omitted, names that do not begin with Mr. or Mrs. are ignored (assuming the name is Gumby).
If you omit the outer else clause, strangers will be ignored.
More complex conditions
1. Comparison Operators
In conditional expressions, the most basic operators may be comparison operators, which are used to perform comparisons.
Python also supports chained comparisons: multiple comparison operators can be used at the same time, such as 0 < age < 100.
- Equality Operator
To determine whether two objects are equal, use the comparison operator, which is represented by two equal signs (==).
>>> "foo"== "foo" True >>> "foo"=="bar" False
When an equal sign is given:
>>> "foo"="foo" SyntaxError: can't assign to literal
An equal sign is an assignment operator that modifies a value.
- is:: Same Operator
It's interesting to see that this operator acts as if it were==, but which one doesn't.
>>> x = y = [1,2,3] >>> z = [1,2,3] >>> x == y True >>> x == z True >>> x is y True >>> x is z False
is checks if two objects are identical (not equal).
Variables x and y point to the same list, while z points to another list (which contains values and the order in which they are listed is the same as the previous list).
The two lists are equal, but they are not the same object.
Example:
>>> x = [1,2,3] >>> y = [2,4] >>> x is not y True >>> del x[2] >>> y[1]=1 >>> y.reverse()
In this example, two different lists, x and y, are created first.
The two lists have been slightly modified, and although they are equal, they are still two different lists.
>>> x == y True >>> x is y False
Obviously, the two lists are equal but different.
==is used to check whether two objects are equal, while is is used to check whether two objects are the same (the same object).
- in: Membership operator
The operator in, like other comparison operators, can also be used in conditional expressions.
name = input('What is your name?') if 's' in name: print('Your name contains the letter "s".') else: print('Your name does not contain the letter "s".')
- Comparison of strings and sequences
Strings are compared according to the alphabetical order of the characters.
>>> "alpha" < "beta" True
Although based on alphabetical order, letters are Unicode characters, which are arranged by code points.
Characters are arranged in order. To know the order value of the letters, use the function ord. Function does the opposite of function chr
>>> ord ("→") 8594 >>> ord ("←") 8592 >>> chr(8593) '↑'
This method may be the opposite of sorting.
When capital letters are involved, the order may be different from what you want.
>>> "a" < "B" False
One trick is to ignore case.
You can use the string method lower as follows:
>>> "a".lower() < "B".lower() True >>> 'FnOrD'.lower() == 'Fnord'.lower() True
Other sequences are compared in the same way, but they may contain elements that are not characters but other types of values.
>>> [1,2] < [2,1] True
If the elements of a sequence are other sequences, they are compared according to common rules.
>>> [2,[1,4]] < [2,[1,5]] True
2. Boolean Operators
Many expressions that return true values may require checking multiple conditions.
For example, suppose you want to write a program that lets him read a number and check if it is between 1 and 10. The following can be done:
number = int(input('Enter a number between 1 and 10: ')) if number <= 10: if number >=1: print('Great!') else: print('Wrong!') else: print('Wrong!')
These are entered twice in print('Wrong!').
Duplicate work is not a good thing.
Solve as follows:
number = int(input('Enter a number between 1 and 10: ')) if number <= 10 and number >=1: print('Great!') else: print('Wrong!')
The operator and is a Boolean operator.
It accepts two true values and returns true if both values are true, otherwise it returns false.
There are also Boolean operators: or and not.
By using these three operators, the true values can be combined in any way.
if ((cash > price) or customer_has_good_credit) and not_of_stock: give_goods()
One interesting feature of Boolean operators is that they do only the necessary calculations.
Short circuit logic (or delay evaluation): Boolean operators are often referred to as logical operators and in some cases decrease the second value of Bypass.
Assertion
The if statement has a useful "relative" that works like this:
if not condition: crash program
Let the program crash immediately when the error condition occurs rather than later.
Certain conditions can be required to be met, for which the keyword assert can be used in statements.
>>> age = 10 >>> assert 0 < age < 100 >>> age = -1 >>> assert 0 <age < 100 Traceback (most recent call last): File "<pyshell#614>", line 1, in <module> assert 0 <age < 100 AssertionError
When certain conditions must be met before the program can correctly begin, assert statements can be added to the program to act as checkpoints.
You can also add a string after the condition to explain the assertion.
>>> age = -1 >>> assert 0 < age <100, 'The age must be realistic' Traceback (most recent call last): File "<pyshell#616>", line 1, in <module> assert 0 < age <100, 'The age must be realistic' AssertionError: The age must be realistic
loop
Example, pseudocode like this
send mail with one month send mail with one month send mail with one month (... and so on)
If you want the program to continue executing like this until it stops artificially, you can write code like this (pseudocode):
while we aren't stopped: send mail wait one month
Suppose you want to print all numbers from 1 to 100. A clumsy approach can be taken:
print(1) print(2) print(3) ... print(99) print(100)
while loop
To avoid tedious code, do the following:
x = 1 while x<=100: print(x) x += 1
You can also use loops to ensure that users enter names as follows:
name = '' while not name: name = input('Please enter your name: ') print('Hello, {}!'.format(name))
The while statement is flexible and can be used to execute code blocks repeatedly when the condition is true.
for loop
Point to the code block for each element in a sequence (or other iterative object).
Iterable objects are available for Loop through the object.
To do this, use the for statement:
words = ['this','is','an','ex','parrot'] for word in words: print(word)
or
numbers = [0,1,2,3,4,5,6,7,8,9] for number in numbers: print(number)
Python provides a built-in function to create scopes, since the number of iterations (that is, traversing) within a specific range is a common task.
>>> range(0,10) range(0, 10) >>> list(range(0,10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The extent is similar to a slice.
They contain the starting position (0 here), but not the ending position (10 here).
If the value provides a location, it is considered the end location, and the starting position is assumed to be 0.
>>> range(10) range(0, 10)
Print numbers 1~100 below:
for number in range(1,101): print(number)
Tip: Only available for Loop, do not use while Cycle.
Iteration Dictionary
To iterate through all the keywords in a dictionary, use a common for statement.
d = {'x':1, 'y':2, 'z':3} for key in d: print(key, 'corresponds to', d[key])
You can also use dictionary methods such as keys to get all keys.
d.values can be used if you are only interested in values.
d.items returns key-value pairs in tuples.
One of the advantages of the for loop is that you can use sequence unpacking in it.
for key, value in d.items(): print(key, 'corresponds to', value)
Note that the order of dictionary elements is uncertain.
Some Iteration Tools
1. Parallel Iteration
Iterate two sequences at the same time.
Assume the following two lists:
name = ['anne','beth','george','damon'] ages = [12, 45, 32, 102]
Print the name and the corresponding age as follows:
for i in range(len(names)): print(name[i],'is',ages[i],'years old')
i is the standard name of the variable used as a circular index.
The parallel iteration tool is a built-in function zip that "stitches" two sequences and returns a sequence of tuples.
The return value is an object suitable for iteration and can be converted to a list using a list to see its contents.
>>> list(zip(names,ages)) [('Alice', 12), ('Beth', 45), ('Cecil', 32), ('Dee-Dee', 102)]
After stitching, tuples can be unpacked in a loop.
for name,age in zip(names,ages): print(name,'is',age,'years old')
The function zip can be used to "stitch" any number of sequences.
When the sequence lengths are different, the function zip will stop "stitching" when the shortest sequence is used up.
>>> list(zip(range(5), range(100000000))) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
2. Obtaining indexes while iterating
Gets the index of the current object while iterating over the sequence of objects.
For example, replace all strings that contain the substring'xxx'in a list of strings.
The following can be done:
for string in strings: if 'xxx' in string: index = strings.index(string) # Find a string in the list of strings strings[index] = '[censored]' index += 1
Searching before replacing is unnecessary.
If not replaced, the index returned by the search may be incorrect (that is, the index at the first occurrence of the string is returned).
Another better solution:
index = 0 for string in strings: if 'xxx' in string: strings[index] = '[censored]' index +=1
Another solution is to use the built-in function enumerate.
for index, string in enumerate(srings): if 'xxx' in string: strings[index] = '[censored]'
This function allows you to iterate over index-value pairs, where the index is provided automatically.
3. Inverse iteration and sorting followed by iteration
Functions: reversed and sorted.
Similar to the list methods reverse and sort (sorted accepts parameters similar to sort), but can be used for any sequence or iterative object, and instead of modifying the object in place, it returns the inverted and sorted version.
>>> sorted([4,3,6,8,3]) [3, 3, 4, 6, 8] >>> sorted('Hello,world!') ['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] >>> list(reversed('Hello,world!')) ['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H'] >>> ''.join(reversed('Hello,world!')) '!dlrow,olleH'
Notice that sorted returns a list, and reversed returns an Iterable object like zip.
It cannot be indexed or sliced, nor can it be invoked directly to the methods of the list.
To perform these operations, you can first convert the returned object using a list.
Break
Loops continue to execute code blocks until the condition is false or all elements in the sequence are used up.
You want to break the loop, start a new iteration, or end the loop directly.
1. break
To end (jump out) the loop, use break.
For example, to find the maximum square value less than 100, you can iterate down from 100. Once you find a square value, you don't need to iterate anymore, so you jump out of the loop.
from math import sqrt for n in range(99, 0, -1): root = sqrt(n) if root == int(root): print(n) break
The third parameter in the range is the step, which is the difference between the number of neighbors in the sequence.
By setting the step size to a negative number, you can let the range iterate down.
2. continue
Statement continue is much more useful than break.
It ends the current iteration and moves to the beginning of the next iteration.
This means that the remaining statements in the loop body are skipped, but the loop does not end.
This is useful when the loop is large and assigned, and there are several reasons to skip it.
In this case, continue can be used as follows:
for x in seq: if condition1: continue if condition2: continue if condition3: continue do_something() do_something_else() do_another_thing() etc()
In many cases, an if statement is sufficient.
for x in seq: if not (condition1 or condition2 or condition3) do_something() do_something_else() do_another_thing() etc()
You must be familiar with the break statement because it is often used in while True loops.
3. while True/break examples
For example:
Suppose you want to perform an action when the user enters a word as prompted and end the loop when the user does not provide a word.
One way is as follows:
word = 'dummy' while word: word = input('Please enter a word: ') # Do something with this word: print('The word was', word)
The code works as follows:
Please enter a word: first The word was first Please enter a word: second The word was second Please enter a word:
To enter the loop, you need to assign a dummy value (an unused value) to word.
This dummy value usually means you're not doing the right thing.
Try to eliminate this dummy value:
word = input('Please enter a word: ') while word: # Do something with this word: print('The word was', word) word = input('Please enter a word: ')
Dummy values are eliminated but contain duplicate code.
To avoid duplication, use the example while True / break.
while True: word = input('Please enter a word: ') if not word: break # Do something with this word: print('The word was ', word)
while True causes the loop to never end, but places the couple in an if statement inside the loop that calls break when the condition is met.
The if / break line divides the entire loop into two parts:
The first part is responsible for setting up (which is repeated if you use a regular while loop), and the second part uses the data initialized in the first part when the loop condition is true.
else clause in loop
You can define a Boolean variable before the loop starts and set it to False, then set it to True when you jump out of the loop.
This allows you to use an IF statement after the loop to determine if it ended prematurely.
break_out = False for x in seq: do_something(x) if condition(x): broke_out = True break do_something_else(x) if not broke_out: print("I didn't break out!")
An easy way to do this is to add an else clause to the loop, which executes only when break is not called.
Example:
from math import sqrt for n in range(99, 81, -1): root = sqrt(n) if root == int(root): print(n) break else: print("Didn't find it!")
Simple Derivation
List derivation is a way of creating lists from other lists, similar to set derivation in mathematics.
List derivation works very simply, somewhat like a for loop.
>>> [x*x for x in range(10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Add an if statement to the list derivation.
>>> [x*x for x in range(10) if x % 3 == 0] [0, 9, 36, 81]
You can add more for sections.
>>> [(x,y) for x in range(3) for y in range(3)] [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
For comparison, the following two for loops create the same list:
result = [] for x in range(3): for y in range(3) result.append((x, y))
An if clause can also be added when using multiple for parts.
>>> girls = ['alice','bernice','clarice'] >>> boys = ['chris','arnold','bob'] >>> [b+'+'+g for b in boys for g in girls if b[0] == g[0]] ['chris+clarice', 'arnold+alice', 'bob+bernice']
Using parentheses instead of square brackets does not implement tuple derivation, but instead creates a generator.
You can use curly brackets to perform dictionary derivation.
>>> squares = {i:"{} squared is {}".format(i, i**2) for i in range(10)} >>> squares[8] '8 squared is 64'
In list derivation, for is preceded by only one expression, whereas in dictionary derivation, for is preceded by two colon-separated expressions.
These expressions are keys and their corresponding values, respectively.
Three-person pedestrian
Statements: pass, del, and exec.
Don't do anything?
Sometimes you don't need to do anything.
You can use pass statements.
>>> pass >>>
Nothing happened here.
A statement that does nothing can be used as a placeholder.
The following:
if name == 'Ralph Auldus Melish' print('Welcome!') elif name == 'Enid': # Not yet done... elif name == 'Bill Gates': print('Access Denied')
These codes cannot run because the code block in Python cannot be empty.
To fix this problem, you need to add a pass statement to the middle block of code.
if name == 'Ralph Auldus Melish' print('Welcome!') elif name == 'Enid': # Not yet done... pass elif name == 'Bill Gates': print('Access Denied')
Delete using del
For objects that are no longer used, Python typically deletes them (because there are no variables or data structure members pointing to them).
>>> scoundrel = {'age':42, 'first name':'Robin','last name':'of Locksley'} >>> robin = scoundrel >>> scoundrel {'age': 42, 'first name': 'Robin', 'last name': 'of Locksley'} >>> robin {'age': 42, 'first name': 'Robin', 'last name': 'of Locksley'} >>> scoundrel = None >>> robin {'age': 42, 'first name': 'Robin', 'last name': 'of Locksley'} >>> robin = None
Robin and scoundrel point to the same dictionary, so after assigning None to scoundrel, you can still access the dictionary through robin.
With robin also set to None, the dictionary floats in computer memory without any name associated with it, and can no longer be retrieved or used.
Therefore, the Python interpreter deletes it directly. This is called garbage collection.
You can also assign any other value to two variables instead of None, and the dictionary will disappear.
Another way is to use a del statement.
This not only deletes the reference to the object, but also the name itself.
>>> x = 1 >>> del x >>> x Traceback (most recent call last): File "<pyshell#654>", line 1, in <module> x NameError: name 'x' is not defined
Sometimes it's not easy to understand.
For example, in the following example, x and y point to the same list:
>>> x = ["Hello","world"] >>> y = x >>> y[1] = "Python" >>> x ['Hello', 'Python']
You cannot delete y by deleting x.
>>> del x >>> y ['Hello', 'Python']
X and Y point to the same list, but deleting X has no effect on y because only the name x is deleted, not the list itself (value).
Executing strings with exec and eval is the calculator result
Both exec and eval are now functions, but exec used to be a statement and eval is closely related to it.
1. exec
The function exec executes strings as code.
>>> exec("print('Hello, world!')") Hello, world!
When calling the function exec, in most cases, you should also pass a namespace to it - the place where variables are placed; Otherwise, the code will pollute your namespace, modifying your variables.
For example, suppose the code uses the name sqrt:
>>> from math import sqrt >>> exec("sqrt = 1") >>> sqrt(4) Traceback (most recent call last): File "<pyshell#664>", line 1, in <module> sqrt(4) TypeError: 'int' object is not callable
The function exec is primarily used to dynamically create code strings.
For security reasons, provide a dictionary to act as a namespace.
To do this, add a second parameter, the dictionary, which is used as the namespace for the code string.
>>> from math import sqrt >>> scope = {} >>> exec('sqrt = 1', scope) >>> sqrt(4) 2.0 >>> scope['sqrt'] 1
Note that if you try to print a scope, you will find that it contains a lot of content because a dictionary containing all built-in functions and values is automatically added to it_ builtins_.
>>> len(scope) 2 >>> scope.keys() dict_keys(['__builtins__', 'sqrt'])
2. eval
eval is a built-in function similar to exec.
Exec executes a series of Python statements, and eval evaluates the value of the Python expression represented by a string and returns the result (exec does not return anything because it is a statement itself).
You can create a Python calculator using the following code:
>>> eval(input("Enter an arithmetic expression: ")) Enter an arithmetic expression: 6+18*2 42
Like exec, eval can also be given a namespace.
Talking about Scope
When you provide a namespace to exec or eval, you can add values to it before using it.
>>> scope = {} >>> scope['x'] = 2 >>> scope['y'] = 3 >>> eval('x*y', scope) 6
Similarly, the same namespace can be used to call exec or eval multiple times.
>>> scope = {} >>> exec('x=2', scope) >>> eval('x*x', scope) 4
Summary
New functions introduced in this chapter
Learning References:
<Python Basic Tutorials 3rd Edition