A small game that guesses numbers, but there are the following errors in pycharm, opening with IDLE is no problem. May I ask what is the reason?
#guess number
import random #use import function convert random module
num = random.randint(0,11) #create random int
temp = input ('Please type you guess number: ') #type random str
guess = int (temp) #temp convert to int, if the str is decimal could use int(float(temp)) transfer
while guess != num: #while loop
print ("Sorry! You are wrong.")
temp = input ('Please type the number again: ')
guess = int (temp)
if guess == num:
print ('Amazing!')
else:
if guess > num:
print ("The number is high.")
else :
print ('The number is low.')
print ('Congragulation!')
D:\Anaconda\python.exe "C:/Users/Sky Talk/PycharmProjects/untitled/Key"
File "C:/Users/Sky Talk/PycharmProjects/untitled/Key", line 7
print "dict['name']:",dict['name']
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("dict['name']:",dict['name'])?
Process finished with exit code 1
code screenshot
error message
terminal screenshot
Print(words) is a command that accepts parameters. When you use the print function, you have to use the parenthesis, or you will get an error. Use the suggestion that the error message gave you:
print("dict['name']:",dict['name'])
Related
I was writing a code to get a student grade point average but I got an error.
here is the piece of my code getting error :
scoreinput=input("Score lesson: ")
while True:
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
scoreinput = int(input("This number is too big. Try again: "))
elif scoreinput < 0:
scoreinput = int(input("This number is too low. Try again: "))
else:
print("please write number correctly...")
This is the output of this code which has got an error :
Score lesson: 5
Traceback (most recent call last):
File "e:\TEST PYTHON\test3.py", line 3, in <module>
if scoreinput.isnumeric():
AttributeError: 'int' object has no attribute 'isnumeric
please help me. thanks
If the input is a positive number below 20, which is what you want to have, after scoreinput=int(scoreinput)
you have the number, but instead of doing something, you continue to the next iteration of the while loop. On the next iteration, scoreinput is an int and not str this is why you get an error. If scoreinput is in the correct range, you should use break to stop the loop.
Another problem occurs when the input is wrong. If the input is not a number, you are not getting a new input and will be stuck in an infinite loop. If the input is a number, but not between 0 to 20, you get new input and imminently cast it to int. If the input is not a number you will get an exception. If it is a number, it will fail as soon as you reach the next iteration since scoreinput should be str at the beginning of the iteration, but it will be int.
I would suggest you will use the following code:
while True:
scoreinput=input("Score lesson: ") # using input only one time at the beggining of the loop instead of input command for each case of bad input
if scoreinput.isnumeric():
scoreinput=int(scoreinput)
if scoreinput > 20:
print("This number is too big. Try again.")
elif scoreinput < 0:
print("This number is too low. Try again.")
else:
break # input is valid
else:
print("please write number correctly...")
If you write on the top: scoreinput = int(input('Score lesson: ')) you won't have to verify if scoreinput is numeric or alphabetic.
I did google it a lot, and I think I figured out what was causing it, but I don't understand why.
When I would try to run this code:
from random import randint
def getNums():
nums = set()
nums = randint(100, 999)
return str(nums)
def askUser():
try:
guess = int(input("Choose 3 digits to play the game: "))
except:
print("Please enter numbers only.")
return guess
def compare(num, guess):
try:
if guess == num:
print("Guessed!")
print(f"The number was {num}")
elif guess[0] in num or guess[1] in num or guess[2] in num:
print("Match")
elif num != guess:
print("Nope")
except IndexError:
pass
#GET RANDOM DIGITS
num = getNums()
#ASK THE USER TO ENTER THEIR GUESS
#GAME
while True:
guess = askUser()
guess = str(guess)
compare(num, guess)
if num == guess:
break
I would get
---> 23 elif guess[0] in num or guess[1] in num or guess[2] in num:
24 print("Match")
25 elif num != guess:
IndexError: string index out of range
When I would try with 0.
Removing the int(input) and casting the int variables to string seems like it fixed it, but I don't know why there was a problem to start with since they had the same length. Thank you
When you enter a number like '012', and you convert it to an int (12), then the resulting string will be '12'.
As you can see, you no longer have a string of length 3 in this example, but of length 2.
So you get an IndexError when accessing guess[2], since that index does not exist (at least you get the IndexError when you remove the try/except statement).
A simple way around this would be to store the user input in the variable without trying to parse as int, and then just use int() without changing guess.
Something like this:
def askUser():
try:
guess = input("Choose 3 digits to play the game: ")
int(guess)
except:
print("Please enter numbers only.")
return guess
There are other things that can be improved, like only returning guess when there's no error (otherwise you'll get an exception), only catching a ValueError instead of all exceptions, and actually testing if the user input is exactly three characters long.
If I am understanding your code and question, when you cast the int to a string, you are able to parse it as a string hence, why it works. If you pass it as an int, you cannot parse an int by positional reference such as guess[0].
To me, you corrected the issue by casting it to a string that allowed for your parsing.
Also, by using the Python "in" keyword, it will check to see if the value is in the string so, you do not need to parse through the string as "in" will return True or another output if you use an "if" statement.
I want the print statement to print the number in the range between the low and upper.
I keep getting the error code:
Traceback (most recent call last):File "python", line 5, in <module> ValueError: non-integer arg 1 for randrange()
From the program:
from random import*
lowRange = input('What is the lower range number?')
hiRange = input('What is the higher range nunmber?')
ran = randrange (lowRange,hiRange)
print (ran)
The input() function always returns a string. If you want to use integers, as in this case, you have to convert those strings to integers using int(). However, if the user enters something that cannot be converted to an integer (e.g. 'hi', or just hitting return), you will get an error when trying to convert. To deal with that, you will want to look into try and except statements. Hope that helps!
Try this:
In here until you enter a number it wouldn't stop. Inputs other than int will take as an invalid input.
What's wrong in your code is everything reads from input is taken as a string.
from random import*
while True:
try:
lowRange = int(input('What is the lower range number?'))
break
except:
print("That's not a valid input!")
while True:
try:
hiRange = int(input('What is the higher range nunmber?'))
break
except:
print("That's not a valid input!")
ran = randrange (lowRange,hiRange)
print (ran)
I'm trying to create a small code that asks a user to enter a number between 1 and 100. However my Else statement will not output when entering a string. I want my Else statement to print a message if the user enters an input other than an integer or float. Here is my code.
def between():
print ("Please enter a number between 1 and 100.")
number = eval(input())
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
elif number > 100 or number < 1:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
between()
between()
The easiest method would be to use try and except
num = input()
try:
number = float(num)
# code to do if num is a number
except ValueError:
print("Not a number!")
# code to do if num isn't a number
If num isn't a number, then converting it to a float would raise ValueError going on to the except.
If num is a number, the coversion of it to a float would run fine, and continue on in the try.
Side note: I highly suggest not using eval(input()) but rather just input(), see this for why you shouldn't use eval. Also eval(input()) won't work with my example above.
Try this:
print "Please enter a number between 1 and 100"
in = input()
try:
num = int(in)
if 1 <= num <= 100:
print("Valid")
else:
print("Out of bounds")
except:
print("Invalid")
Try:
def between():
print ("Please enter a number between 1 and 100.")
number=0
try:
number = int(input())
except:
print ("ERROR! You have entered an invalid value. Please try again using numerical values only.")
exit(1)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
between()
Note: why you use eval and input together? I don't think that's right, correct me if I'm wrong
There are a few logical issues with your code. First before using eval() you must be aware of the security risk associated with it. Consider going through this post for some insight. If you entered some arbitrary input in eval, it will most likely be a run time error.
Now, assuming that the variable actually has a value. To check if it is an integer or a float and is in the desired range or something else (possibly a string), you can not directly apply comparison operators with it because if the variable is not a number it will most likely give a TypeError during comparison with other integers.
Hence a correct approach would be to first check if the variable is of desired type by checking if type(r) is int or type(r) is float only then you should apply test for range. If the above type checking is false then you should print your "else" error message.
Try is too slow and should be avoided when not necessary
num = input("Please enter a number between 1 and 100: ")
if num.replace('.','').isdigit():
num = float(num)
if number >= 1 and number <= 100:
print ("Thank you! You entered",number,"which is within the 1 and 100 range.")
between()
else:
print ("OOPS! You entered",number,"Please enter a number between 1 and 100.")
between()
else:
print('thats not a number!')
I'm making a program in python. It is suppose to take in a GTIN number and put in a list and then check if it's valid. The program works, but as soon as I enter a GTIN number that starts with a 0, I get a "invalid token (, line 1)" error. I really need a solution because some products have their GTIN numbers starting with a 0.
when I input a number for example:
96080832
The program works great.
When i put in a number like:
00256986
I get an error:
invalid token (<string>, line 1)
pointing to this line:
inputtedInt = int(input("Enter the gtin number: "))
Whole def:
def chooseOption(inputInt):
while(inputInt > 0 and inputInt < 4):
if(inputInt == 1):
print("you picked option number 1")
showOptions()
break
elif(inputInt == 2):
print(" ")
inputtedInt = int(input("Enter the gtin number: "))
gtin = map(int,str(inputtedInt))
checkValidity(gtin, 2)
print(" ")
showOptions()
break
elif(inputInt == 3):
print("you picked option number 3")
showOptions()
break
else:
option = int(input("Error - enter a number from 1 to 3. : "))
chooseOption(option)
Thanks in advance.
You seem to be using Python 2. In Python 2, input tries to evaluate the input string as a Python expression, and a leading 0 on a numeric literal in Python 2 syntax means that the number is in octal, or base 8. Since 8 and 9 are not valid digits in base 8, this input constitutes a syntax error.
If you were supposed to be using Python 3, get on Python 3. If you're supposed to be on Python 2, use raw_input instead of input.
Additionally, if you care about preserving things like leading zeros, you should keep the input as a string and only call int on it when you want to do math on it as an integer.
Error is raised because you are mapping str ant/to int in line:
gtin = map(int,str(inputtedInt))
for example if you ty to run:
a = 005
You will get following error:
File "<stdin>", line 1
a = 005
^
SyntaxError: invalid token
Sollution -> you should use stringsfor GTIN number :)