Python3x 整数和字符串输入

2024-09-29 00:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户输入一个数字 给出一个数字:他键入“10”—但是。。。 给出一个数字:他键入“我想键入10” 我希望程序只是“计算”整数。因为如果他输入一个字符串,程序就会停止

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

Tags: toname程序input键入value数字random
2条回答

好吧,您可以手动循环字符串并使用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")

编辑: 我想会有一些好的和简单的正则表达式解决方案,但我会离开我的手离它,因为我不是太有经验的与它

这将获取任何输入并从中提取第一个数字\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)

相关问题 更多 >