[PYTHON] week4: Control structure / eval function

Mostly similar to other languages, abbreviations, memos and other specific parts:

1. eval function

eval () function large enough, official demo solution: general character skewer str effective expression expression coming request parallel return calculation result. Example

>>> a,b,c = eval(input("please input(a,b,c):"))
please input(a,b,c):1,2,3
>>> print("{},{},{}".format(a,b,c))
1,2,3

Top-level syllabary, etc. ʻa, b, c = 1,2,3`, cause eval general 户 import-like character string skewer completion ceremony. Eval meeting without using the upper surface of the fruit

>>> a,b,c = input("please input(a,b,c):")
please input(a,b,c):1,2,3
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a,b,c = input("please input(a,b,c):")
ValueError: too many values to unpack (expected 3)

Equivalence relations, etc. ʻA, b, c = "1,2,3" `, Equivalence relations.

Re-examination one example child:

>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> print("{}".format(a))
[[1,2], [3,4], [5,6], [7,8], [9,0]]
>>> print("{}".format(b))
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> print("{},{}".format(type(a),type(b)))
<class 'str'>,<class 'list'>

At the time of b = eval (a), Sho a Nakabiki issue internal partial action table, 赋 值 给 b, Na 么 b most important list immediate sequence table, syllabary.


  1. ** On the other hand, it is convenient, but it is safe to use, and it is necessary to import the user's information and talk about it. ** **

1.1 This kind of similar exec () function

eval's ability calculation single-individual expression type 值, exec can dynamic state 执 码 dan, total extra exec mortal return 值 **, Nyoshita

def func():
    y = 20
    a = exec('2*y')
    print('a: ', a)

    a1 = eval('1.5*y')
    print('a1: ', a1)    

    exec("A=1;B=A+2;print(\"{},{}\".format(A,B))")

func()

Export consequences:

a:  None
a1:  30
1,3

Top surface Introduction:

  1. exec function return return, eval return return
  2. exec can multi-stage table expression

2 Exception handling

Others are similar in order, examples below:

import math
def main():
    try:
        number1,number2=eval(input("Enter the two number,separated by a comma  :"))
        result = number1 / number2

    except ZeroDivisionError:
        print("Division by zero!")
    except SyntaxError:
        print("A comma may be missing!")
    except:
        print("Something wrong!")
    else:
        print("No exception,the reslut is ",result)
    finally:
        print("Over!")

main()

Export results:

Enter the two number,separated by a comma  :1 3
A comma may be missing!
Over!

========= RESTART: C:\Users\legendcos\Desktop\python-study\052701.py =========
>>> 
Enter the two number,separated by a comma  :1,0
Division by zero!
Over!

========= RESTART: C:\Users\legendcos\Desktop\python-study\052701.py =========
Enter the two number,separated by a comma  :1,2
No exception,the reslut is  0.5
Over!

3. Alternate circulation

def main():
    sum = 0.0
    count = 0
    xStr = input("Enter a number(<Enter> to quit) >> ")
    while xStr != "":
        x = eval(xStr)
        sum = sum + x
        count = count + 1
        xStr = input("Enter a number(<Enter> to quit) >> ")

    print("\n The average of the numbers is: ",sum / count)

main()

1 Direct acceptance import, direct direct import enter

4. Document circulation

def main():
    fileName = input("what file are the numbers in:\n")
    infile = open(fileName,'r')
    sum = 0
    count = 0
    for line in infile:
        sum = sum + eval(line)
        count = count + 1
    print("\n The average of the numbers is: ",sum / count)
main()

The result of the deed:

what file are the numbers in:
h:\data.txt

 The average of the numbers is:  4.111111111111111
>>> 

Ya Can use readline () function, Nyoshita:

def main():
    fileName = input("what file are the numbers in:\n")
    infile = open(fileName,'r')
    sum = 0
    count = 0
    line = infile.readline()
    while line != "":
        sum = sum + eval(line)
        count = count + 1
        line = infile.readline()
    print("\n The average of the numbers is: ",sum / count)
main()

In the top-level import text, one number with each other, many numbers with each and every one, and "," division, 则 demand fitting circulation, after the reform

def main():
    fileName = input("what file are the numbers in:\n")
    infile = open(fileName,'r')
    sum = 0
    count = 0
    line = infile.readline()
    while line != "":
        for xStr in line.split(","):
            sum = sum + eval(xStr)
            count = count + 1
        line = infile.readline()
    print("\n The average of the numbers is: ",sum / count)
main()

5. Infinite loop

Infinite loop using python

while True:
    try:
        x = int(input("please enter a number:"))
        break
    except ValueError:
        print("oh,that wa no valid number,Try again..")

Introductory import numbers Talent exit break

Recommended Posts

week4: Control structure / eval function
[Python tutorial] Control structure tool