NameError: имя 'dice1' не определено - PullRequest
0 голосов
/ 23 октября 2019

Он говорит, что dice1 не определен, когда я четко сказал, что он определяет (random.randint(min, max)).

Я пытался изменить имя переменной, но она все еще не работает.

import time
import random

name = input("Enter Your Name")

if name =="Name":
    pwd = input("Enter Password")

    if pwd == 'password':
        print ("Welcome")
    else:
        print ("Incorrect login. Check your details and try again!")

else:
    print("Incorrect Username")     

min = 1
max = 6
score = 0
roll = "Yes"
answer = "no"

#Rolling dice

input("Roll the dice?")

while roll == "yes" or roll == "y" :
    print("Rolling......")
    dice1 = (Random.randint(min, max)) #random number between 1 and 6 as it is a dice
    print (dice1)
    time.sleep(1)
    dice2 = (Random.randint(min, max)) #another random number
    print (dice2)
    time.sleep(1)
    total1 = dice1 + dice2

Ошибка:

NameError: name 'dice1' is not defined`

Ответы [ 2 ]

1 голос
/ 23 октября 2019

У вас есть несколько проблем с предоставленной вами выпиской. Во-первых, вы не определили переменную "roll", которая должна быть входной. Тогда вы не определили ни мин, ни макс. Наконец, кубики будут катиться бесконечно, пока вы не попросите новый ввод в конце цикла (но, возможно, это то, что вы хотите).

Пожалуйста, попробуйте этот код

import time
import random

roll = input("Roll the dice?")
min = 1
max = 6

while roll == "yes" or roll == "y":
    print("Rolling......")

    dice1 = (random.randint(min, max))
    print(dice1)
    time.sleep(1)

    dice2 = (random.randint(min, max))  # another random number
    print(dice2)
    time.sleep(1)

    total1 = dice1 + dice2
    roll = input("Roll the dice?")

Вывод

Roll the dice?yes
Rolling......
4
4
Roll the dice?yes
Rolling......
5
2
Roll the dice?no
1 голос
/ 23 октября 2019

ОБНОВЛЕНИЕ

Вы не назначаете свой ввод для roll, так как он вводит ваши while?

roll = input("Roll the dice?")

Каковы ваши значения min max? Может быть, вы не инициализировали мин и макс. Также вам не следует указывать min и max в качестве имен переменных, пока они являются списочными функциями python, а вы их переопределяете. Я запустил следующее и работает очень хорошо:

if name =="Name":
    pwd = input("Enter Password")
    if pwd == 'password':
        print ("Welcome")
    else:
        print ("Incorrect login. Check your details and try again!")
else:
    print("Incorrect Username")
min = 1
max = 6
score = 0
roll = "Yes"
answer = "no"
roll = input("Roll the dice?")
while roll == "yes" or roll == "y" :
    print("Rolling......")
    dice1 = random.randint(min, max)
    print (dice1)
    time.sleep(1)
    dice2 = random.randint(min, max) #another random number
    print (dice2)
    time.sleep(1)
    score = dice1 + dice2
    print('Score : %d' % score)
...