【问题标题】:how to ask for both an integer and an string如何同时要求整数和字符串
【发布时间】:2016-04-10 23:57:41
【问题描述】:
print("welcome to the Pythagoras calculator")
print("please leave empty whenever asked for any sides of the triangle you do not have data for")
print("please answer every question with integers only")

side = input("which side would you like to be found?")

hyp = int(input("hypotenuse length:"))
if hyp == (''):
    hyp = str(hyp)
adj = int(input("adjacent length:"))
if adj ==(''):
    adj = str(adj)
opp = int(input("opposite length:"))
if opp == (''):
    opp = str(opp)

while hyp == ("") and adj == (""):
    print("you need to insert two values")
    hyp = int(input("hypotenuse length:"))
    adj = int(input("adjacent length:"))
    opp = int(input("opposite length:"))

while hyp == ("") and opp == (""):
             print("you need to insert two values")
             hyp = int(input("hypotenuse length:"))
             adj = int(input("adjacent length:"))
             opp = int(input("opposite length:"))

while adj == ("") and opp == (""):
             print("you need to insert two values")
             hyp = int(input("hypotenuse length:"))
             adj = int(input("adjacent length:"))
             opp = int(input("opposite length:"))

while adj == ("") and opp == (""):
             print("you need to insert two values")
             hyp = int(input("hypotenuse length:"))
             adj = int(input("adjacent length:"))
             opp = int(input("opposite length:"))

while hyp == ("") and adj == ("") and opp == (""):
             print("you need to insert two values")
             hyp = int(input("hypotenuse length:"))
             adj = int(input("adjacent length:"))
             opp = int(input("opposite length:"))

我正在尝试创建一个毕达哥拉斯计算器,但是当我要求人们插入边的长度时,它会弹出一个错误,说明基本上我正在尝试使用 int 作为字符串(在验证中),我'我知道我不能将 int 用作字符串我只是不知道如何在同一输入中同时使用字符串和整数(我要求输入,它既是字符串又是整数)。

谢谢

【问题讨论】:

  • if hyp == ('') 永远不会发生,如果字符串为空你会得到一个错误,如果你想验证输入使用 try/except。 stackoverflow.com/questions/23294658/…
  • 编写您自己的输入函数,检查用户输入的字符串的长度,并使用 try/except 子句查看是否可以使用 int() 将其转换为整数 — 然后在任何地方使用它代替int(input("name:"))

标签: python string integer


【解决方案1】:

在 python 2.7 中,您只需使用 raw_input() 喜欢

hyp = raw_input("hypotenuse length:")
adj = raw_input("adjacent length:")
opp = raw_input("opposite length:")

然后您的检查将起作用,因为如果未输入任何内容,它们将是空字符串。

此外,您最好将raw_input 用于所有输入,无论您需要将值作为int 的任何地方,您都可以明确将其隐藏,例如

temp = int(adj) 

raw_input() 返回一个字符串,input() 尝试将输入作为 Python 表达式运行。

在 python 3 中,raw_input 只是重命名为input,因此可以直接用于获取字符串形式的输入。

【讨论】:

  • 我希望通过这些冗余检查不需要将它们转换为字符串。因此,您的程序将立即进入那些 while 循环中的检查。
【解决方案2】:

您可以使用如图所示的try/except 块,并添加其他条件来验证(我检查了validate_input() 中的空白边数,但您可以扩展到正数等)。

#!/usr/bin/python

import math

#Triangle has three sides; two can be defined and the third is calculated
class Triangle:

    def __init__(self):
        self.side={"adjacent":0,"opposite":0,"hypotenuse":0}

    def define_sides(self):
        for i in self.side:
            self.side[i]=self.get_side(i)

    def print_sides(self):
        for i in self.side:
            print "side",i,"equals",self.side[i]

    #return user integer or None if they enter nothing
    def get_side(self,one_side):
        prompt = "Enter length of "+one_side+": "
        try:
            return input(prompt)
        except SyntaxError:
            return None

    def count_nones(self):
        nones=0
        for side, length in self.side.iteritems():
            if self.side[side] == None:
                nones+=1
        return nones

    def validate_input(self):
        nNones=self.count_nones()

        if nNones < 1:
            print "You must leave one side blank."
            quit()
        if nNones > 1:
            print "Only one side can be left blank."

    def calculate_missing_length(self):
        h=self.side["hypotenuse"]
        a=self.side["adjacent"]
        o=self.side["opposite"]

        #hypotenuse is missing
        if h == None:
            self.side["hypotenuse"] = math.sqrt(a*a+o*o)

        #adjacent is missing
        if a == None:
            self.side["adjacent"] = math.sqrt(h*h-o*o)

        #opposite is missing
        if o == None:
            self.side["opposite"] = math.sqrt(h*h-a*a)

#begin program
triangle=Triangle()
triangle.define_sides()
triangle.print_sides()
triangle.validate_input()
triangle.calculate_missing_length()
triangle.print_sides()

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    相关资源
    最近更新 更多