我希望使这个代码更加优雅,使用循环将用户输入放入列表中,并将列表作为浮点列表,而不必在列表中将每个参数定义为浮动时自行使用他们或打印他们...... 我是python 3.x或python的新手,这是我迄今为止写过的第一个代码,所以请原谅我!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
答案 0 :(得分:1)
既然你说你不熟悉Python,我建议你自己尝试一些方法。这将是一个很好的学习经历。我不打算直接在这里给你答案,因为那会破坏目的。我会提供关于从哪里开始的建议。
旁注:你使用Python3很棒。 Python3.6支持f-strings。这意味着您可以使用print
函数替换该行,如下所示。
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
好的,您应该按顺序查看以下内容:
答案 1 :(得分:0)
你在寻找这样的东西:
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
输出:
1 2
0.5
答案 2 :(得分:0)
通过在构造你的2个数字的列表理解中使用为你输入的函数:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
其余部分来自您的代码,更改的是列表comp以处理消息和输入创建:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
输出:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
链接: