引用字符串中的整数?python
如何使用python引用字符串中的整数?我对编码是完全陌生的,我正在尝试做这个bug收集练习,其中用户将输入一周内每天收集的bug数量,并在一周结束时显示收集的bug总数 这是我目前掌握的代码引用字符串中的整数?python,python,for-loop,Python,For Loop,如何使用python引用字符串中的整数?我对编码是完全陌生的,我正在尝试做这个bug收集练习,其中用户将输入一周内每天收集的bug数量,并在一周结束时显示收集的bug总数 这是我目前掌握的代码 totalBugs = 0.0 day = 1 for day in range(7): bugsToday = input('How many bugs did you get on day', day,'?') totalBugs = totalBugs + bugsToday p
totalBugs = 0.0
day = 1
for day in range(7):
bugsToday = input('How many bugs did you get on day', day,'?')
totalBugs = totalBugs + bugsToday
print 'You\'ve collected ', totalBugs, ' bugs.'
因此,我试图在循环中得到bugsToday提示符,以询问用户
“第一天你收集了多少虫子?”
“第二天你收集了多少虫子?”
等等
我该怎么做呢?你可以试试
...
for day in range(7):
bugsToday = input('How many bugs did you get on day %d ?' % day)
totalBugs = totalBugs + bugsToday
...
我会这样做的方式如下
total_bugs = 0 #assuming you can't get half bugs, so we don't need a float
for day in xrange(1, 8): #you don't need to declare day outside of the loop, it's declarable in the for loop itself, though can't be refernced outside the loop.
bugs_today = int(raw_input("How many bugs did you collect on day %d" % day)) #two things here, stick to raw_input for security reasons, and also read up on string formatting, which is what I think answers your question. that's the whole %d nonsense.
total_bugs += bugs_today #this is shorthand notation for total_bugs = total_bugs + bugs_today.
print total_bugs
要了解字符串格式,请执行以下操作:
我写的关于原始输入与出于安全目的的输入的文章,如果您对此感兴趣:
从Python文档中:
CPython实现细节:如果s和t都是字符串,一些Python实现(如CPython)通常可以对s=s+t或s+=t形式的赋值执行就地优化。如果适用,这种优化使二次运行时的可能性大大降低。此优化取决于版本和实现。对于性能敏感的代码,最好使用str.join()方法,该方法可确保跨版本和实现的一致线性连接性能
一开始编程可能看起来很难,只要坚持下去,你就不会后悔了。祝你好运,我的朋友 我个人非常喜欢
format()
。您可以这样编写代码:
totalBugs = 0
for day in range(1, 8):
bugsToday = raw_input('How many bugs did you get on day {} ?'.format(day))
totalBugs += int(bugsToday)
print 'You\'ve collected {} bugs.'.format(totalBugs)
范围(1,8)
经过day=1
到day=7
,如果这是您想要做的。您想要“从用户输入读取”。签出:可能存在重复的s=“34”
n=int(s)
打印n+1
35
不清楚问题出在哪里。你在做一些字符串+一些整数时有困难吗?您在请求用户输入时遇到问题吗?您是在询问
循环的?不管怎么说,这是一个重复的问题,但我不知道该把它指向哪里,谢谢!!!这正是我想要的!!!我一定记得%d。没问题,很乐意帮忙。我可能错过了一些东西,xrange比range快,所以我习惯使用它。(1,8)1-7而不是0-6,我认为这更好,但取决于你。我对raw_输入使用int(),因为raw_输入返回一个字符串,我们需要一个int类型。还要注意的是%d表示整数,%s表示字符串,%f表示浮点等。您可能会发现.format方法更简单。