2015-11-01 44 views
0

我希望用户输入一个数 给了一些:他种“”,但是...... 给了一些:他种“我要输入10” 我希望程序只对整数进行“计数”。因为如果他键入一个字符串程序将停止Python3x整数和字符串输入

import random 
goal = random.randrange(1,10) 
n = 1 
tries = 0 
name = input("Dose to onoma sou ") 

print("A game in Python") 
while n != 0 : 
    value = int(input("madepse poio einai to noumero:")) 
    n = abs(value - goal) 
    print(value,n) 
    tries = tries + 1 
    if n >= 4 : 
    print("den eisai koda") 
    elif n > 0 and n <= 3 : 
    print("eisai koda") 
    else : 
    print("to vrikes") 
    print ("to score sou einai: ",tries) 

skoros = str(tries) 
score = open('score.txt', 'a') 
score.write(name) 
score.write(' ') 
score.write(skoros) 
score.write("\n") 
score.close 
+0

仅供参考,'score.close'应该是'score.close()'。 –

+0

噢,但我只是试过,没有(),它的工作有什么区别?事实是我忘了(),但我没有错误“:S –

+0

它没有错误,因为它只是一个值,就像有'1'而不是'x = 1'这样的行,你不会得到一个错误,但它并没有真正做任何事情 –

回答

1

这将采取任何输入并从中拉出第一个数字。 \d匹配任何数字0-9,而+表示“一个或多个”。

import re 

while True: 
    user = input('Enter a number: ') 
    match = re.search(r'\d+',user) 
    if match: 
     value = int(match.group(0)) 
     break 
    else: 
     print("I didn't see a number in that response.") 

print(value) 
+0

所以没有办法只是接受用户的答案?我想保留整数从他的答案。“我的答案是10”我想程序保持10而不是我想从他的答案中提取整数 –

+0

啊,我不明白你想要什么。更新... –

+0

我得到的错误模块重新没有属性搜索(其for phython3x) –

0

那么,你可以手动循环字符串并使用isdigit()存储数字的位置。

以下办法预计数为字符串中(允许多位数)的只有一个:

start = None 
stop = None 
for i in range(len(input)): 
    c = input[i] 
    if c.isdigit(): 
     if start == None: 
      start = i 
     stop = i 
try: 
    number = int(input[start:stop]) 
catch: 
    print("invalid input") 

编辑: 我想会有一些不错的易正则表达式的解决方案,但我会因为我对它没有太多的经验......

+0

怎么样的重新模块?我只是不知道如何重新模块的syndax –

+0

@D Ace对于重新,请参阅标记答案,我会建议使用。 – xXliolauXx

+0

以及它看起来很好,我得到他的答案的逻辑,但我得到一个错误,也许我仍然做错了什么 –