Input usage examples in python

Input usage examples in python

 

Let's first understand the role of input() in python

Enter the command in the python shell

help(input)

See the picture below:

The help is a bit magical (not very popular). Simply put: input built-in function, one of the parameters is a prompt, this function is used to get a string from the standard input, that is, No matter what the input is-an integer, decimal, or other value-it will be treated as a string.

E.g:

 

If you want to get an integer 234, you need to use forced type conversion:

 

If you want to use input() to receive multiple values, you can combine it with the split() method to work around:

a,b,c = (input("Please enter the length of the three sides of the triangle (separated by spaces):").split())

[For the introduction of Python's split() method, please refer to https://www.w3school.com.cn/python/ref_string_split.asp ]

 

The following gives an application example, the code for finding the area of ​​a triangle

#下句输入三角形的三边长
a,b,c = (input("请输入三角形三边的长(用空格分隔):").split())
a= float(a)
b= float(b)
c= float(c)

#计算三角形的半周长p
p=(a+b+c)/2

#计算三角形的面积s
s=(p*(p-a)*(p-b)*(p-c))**0.5

#输出三角形的面积
print("三角形面积为:",format(s,'.2f'))

Run it, see the figure below:

 

Use input() to input the value, and if the detection contains a non-value, it will prompt to re-enter until it meets the requirements.

Method One

while True:
     try:
         str_num = input('input a number:')
         num=float(str_num)
         print(num)
         break   #若输入的正确,则退出,错误执行except下面代码
     except:
         print('您输入的内容不规范,请重新输入:')

Method II

while True:
    str_num = input('input a number:')

    flag=True #假设输入数据没问题
    dotCount=0

    # str_num_copy=str_num[1:]#这样去掉第一个元素,这个元素可以用'-'替代,就可以输出负数,
    #但是对于负数来说,'-'只能有一个,所以还是有确定
    if str_num[0]=='-': #if str_num.startswith('-'):
        str_num_copy=str_num[1:]
    else:
        str_num_copy=str_num
    for ch in str_num_copy:
        if ch>='0' and ch<='9':
            continue
        elif ch=='.':#确保一个小数点
            dotCount+=1

            if dotCount>1:
                flag=False
                print('您输入的内容不规范,请重新输入:')
                break
            continue

        else:
            flag=False
            print('您输入的内容不规范,请重新输入:')
            break  #若没有这个break,且输入的东西有很多次不符合前两个if判断,则会输出很多次print('您输入的内容不规范,请重新输入:')
    if flag==True:
        print(float(str_num))
        break

 

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/115027082