Home  >  Article  >  Backend Development  >  How to find the length of the third side using python

How to find the length of the third side using python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-19 16:52:018155browse

Use Python to implement "Given two right-angled sides of a triangle, find the hypotenuse"

Requirements: The user inputs two right-angled sides (the value is a floating point type). If it is not a floating point type, the user is prompted, Continue typing.

How to find the length of the third side using python

Idea: Pseudo code describes the steps

1. -input a value for the base as a float (input a float Points as the base value)

2、-input a value for the height as a float(Enter a floating point number as the height value)

3、-square root-- b squared plus h squared (find the sum of squares and the root)

4. -save that as a float in hype, for hypotenuse (save the result as hyp, indicating the hypotenuse)

5. -print something out, using the value in hyp. (print out the result)

Related recommendations: "Python Video Tutorial"

Analysis of the above ideas (pseudocode ), it can be concluded:

0. The user’s input results are in various situations, so be careful about the user’s input

1. The abstraction of the code (use math for the calculation of the square root) Module's sqrt built-in function)

2. Process control

Code 1

#! /usr/bin/env python
# encoding:utf-8
import math
# 取底
inputOK = False
while not inputOK:
    base = input('输入底:')
    if type(base) == type(1.0): 
inputOK = True
    else: 
print('错误,底必须为浮点数')    
# 取高
inputOK = False
while not inputOK:
    height = input('输入高:')
    if type(height) == type(1.0): 
inputOK = True
    else: 
print('错误,高必须为浮点数')
 
#斜边
hyp = math.sqrt(base*base + height*height) 
print '底' + str(base) + ',高' + str(height) + ',斜边' + str(hyp)

Analyzing code 1, you will find the code for taking the bottom and taking the high Very similar, this will make people think of abstracting into methods and achieving modularity.

Code 2

#!/usr/bin/env python
#coding:utf-8 
import math 
"""
用户输入两个直角边(数值为浮点类型),若非浮点类型,则提示用户,继续输入。
""" 
def getFloat(requestMsg, errorMsg):
    inputOK = False
    while not inputOK:
        val = input(requestMsg)
        if type(val) == type(1.0): 
inputOK = True
        else: 
print(errorMsg)
    return val 
base = getFloat('输入底:','错误,底必须为浮点数')
height = getFloat('输入高:','错误,高必须为浮点数') 
hyp = math.sqrt(base*base + height*height) 
print '底' + str(base) + ',高' + str(height) + ',斜边' + str(hyp)

The above is the detailed content of How to find the length of the third side using python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn