invalid syntax for "from import random" - python

when I try to run this module
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()
I get invalid syntax highlighting the import.
what is the issue?
I have already tried import random but it doesn't seem to want to work

Your code is full of errors. I have fixed indentation and other syntax issues.
You don't need to use from, just use import random.
Here is the code
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()

Fixed your indentation, spelling, capitalization, insertion of unnecessary spaces and comparing between a string and int which would always be false.
Also added str.title to allow for all types of capitalization for 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()

Related

random number random.randint is giving me "invalid syntax. Perhaps you forgot a comma?"

I am trying to make a random number guessing game. My random.randit is saying "invalid syntax. Perhaps you forgot a comma?" and I don't know why.
import os,random,time
def start():
while True:
game=input("number guess(1), ")
if game=="1":
numberguess()
def numberguess():
while True:
range=input("1-25(A),1-50(B),1-100(C) ")
if range=="A":{
random.randint(1, 4)
numg=input("guess the number: ")
if num==numg:
print("Correct")
playagian=input("Play again(Y/N")
if playagain=="Y":
continue
elif playagain=="N":
start()
}
I don't know what to try to fix this issue.
Remove braces {} after if range=="A": as we don't use {} in python.
Replace:
import os,random,time
def start():
while True:
game=input("number guess(1), ")
if game=="1":
numberguess()
def numberguess():
while True:
range=input("1-25(A),1-50(B),1-100(C) ")
if range=="A":
random.randint(1, 4)
numg=input("guess the number:")
if num==numg:
print("Correct")
playagian=input("Play again(Y/N")
if playagain=="Y":
continue
elif playagain=="N":
start()

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

Function Is Not Running

Just started to code, can't figure out why the start function will not ask me for any user input.
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!") #Asks me for user input... Doesn't work
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")
You want to give consideration to your program as a module.
Try making the following changes:
import random
_NUMBER = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + _NUMBER)
else:
print("Aww :( ")
if __name__ == "__main__":
start()
The "if name"... addition allows your program to be run from the interpreter as a module. You can also import this module into other programs easily.
I've also changed the syntax on your global variable (number) to reflect best practices. It's now private -- indicated by the underscore -- and uppercase.
If this program is imported as a module, the global variable won't impact those of the same name.
Now you can do python filename.py from the command line, or from filename import start and start() from the interpreter to run your program.
You have to call the function.
start()
Working script:
import random
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print "Rolling the dice... The number is... ", number
else:
print("Aww :( ")
start()
You never actually call the function:
number = random.randint(1,6)
def start():
print("Do you want to start?")
answer = raw_input("Type 'Yes' to start!")
if answer == "yes":
print("Rolling the dice... The number is... " + number)
else:
print("Aww :( ")
start()
Just like the other two said, you haven't called the function "start()". Also you asked to type "Yes" but you check if the user gave "yes".

Int is not callable

I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().

Why will this program not work in the shell, but work in my IDE?

Im having a problem with a dice roller program (text for now but eventually graphical). It will not work in anything except for the IDE I use, Wing IDE 101 4.1. The error i get flashes too fast for me to read, but i will try to take a screenshot of it. (I will edit this post if i get a screenshot.)
Here is the program:
import random
#variables
available_dice = "D20"
main_pgm_start = False
#definitions of functions
def diePick():
print("Pick a die. Your choices are: ", available_dice)
print("")
which_dice = input("")
if which_dice == "D20" or which_dice == "d20":
rollD20()
else:
print("Error: Please try again")
print("")
diePick()
def rollD20():
print("Rolling D20 .... ")
print("")
d20_result = random.randrange(1, 20)
print("You have rolled a ", d20_result)
print("")
print("Would you like to roll again?")
print("")
y = input("")
if y == "y" or y == "Y" or y == "yes" or y == "Yes":
print("")
diePick()
def MainProgram():
print("Benjamin Ward's Random D&D Dice Roller")
print("")
x = input(" Press Enter to Continue")
print("")
diePick()
MainProgram()
You can redirect the log to the text file with "logging" module if my memory serves.
I dont think input() does what you expect it to. input reads a line of text, then executes it (as python).
I think what you want is more along the lines of stdin.readline(). To use it, you will have to from sys import stdin at the top, then replace all occurences of input with sys.readline(). Note also that this will return a newline at the end, which you have to account for.

Categories