2017-02-14 63 views
-2

,当我尝试运行此模块无效语法“来自导入随机”

from import random 
def guessnum(): 
    randomnum = random.randint(1,6) 
awnser = input ("what do you think the number is? ") 
if awnser==randomnum: 
    print ("good job. you are correct. ") 
else: 
    print ("incorrect. better luck next time. ") 
restart = input ("would you like to try again? ") 
if restart = Yes or y: 
guessnum() 
else: 
    end() 

我得到无效的语法高亮进口。

问题是什么?

我已经尝试import random但它似乎不希望工作

+1

看起来像你最好再和你有什么资源,学习Python的:有一个令人惊讶的大量的代码量小的错误。 – Biffen

+1

修复你的导入回到正确的'导入随机'和你的缩进,如果你仍然有问题明确说明它是什么。 – Julien

回答

0

你的代码是完全错误的。我已经修复了缩进和其他语法问题。 你不需要使用,只需使用import random

下面是代码

import random 

def guessnum(): 
    randomnum = random.randint(1,6) 
    awnser = input ("what do you think the number is? ") 
    if awnser==randomnum: 
    print ("good job. you are correct. ") 
    else: 
    print ("incorrect. better luck next time. ") 

restart = input ("would you like to try again? ") 
if restart == "Yes" or "y": 
    guessnum() 
else: 
    end() 
0

固定的缩进,拼写,大小写,多余的空格的插入和stringint这将永远是假之间的比较。

还增加str.title,允许各类资本对restart

import random 
import sys 

def guessnum(): 
    random_num = random.randint(1,6) 
    answer = int(input("What do you think the number is? ")) 
    if answer == random_num: 
    print("Good job. you are correct!") 
    else: 
    print("Incorrect. Better luck next time. The number was %d" % random_num) 
    restart = input("Would you like to try again? ") 
    if restart.title() in ["Yes", "Y"]: 
    guessnum() 
    else: 
    end() 

def end(): 
    print("Goodbye!") 
    sys.exit(0) 

guessnum() 
+0

thankyou @ shash678但是,如果我一起加入多个脚本,或者如果我想创建一个“游戏室?”,我将不得不在每个脚本中导入导入,但这仍然有效吗? – Scratchndent

+0

@Scratchndent您在此问题中提出的问题http:/ /stackoverflow.com/a/1057765/6328256,但我有一种感觉,它可能会稍微提高一点,所以当你还是新手时,只需在每个“游戏”脚本的顶部放置相同的导入语句。顺便点击绿色的勾号按钮,您能够将我的答案标记为正确/有用吗? – shash678