im wondering why is
File "<string>", line 1
.
^
SyntaxError: unexpected EOF while parsing
coming when i execute following script and including dot in input.
answer = input('enter 1: ')
if answer == 1:
print('nice')
else:
print('please enter "1"')
return
I have been wondering this pretty long, and now im trying to ask here if someone could help me.
So i can't include dots or anything else that basic letters and numbers my input.
I thought there could be easy way to find this thing out.
There is other code i need to fix below, with same error.
email = str(input('required* Your mail: '))
print('your mail is : ' + email)
now, it needs to include dot and at mark.
The code here seems ok, except for the fact you're using return without a function.
And the code wouldn't work when I put I type 1, because you need to cast the var "aswer".
The code should be like this:
answer = int(input('enter 1: '))
if answer == 1:
print('nice')
else:
print('please enter "1"')
You are putting a string and you are checking if is this a number, that is your error, so if you want to ask every time if the answer is wrong you could do this:
while True:
answer = input('enter 1: ')
if answer == "1":
print('nice')
break
else:
print('please enter "1"')
Related
I wrote a length converter with python,
here are the codes:
active = True
while active:
option = input('please choose:\na:centimetre to inch \nb:inch to centimetre:')
if option == "a":
centimetre = input('Please enter centimetre:')
centimetre= float (centimetre)
inch = centimetre / 2.54
print(str(centimetre) + ' centimetre equals' + str(inch) + ' inches')
elif option == "b":
inch = input('Please enter inch:')
inch = float ( inch )
centimetre = inch * 2.54
print(str(inch) + ' inch equals ' + str(centimetre) + ' centimetre')
else:
print("sorry you entered wrong option。please enter 'a'or'b': ")
continue
status = input('continue? yes/no :')
if status == 'no':
active = False
It's ok when these codes run with notepad++ and
http://www.pythontutor.com/
but when I try to use pycharm, it got error:
line 6, in <module>
centimetre= float (centimetre)
ValueError: could not convert string to float:
not sure where is the problems. Has anyone met this issue?
You could try checking if the input is able to be converted into a float, using try:.
And, also, if it's an issue with Python not recognizing commas as a decimal point, and maybe periods as a thousands separator, then you could check for if the number with commas and periods swapped (using the .replace() method).
An example of this is:
x = '2.3'
y = '3,4'
def isnumber(num):
try:
float(num)
return True
except ValueError:
try:
float(num.replace(',', 'A').replace('.', 'B').replace('A', '.').replace('B', ','))
return True
except ValueError:
return False
if isnumber(x):
print(f'The number {x} is valid.')
else:
print(f'The number {x} is not valid.')
print()
if isnumber(y):
print(f'The number {y} is valid.')
else:
print(f'The number {y} is not valid.')
You are probably using wrong decimal separator on input. Perhaps comma "," instead of full stop "."
You need to replace that or catch the error (or both together). I suggest:
try:
centimetre = float(centimetre.replace(',', '.'))
except ValueError:
print('Input is not a valid number or in invalid format!')
i tried days to fix it and have solved this issue
i created a brand new project in pycharm and put the code in a new file.
it works now
if you just copy and paste the code to existed pycharm project, it might not work
not sure why, but at least it's not my codes' fault and it works now.
Try this:
centimetre = float(input('Please enter centimetre:'))
I am trying to write a simple python code to guess a random number between 1 and 20. For the incorrect guess, the system shows intended message but for the correct guess it is not giving the proper output.
Could someone help me understand the issue in the below code
import random
import sys
answer=random.randint(1,20)
nt=0
cg=0
while cg!=answer:
nt=nt+1
print('Guess the correct number')
cg=input()
if cg==answer:
print('Congrats! You have guessed correctly in' + str(nt) + ' tries')
sys.exit()
print('Guess is incorrect. Please try again. Answer is ' + str(answer) + ' in ' + str(nt) + ' tries')
continue
In cg=input(), input() return type in 'str'. So the condition cg==answer will always be false.
Use:
cg=int(input())
instead of
cg=input()
read more about input() here
choice = input (" ")
choice = int(choice)
if choice == 2:
print ("What class are you in? Please choose (class) 1, 2 or 3.")
Class = int(input ())
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
ScoreCount = str(ScoreCount)
c1.write(myName + "-" + ScoreCount)
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
if choice == 3:
row[1]=int(row[1]) #converts the values into int.
row[2]=int(row[2])
row[3]=int(row[3])
row[4]=int(row[4])
if choice == 4:
WMCI= 1
print ("Thank You. Bye!")
So when this code is actually run it outputs an error which I don't understand:
ValueError: invalid literal for int() with base 10:#(myName-score)
How to fix this and what does this error mean in simple terms?
You've got 2 bugs.
The first is when you store your score into the csv, you're converting ScoreCount into a string, and keeping it that way. You need to let the conversion be temporary for just the job:
#class 1 file
if Class == 1:
c1 = open('class1.csv', 'a+')
c1.write(myName + "-" + str(ScoreCount))
c1.write("\n")
c1.close()
read_c1 = open('class1.csv', 'r')
print (read_c1)
That'll fix it with Class 1, you'll need to do 2 & 3. Your second bug is when you're reading the scores from the file, you've stored them as: "Name-5" if the person called Name had scored 5. That means you can't convert them as a whole entity into a number. You'll need to split the number part off. So in min max, where you've got:
row[0] = int (row[0])
It needs to become:
row[0] = int(row[0].split("-")[1])
But from there I can't figure out your logic or what you're trying to achieve in that section of code. It'll get rid of the current error, but that part of your code needs more work.
Explaining the right hand side of the above line of code by building it up:
row[0] # For our example, this will return 'Guido-9'
row[0].split("-") # Splits the string to return ['Guido','9']
row[0].split("-")[1] # Takes the second item and returns '9'
int(row[0].split("-")[1]) # Turns it into a number and returns 9
split("-") is the part you're likely to not have met, it breaks a string up into a list, splitting it at the point of the "-" in our example, but would be at the spaces if the brackets were left empty: split() or any other character you put in the brackets.
You are probably trying to convert something that can't be converted to an int for example
int("h")
This would give the base 10 error which you are getting
How to change below code and remove unnecessary new line?
#"Please guess a number!"
choice = input ("Is it ")
print ("?")
Is it 10
?
So that result will look like
Is it 10?
To "remove" the newline in your code snippet you would need to send cursor control commands to move the cursor back to the previous line. Any concrete solution would depend on the terminal you're using. Strictly speaking, there are no unnecessary newlines in the sample above. The user provided the newline that follows 10, not Python. I suppose you could try to rewrite the input processor so that user input isn't echoed similar to getpass.getpass().
If someone looking for a solution, I found one-liner:
print('Is it ' + input('Please guess a number: ') + '?')
Firstly, with above line user input requested as
Please guess a number:
Then user enter the value
Please guess a number: 10
After input confirmation (Pressing Enter) next line appears as
Is it 10?
you mean something like that?
choice = input ("enter somthing...")
print ("Is it "+str(choice)+"?")
If you need it to be longer then the above one you could drag it out.
Choice = input("Number:")
answer = "Is it %s ?" % choice
print(answer)
I like Shohams tho, more pythonic imho
Very similar to the accepted answer in this question: remove last STDOUT line in Python
But here it is tailored to your solution. A little hackish admittedly, would be interested in a better way!
choice = input ("Is it ")
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print CURSOR_UP_ONE + ERASE_LINE + 'Is it ' + str(choice) + '?'
I do deep you cannot.Because if the procedure is "choice = input("Is it ")",you must be to what end the enter,the line must be is new line.you can the change the express.
choice = input("Please input the number:")
print "Is it " + str(choice) + " ?"
This question already has answers here:
Receive a string, convert to calculate and display response, but.. Can't split
(2 answers)
Closed 9 years ago.
I am a python newbie.I am getting familiar with loops and tried this example from a book
while True:
s = input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
However the output is as follows
Enter something : ljsdf
Traceback (most recent call last):
File "trial_2.py", line 2, in <module>
s = input('Enter something : ')
File "<string>", line 1, in <module>
NameError: name 'ljsdf' is not defined
You have to use raw_input() instead (Python 2.x), because input() is equivalent to eval(raw_input()), so it parses and evaluates your input as a valid Python expression.
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
Note:
input() doesn't catch user errors (e.g. if user inputs some invalid Python expression). raw_input() can do this, because it converts the input to a string. For futher information, read Python docs.
you want raw_input() in python2
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'
input() tries to evaluate (dangerously!) what you give it
Your code will work fine in python 3.x
But if you are using python 2 you will have to input string using raw_input()
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print('Length of the string is', len(s))
print('Done')
It seems like you're using Python 2.x, while the code is expected to be run in Python 3.x.
input in Python 2.x evaluates the input string unlike input in Python 3.x.
In Python 2.x input() is designed to return numbers, int or float depending on the input from the user, you can also enter variable names.
you need to use:
raw_input('Enter something: ')
The error is caused because Python thinks that "ljsdf" is the name of a variable, and that's why it raises this exception:
NameError: name 'ljsdf' is not defined
becuase "ljsdf" is not defined as a variable. :D
raw_input() is safer to use, and then convert the input to whatever other type after :D