无法在输入中将字符串转换为float

时间:2013-11-24 01:05:22

标签: python python-3.x

  #My code should take a random between 1 and 100 and let you guess it. 
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
    def reveal(guess):
        return secret_number
    import random 

    secret_number = random.random()*100  
    guess = float(input("Take a guess: ")) #This is the input

    while secret_number != guess :

        if guess < secret_number:
            print("Higher...")
        elif guess > secret_number:
            print("Lower...")
        guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping

    else:
        print("\nYou guessed it! The number was " ,secret_number)
    if guess == "reveal": #This is where I "tried" to make the reveal thingy.
        print ("Number was", secret_number)
    input("\n\n Press the enter key to exit")  

任何帮助都将是一项很棒的服务。此外,我只编程了几周,很抱歉,如果我的代码看起来不对。

4 个答案:

答案 0 :(得分:1)

如果你想使用浮点数进行比较,游戏可能会无穷无尽,因为浮点数有很多小数位数。使用int number。

#!/usr/bin/env python3.3
# coding: utf-8

import random


def guess_number():
    try:
        guess = int(input("Take a guess:"))
    except ValueError:
        print("Sorry, you should input a number")
        guess = -1
    return guess


if __name__ == '__main__':
    secret_number = int(random.random() * 100)
    while True:
        guess = guess_number()
        if guess == -1:
            continue
        elif guess < secret_number:
            print("Lower...")
        elif guess > secret_number:
            print("Higher...")
        else:
            print("\nYou got it! The number was ", secret_number)
            input("\n\nPress any key to exit.")
            break # or 'import sys; sys.exit(0)'

答案 1 :(得分:0)

您可以通过定义一个要求用户输入的函数来隔离关注点,直到提供浮点数:

def input_float(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("You should input a float number. Try again.")

然后你可以在你的脚本中使用它:

guess = input_float("Take a guess: ")

如果除了浮点数之外还想接受'reveal'作为输入:

def input_float_or_command(prompt, command='reveal'):
    while True:
        s = input(prompt)
        if s == command:
           return s
        try:
            return float(s)
        except ValueError:
            print("You should input a float number or %r. Try again." % command)

答案 2 :(得分:0)

使用random.range而不是random.random。

secret_number = random.range(1,100,1)  

...,str(secret_number)

...
else:
    print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
    print ("Number was", str(secret_number))
...

通过这种方式,您将使用字符串连接字符串。此外,您可以保留random.random并仅进行第二次更改。

编辑:

要做的另一件事是使用raw_input而不是input。然后使用try

guess = raw_input("Take a guess: ")
try:
    guess = float(guess)
except:
    pass

这会尝试将guess转换为float,然后它会失败,那么它将保持一个字符串。这应该可以解决你的问题。

答案 3 :(得分:0)

import random

LOWEST = 1
HIGHEST = 100

def main():
    print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
    secret = random.randint(LOWEST, HIGHEST)

    tries = 0
    while True:
        guess = raw_input('Your guess: ').strip().lower()
        if guess.isdigit():
            tries += 1
            guess = int(guess)
            if guess < secret:
                print('Higher!')
            elif guess > secret:
                print('Lower!')
            else:
                print('You got it in {} tries!'.format(tries))
                break
        elif guess == "reveal":
            print('The secret number was {}'.format(secret))
            break
        else:
            print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))

if __name__=="__main__":
    main()