[英]String Slicing with If?
这个学期在Python上开设了一个课程,目前的作业遇到了麻烦。 直到现在为止,通过课堂上完成的示例和练习,仍然找不到任何东西。
Q1)固定
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == 1):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now",aN[0:4],
elif (bN[-1] == 0):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now",bN[0:3]
我希望它能够打印出两个语句,每个结果一个。 如果输入的二进制数字以“ 1”结尾,它将以2个小数点吐出aN;如果输入的二进制数字以“ 0”结尾,则将以1个小数点吐出aN。
它运行时,在显示用户为bN输入的值后,它什么也不做
Q2)是否有更好的方法来查找小数点后的数字? 切片仅在数字<10时有效。
编辑)对那个指出字符串的人,我完全忘记了:(
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (float(bN[-1]) == 1):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now",aN[0:4],
elif (float(bN[-1]) == 0):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now",aN[0:3]
如果有人可以回答第二个问题,那就太好了。
raw_input()
将输入作为字符串。 在您的if
条件中,您正在编译一个带有整数的字符串。 让你if
这样,
if float(bN[-1]) == 1:
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now %.2f" % float(aN)
elif float(bN[-1]) == 0:
print "The binary number was even so your number will contain 1 decimal"
print "The number is now", bN[0:3]
如果要在小数点后打印两位数,则可以采用这种方法。
首先, raw_input()
将输入作为str
。
因此,将aN[-1]
与int
任何比较都会导致False
。 即您的代码将始终运行else
块。
此外,您需要首先找到小数点的索引,然后计算是显示一个还是两个位置(或者处理没有小数点的情况)
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == '1'):
print "The binary number was odd so your number will contain 2 decimals"
if aN.find('.') == -1:
print "The number is now ",aN
else:
print "The number is now ", aN[:aN.find('.')+3]
elif (bN[-1] == '0'):
print "The binary number was even so your number will contain 1 decimal"
if aN.find('.') == -1:
print "The number is now ",aN
else:
print "The number is now ", aN[:aN.find('.')+2]
假设aN总是至少有1个小数,这应该是可行的。 您可以使用find()
找到“”。 小数点。
aN = raw_input("Enter a number with decimals")
bN = raw_input("Enter a binary number, 2 to 4 digits in length")
if (bN[-1] == "1"):
print "The binary number was odd so your number will contain 2 decimals"
print "The number is now", aN[:aN.find(".")+3]
elif (bN[-1] == "0"):
print "The binary number was even so your number will contain 1 decimal"
print "The number is now", aN[:aN.find(".")+2]
例:
>>> aN
'1.12345'
>>> bN
'11'
>>> if (bN[-1] == "1"):
... print "The binary number was odd so your number will contain 2 decimals"
... print "The number is now", aN[:aN.find(".")+3]
... elif (bN[-1] == "0"):
... print "The binary number was even so your number will contain 1 decimal"
... print "The number is now", aN[:aN.find(".")+2]
...
The binary number was odd so your number will contain 2 decimals
The number is now 1.12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.