running into unidentifiable syntax error [duplicate] - python

I have a simple Python question that I'm having brain freeze on. This code snippet works. But when I substitue "258 494-3929" with phoneNumber, I get the following error below:
# Compare phone number
phone_pattern = '^\d{3} ?\d{3}-\d{4}$'
# phoneNumber = str(input("Please enter a phone number: "))
if re.search(phone_pattern, "258 494-3929"):
print "Pattern matches"
else:
print "Pattern doesn't match!"
Pattern does not match
Please enter a phone number: 258 494-3929
Traceback (most recent call last):
File "pattern_match.py", line 16, in <module>
phoneNumber = str(input("Please enter a phone number: "))
File "<string>", line 1
258 494-3929
^
SyntaxError: invalid syntax
C:\Users\Developer\Documents\PythonDemo>
By the way, I did import re and tried using rstrip in case of the \n
What else could I be missing?

You should use raw_input instead of input, and you don't have to call str, because this function returns a string itself:
phoneNumber = raw_input("Please enter a phone number: ")

In Python version 2.x, input() does two things:
Reads a string of data. (You want this.)
Then it evaluates the string of data as if it were a Python expression. (This part is causing the error.)
The function raw_input() is better in this situation because it does #1 above but not #2.
If you change:
input("Please enter a phone number: ")
to read:
raw_input("Please enter a phone number: ")
you'll eliminate the error of the phone number not being a valid Python expression.
The input() function has tripped up so many people learning Python that starting with Python versions 3.x, the designers of the language removed the extra evaluation step. This makes input() in versions 3.x behave the same as raw_input() in versions 2.x.
See also a helpful wikibooks article.

The input() function actually evaluates the input that's typed into it:
>>> print str(input("input: "))
input: 258238
258238
>>> print str(input("input: "))
input: 3**3 + 4
31
It's trying to evaluate '258 494-3929' which is invalid Python.
Use sys.stdin.readline().strip() to do your read.

input() calls eval(raw_input(prompt)), so you want phoneNumber = raw_input("Please enter a phone number: ").strip()
See also http://docs.python.org/library/functions.html#input and http://docs.python.org/library/functions.html#raw_input

Related

Create a username using Python

I'm just learning Python and have to create a program that has a function that takes as arguments a first and last name and creates a username. The username will be the first letter of the first name in lowercase, the last 7 of the last name in lowercase, and the total number of characters in the first and last names. For example, Jackie Robinson would be jobinson14. I have to use sys.argv.
This is my code:
import sys
def full_name(first, last):
first = input(first)
last = input(last)
username = lower((first[0] + last[:7])) + len(first+last)
return username
first = sys.argv[1]
last = sys.argv[2]
username = full_name(first, last)
print ("Your username is",username)
When entering Darth Vader
Expected output:
Your username is dvader10
Actual output:
Darth
Please help!
Actual output:
Darth
Not exactly. You are using input(first), which is waiting for you to type something...
Using sys.argv means you need to provide the arguments when running the code
python app.py Darth Vader
And if you remove the input() lines, this would return without prompting for input, and not show Darth
As shown, you are trying to read from arguments and prompt for input.
If you did want to prompt, then you need to remove the import
def full_name(first, last):
return (first[0] + last[-7:] + str(len(first+last))).lower()
first = input('First Name: ')
last = input('Last Name: ')
username = full_name(first, last)
print("Your username is",username)
And just run the script directly. But you say you have to use sys.argv, so the solution you're looking for is to not use input() at all.
When you call the input() function and assign it to first, like this:
first = input(first)
what you're doing is printing first (so "Darth"), waiting for the user to enter something, and then assigning that to first. That's why your script prints Darth -- it's waiting for you to tell it what first is.
But since you already passed the first and last name via the command line, you don't want to do that -- so just remove those two input lines. Make sure to convert the len to a str before you add it to the other strings!
def full_name(first, last):
return (first[0] + last[:7] + str(len(first+last))).lower()
You ask to input names even if they are in sys.argv.
Input("Enter name: ") accepts string that help to understand what you should input.
As OneCricketeer commented, you trying to get first 7 letters instead of last.
Here is an example that accepts names from command line otherwise prompt to input.
import sys
def full_name(_first, _last):
return f"{(_first[0] + _last[-7:])}{len(_first + _last)}"
if __name__ == '__main__':
first = last = ""
if len(sys.argv) == 3:
if sys.argv[1]:
first = sys.argv[1].lower()
if sys.argv[2]:
last = sys.argv[2].lower()
if not first:
first = input("Input first name: ").lower()
if not last:
last = input("Input last name: ").lower()
username = full_name(first, last)
print("Your username is", username)

