我对编程非常陌生,我正在尝试用python 3.6编写一个程序,该程序会生成一个随机数作为“答案”,然后计算机必须猜测该答案是否包含x个问题。为了跟踪计算机猜对了多少个问题,我创建了一个称为“正确”的变量,如果计算机的答案等于猜测,则将一个变量添加到该变量中。但是,即使错了,它也会每次执行。抱歉,这看起来很愚蠢,但谢谢您的帮助
import random
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
while n <= x:
ans()
guess()
if cor == gue:
right += 1
n += 1
print(right, n)
答案 0 :(得分:0)
我试图通过将ans()
和guess()
函数移到total(x,t)
函数之外来略微修改您的代码,因为它们似乎彼此独立。先前ans
和guess
随机生成cor
和gue
,但没有返回要在if
语句中使用的值,该语句始终使用的初始值0
。现在,通过将返回值另存为cor = ans()
和gue = guess()
,0
和cor
的{{1}}的初始化值将被覆盖。
gue
输出
import random
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
return cor
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
return gue
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if cor == gue:
right += 1
n += 1
print(right, n)
print (total(2,3))
答案 1 :(得分:0)
ans
和guess
之类的嵌套函数可能很有用,但是我在开始编程时会尽量避免使用它。它使您的程序更难以理解。
这是您要尝试做的事情(如果我正确理解的话!)
import random
# Play number_of_games_to_play of the number guessing game allowing a maximum of max_guesses per game played.
def play(number_of_games_to_play, max_guesses):
num_games = 0
guessed_right = 0
while num_games < number_of_games_to_play:
if guess_number(max_guesses):
guessed_right += 1
num_games += 1
print('\n\nI played', num_games, 'games and guessed right', guessed_right, 'times')
# Generate a random number, try and guess it up to max_guesses times. Returns whether the number was guessed correctly or not.
def guess_number(max_guesses):
answer = random.randint(1, 4)
print('\n\nPlaying guess_number. The right answer is', answer)
num_guesses = 0
while num_guesses < max_guesses:
guess = random.randint(1, 4)
print('The computer guesses', guess)
if guess == answer:
print('That is right!')
return True
else:
print('That is wrong')
num_guesses += 1
return False
play(number_of_games_to_play = 5, max_guesses = 4)
答案 2 :(得分:0)
我认为您在变量范围方面遇到问题:函数内部的import { Injectable, ErrorHandler } from '@angular/core';
import {ErrorLogService} from './error-log.service';
// Global error handler for logging errors
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
constructor(private errorLogService: ErrorLogService) {
//Angular provides a hook for centralized exception handling.
//constructor ErrorHandler(): ErrorHandler
super();
}
handleError(error) : void {
this.errorLogService.logError(error);
}
}
和import { NgModule, ErrorHandler } from '@angular/core';
import {ErrorLogService} from './error-logg.service';
import {GlobalErrorHandler} from './global-error.service';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
UserComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
RouterModule.forRoot([
{ path: '', component: AppComponent, pathMatch: 'full', canActivate: [AuthGuard]},
{ path: 'user', component: UserComponent, canActivate: [AuthGuard]},
{ path: 'login', component: LoginComponent}])
],
providers: [ ErrorLogService, // register global error log service
GlobalErrorHandler,// register global error handler
EmployeeService, // register Employee service
ValidationService, //register Validation Service
AuthenticationService, //register Authentication Service
UserService],//register User Service
bootstrap: [AppComponent]
})
export class AppModule { }
与变量外部的变量不同。您的函数没有更改cor
和gue
的值,它们正在创建两个仅存在于其中的新变量(也分别命名为cor
和gue
)。因此,cor
和gue
始终为0,if语句中的条件始终为true,并且每次都要递增cor
。
要解决此问题,可以将变量作为参数传递给函数。
答案 3 :(得分:0)
问题来自可变范围。在方法ans中定义的可变核心与for循环中初始化的可变核心不同。 更好的方法是:
随机导入
def ans():
c = random.randint(1, 4)
return c
def guess():
g = random.randint(1, 4)
return g
def total(x, t):
for i in range(t):
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if (cor == gue):
right += 1
print("Answer: %6d Guess: %6d Right: %d" % (cor, gue, right))
n += 1
print(right, n)