【发布时间】:2017-07-29 20:21:59
【问题描述】:
我目前正在用 python 编写 2 个程序,它们必须互相玩数字游戏。一个程序选择一个介于 1 和 100 之间的数字。然后另一个程序尝试猜测该数字是什么。每次猜测者给出它的猜测,然后选择者回答“太大”、“太小”或“你知道了”。根据回答是什么,猜测者相应地调整下一个猜测。
这是我选择的程序的代码:
import random
from guesser import g
guessCount = 0
number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
outfile = open ('response.txt', 'w')
guess = 50
print (guess)
if guess < number:
print('Your guess is too low.')
switch = '1'
outfile.write (switch + '\n')
elif guess > number:
print('Your guess is too high.')
switch = '2'
outfile.write (switch + '\n')
else:
print('Correct, You guessed the number in', guessCount, 'guesses.')
switch = '3'
outfile.write (switch + '\n')
while guessCount < 8:
guess = g
print (guess)
guessCount += 1
if guess < number:
print('Your guess is too low.')
switch = '1'
outfile.write (switch + '\n')
elif guess > number:
print('Your guess is too high.')
switch = '2'
outfile.write (switch + '\n')
else:
print('Correct, You guessed the number in', guessCount, 'guesses.')
switch = '3'
outfile.write (switch + '\n')
break
outfile.close()
print('The number was',number)
下面是给出猜测的程序代码:
low = 1
high = 100
guess = 0
guessCounter = 0
infile = open ('response.txt', 'r')
switch = int (infile.readline())
def g (switch):
while switch != 3 and guessCounter < 8:
guess = (low+high)//2
guessCounter += 1
if switch == 1:
high = guess
elif switch == 2:
low = guess + 1
return guess
我的主要问题是如何让这两个程序相互交互。我目前正在尝试使用一种方法让他们通过名为 response 的文本文件进行通信,但肯定有更简单的方法吗?
The main problem I'm having it seems is that when chooser tries to get the variable g from guesser it can't because there's no response currently in response.txt meaning switch = int (' ')
Traceback(最近一次调用最后一次):文件 “C:\Users\Jash\Downloads\guesser.py”,第 8 行,在 switch = int (infile.readline()) ValueError: int() 以 10 为底的无效文字:''
是的,它们必须是 2 个独立的程序。并且必须在python中完成。
【问题讨论】:
-
你想单独启动你的脚本,还是如果你有一个为其他脚本创建子进程的主脚本可以吗?
-
或者你可以使用套接字。
-
@michip96 他们是否单独开始都没有关系,这是针对我的一个班级的小组项目。我已经达到了我只是想尝试直到它起作用的地步哈哈任何帮助都非常感谢。
标签: python if-statement ipc