Lecture 7_2: Lists and mutability, dictionaries, pseudocode, introduction to efficiency

本文介绍了一个使用Python实现的简单程序,该程序通过输入验证确保用户输入的是浮点数,并计算直角三角形的斜边长度。程序演示了如何使用math库中的sqrt函数来计算斜边长。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# example code, Lecture 7, Fall 2008

import math

#get base
inputOK = False
while not inputOK:
    base = float(input('Enter base:'))
    #we get str in python 3x from input, we need to convert str to float.
    if type(base) == type(1.0): inputOK = True
    else: print('Enter, Base must be a floating point number.')

#get height
inputOK = False
while not inputOK:
    height = float(input('Enter height:'))
    if type(height) == type(1.0): inputOK = True
    else: print('Error, Height must be a floating point number.')

hyp = math.sqrt(base*base + height*height)

print ('Base:' + str(base) + '.height:' + str(height) + '.hyp:' + str(hyp))

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('Enter base:', 'Error: base must be a float')
height = getFloat('Enter height:', 'Error: height must be a float')

hyp = math.sqrt(base*base + height*height)
print ('Base:' + str(base) + '.height:' + str(height) + '.hyp:' + str(hyp))

# get base
inputOK = False
while not inputOK:
    try:
        # user can pass 'inf', 'nan', no error will be raised
        # should we check this cases?
        base = float(input('Enter base:'))
    except ValueError:
        print('Base must be an integer or floating point number.')
    else:
        inputOK = True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值