ValueError with input and int

I am in an intro to programming class which is using zyBooks so I'm not sure (due to the way this interpreter works) if my problem is just me doing something stupid or just not working properly with the zyBooks thing.
Its asking me to do a basic user input string. These are the instructions:
Assign user_str with a string from user input, with the prompt: 'Enter a string: '
Hint -- Replace the ? in the following code: user_str = ?('Enter a string: ')
I believe i've followed the instructions its given me but I'm getting this error. Thanks for any help!!!
1
2 '''Your Solution Goes here '''
3 user_str = int(input'Enter a string: '))
4 print()
5
6 print(user_str)
The error I'm getting:
Exited with return code 1
Traceback (most recent call last):
File "main.py", line 3, in <module>
user_str = int(input('Enter a string: '))
ValueError: invalid literal for int() with base 10: 'Hello!'
You cannot turn Hello! into an int. Get rid of the int(...) around input.
Note: You can turn strings into ints if the string is a valid number.
Im a little confused with your question, so I will answer both interpretations I can make.
If you want the user to enter a string (ex: Hello World), you want to save it as a string in a variable, so omit the int() function that will try (and fail) to convert it to a integer:
user_str = input('Enter a string: ')
If you want an integer instead (ex: 231) the problem is that you are asking the user for a string, so a better solution would be:
user_str = int(input('Enter a number: '))
or:
user_str = int(input('Enter a integer: '))
The correct way for this case would be to try to convert it to a integer, and print a message if it fails (Probably you haven't seen this in your class yet):
correct_inp = False
while not correct_inp:
inp_str = input('Enter a integer: ')
try:
user_str = int(imp_str)
correct_inp = True
except:
print("Ups, this is not an integer, try again")
print(user_str)

How to make print() accept the user input in same line? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 4 years ago.
When i am tying to take user input in python then it is taking input in next line but I want ti to take input in same line. How to achieve that?
I am taking input like this
print("Enter your name:",end=" ")
It is showing on console as
Enter your name:
Ankit
but I want it as
Enter your name:Ankit
You need to use the input method:
response = input("Enter your name:")
(or raw_input for python 2)
By using the input() method
Just type,
userinput = input("Enter your name: ")
If you are using Python 2.x:
response = raw_input("Enter your name:")
If you are using Python 3.x:
response = input("Enter your name:")
Alternate solution:
For python 2.x:
print("Enter your name:"),
response = raw_input()
For python 3.x:
print("Enter your name:", end="")
response = input()

Python program giving unexpected results, why?

My python program is giving unexpected results within the regular expressions functions, when I enter a number plate for recognition, it tells me it's invalid, although it is valid and I don't know why?
I would be grateful if you could tell me what's wrong and give a possible solution, as this is a very important homework assignment.
#Start
#04/02/2016
bad=[]#initialise bad list
data="Y"#initialise value to prevent infinite loop
standardNumberPlateObj=""
NumPlate=""
import re#import re functions
import pickle#import pickle function
print ("Welcome to the number plate recognition program.\n\n")
choice=input("Press 1 to input number plates and save\nPress 2 to read binary number plate file: ")
if choice == "1":
while data=="Y":# while loop
NumPlate = input("Input Registration number in format (XX01 XXX) *With a space at the end!*:\n\n") #user input for numberplate
standardNumberPlateObj=re.match(r'\w\w\d\d\s\w\w\w\s', NumPlate, re.M|re.I)#validate that numberplate is valid
if standardNumberPlateObj:
print("Verification Success")
data=input(str("Would you like to continue? (Y/N):"))
else:
print("Verification Failed")
bad.append(NumPlate)#add numberplate to bad list
data=input(str("Would you like to continue? (Y/N):"))#ask user to continue
while data=="N":#saving number plates to file if user enters N
f = open("reg.dat", "wb")
pickle.dump(bad, f)
f.close()
print ("\nRestart the program to read binary file!")#ending message
break
elif choice == "2":
print ("\nBad number plates:\n\n")
f=open("reg.dat", "rb")
Registrations = pickle.load(f)
print(Registrations)
f.close()
else:
print ("Please enter a valid choice!")
print ("\n END of program!")
It's not really possible to tell without an example input and the expected and the actual result.
But judging from the expression \w\w\d\d\s\w\w\w\s and your example in the prompt (XX01 XXX), I'd say that your regular expression is expecting a space in the end, while your input doesn't provide one.

New line for input in Python

I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))

Categories