Python 按用户对输入列表使用循环
我想让这段代码更加优雅,使用loop将用户输入获取到列表中,并使列表成为一个浮点列表,而不必在使用或打印列表时将列表上的每个参数定义为一个浮点。。。 我对Python3.x或一般的python都很陌生,这是迄今为止我编写的第一个代码“请原谅我!”Python 按用户对输入列表使用循环,python,python-3.x,loops,calculator,Python,Python 3.x,Loops,Calculator,我想让这段代码更加优雅,使用loop将用户输入获取到列表中,并使列表成为一个浮点列表,而不必在使用或打印列表时将列表上的每个参数定义为一个浮点。。。 我对Python3.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 t
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]))
你在找这样的东西吗:
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
输出:
1 2
0.5
通过使用一个函数在一个列表中为您进行输入,该列表包含两个数字:
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
"
链接:
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:")
好的,您应该按顺序查看以下内容:
- for循环
- 列表理解
- 命名元组
- 功能
- 零分误差