循环并比较作业中的字符串

时间:2018-10-06 04:26:44

标签: python

我需要有关Python入门的作业的帮助。

任务是让计算机选择1到100之间的随机数,并且用户必须猜测该数字。如果您的猜测太高,则会告诉您。如果您的猜测太低,则会告诉您。它将继续重复,直到您猜出所生成的正确数字为止。

我的问题是,如果输入是字符串,那么您会得到提示,说这不是可能的答案。如何解决此问题?

P.S。如果不太麻烦,我想获得有关如何修复代码而不是答案的提示。

代码:

import random

#answer= a
a= random.randint(1,100)

#x= original variable of a
x= a

correct= False
print("I'm thinking of anumber between 1 and 100, try to guess it.")

#guess= g

while not correct:

    g= input("Please enter a number between 1 and 100: ", )

    if g == "x":

       print("Sorry, but \"" + g + "\" is not a number between 1 and 100.")

    elif int(g) < x:

        print("your guess was too low, try again.")

    elif int(g) > x:

        print("your guess was too high, try again.")

    else:

        print("Congratulations, you guessed the number!")

1 个答案:

答案 0 :(得分:0)

因此,如果您要清理输入内容以确保仅输入数字,则可以使用[ [ [odd_clr_val,odd_clr_val,odd_clr_vlue] ... ] .... ]方法进行检查。例如:

from PIL import Image
import numpy as np
import time
#if the value of pixel is:
#Odd = 0 , even = 1
#We make every element odd

img = Image.open('Desktop/test.jpg')

arr = np.array(img)
x,y,z  = np.shape(arr)
count = 0
initial = time.time()

#This nested loop makes every element odd but is very slow and in need to be optimized
for i in range(x):
    for j in range(y):
        count += 1
        k = arr[i][j]
        arr[i][j][0] =  k[0] + int(not(k[0]%2)) # adds 1 if k[i] is odd else 0
        arr[i][j][1] =  k[1] + int(not(k[1]%2))
        arr[i][j][2] =  k[2] + int(not(k[2]%2))

print("Time delta: %f"%(time.time() - initial ))
print("The amount of data you can store in this image is: %d kiBs"%((count*3)/1024))
#every element of this image is odd now

z = input("Enter the string:")

long_array = []
for i in z:
    long_array += list(map(int,list(format(ord(i), '#010b')[2:])))


#everything is in binary now

counter = 0
try:
    for i in range(x):
        for j in range(y):
            k = arr[i][j]

            arr[i][j][0] = k[0] if not(long_array[counter]) else k[0]+1
            counter += 1

            arr[i][j][1] = k[1] if not(long_array[counter]) else k[1]+1
            counter += 1

            arr[i][j][2] = k[2] if not(long_array[counter]) else k[2]+1
            counter += 1
except IndexError:
    print("Done")
except:
    print("An unidentified error occured!")

image = Image.fromarray(arr)

image.show()

image.save("secret.png")

您可以在this StackOverflow thread中了解更多信息。