Python : Input, Raw input error [duplicate] - python

This question already has answers here:
"NameError: name '' is not defined" after user input in Python [duplicate]
(3 answers)
Closed 6 years ago.
I am trying a simple Hello world, this is my code-
def hello(name=''):
if len(name) == 0 :
return "Hello, World!"
else :
return "Hello, %s!" %(name)
my_name = raw_input()
x = hello(my_name)
print (x)
This code works fine if I use raw_input, but if I use input, it gives an error.
Doesn't the new python not support raw_input.
I also want to know why I defined the parameter in my function as following-
def hello(name='')
Why did I need to use the '' after name
I am really confused, please help. If you have any advice to improve my program, it's appreciated

If you are passing string with input, you have to also mention the double quotes ", for example "My Name"
Whereas in raw_input, all the entered values are treated as string by default
Explanation:
# Example of "input()"
>>> my_name = input("Enter Name: ")
Enter Name: "My Name"
# Passing `"` with the input, else it will raise NameError Exception
>>> my_name
'My Name' <--- value is string
# Example of "raw_input()"
>>> my_name = raw_input("Enter Name: ")
Enter Name: My Name
# Not passing any `"`
>>> my_name
'My name' <--- still value is string

Related

Python case insensitive or sensitive strings as input [duplicate]

This question already has answers here:
How do I do a case-insensitive string comparison?
(15 answers)
Closed 1 year ago.
I have the following script:
ip = input('Enter your string: ')
if 'tree' in ip:
print('Correct string')
I would like to print 'Correct string' even if the user input is 'TREE' or 'tree' based on the case. How do I do that (optimally rather than using else or elif)?
If the input from the user is 'TREE' then the script should give an output:
CORRECT STRING
If the input from the user is 'tree' then the script should give an output:
correct string
How do I do that?
Convert the user input to lower case as:
ip = input('Enter your string: ').lower()
if 'tree' in ip:
print('Correct string')

Removing all instances of [] and ' ' from files [duplicate]

This question already has answers here:
Best way to replace multiple characters in a string?
(16 answers)
How to replace two things at once in a string?
(6 answers)
Closed 3 years ago.
I have text file with the following content:
Hi, my name is 'James'. What is your [name]
I wont to remove the ' ' and the [] from the text so the output looks like this:
Hi, my name is James. What is your name
Here is my code:
s= Hi, my name is 'James'. What is your [name]
s=s.replace("[","")
s=s.replace("'","")
However the output leave a bracket to the right of name:
Hi, my name is James. What is your name]
Any ideas?
You forgot to replace ] in your original code. You can also chain replace statements together
In [2]: s= "Hi, my name is 'James'. What is your [name]"
In [3]: s = s.replace("'",'').replace("[","").replace("]","")
In [4]: s
Out[4]: 'Hi, my name is James. What is your name'
Or you can use a regex to strip of [] and ' using the regex [\[\]\'], which essentially replaces the characters []' when found in the string with an empty character using re.sub
import re
s = "Hi, my name is 'James'. What is your [name]"
out = re.sub(r"[\[\]\']", "",s)
print(out)
The output will be
Hi, my name is James. What is your name
if your trying to just put this in console or terminal then print("Hi, my name is James. What is your name? ") will work just fine
But if you are looking for a person to 'talk' and respond then use an input like,
input('Hi, my name is James. What is your name ')
the user can then type after this and if you use a variable you can respond to the users response
example
name = input('whats your name'? )
print('Hi' + name + 'How are you'? )
putting spaces after question marks will make the code look better(in my opinion) when being executed.

If user types numbers instead of letters, show this error [duplicate]

This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 5 years ago.
I'm creating a program where it collects data from the user, I have finished the basic inputs of collecting their first name, surname, age etc; however I wanted the user to have no numbers in their first name or surname.
If the user types a number in their first name such as "Aaron1" or their surname as "Cox2"; it would repeat the question asking for their name again.
Attempt 1
firstname=input("Please enter your first name: ")
if firstname==("1"):
firstname=input("Your first name included a number, please re-enter your first name")
else:
pass
Attempt 2
firstname=input("Please enter your first name: ")
try:
str(firstname)
except ValueError:
try:
float(firstname)
except:
firstname=input("Re-enter your first name: ")
Any suggestions?
First create a function that checks if there are any digits in the string:
def hasDigits(inputString):
return any(char.isdigit() for char in inputString)
Then use a loop to keep asking for input until it contains no digits.
A sample loop would look like the following:
firstname=input("Please enter your first name: ")
while hasDigits(firstname):
firstname=input("Please re-enter your first name (Without any digits): ")
Live Example
You can check if the name contains letters only with isalpha method.
#The following import is only needed for Python 2 to handle non latin characters
from __future__ import unicode_literals
'Łódź'.isalpha() # True
'Łódź1'.isalpha() # False

Printing strings with print() in Python [duplicate]

This question already has answers here:
Why is my print function printing the () and the "" along with the statement?
(2 answers)
Closed 5 years ago.
I am learning Python and I run into a syntax problem. When I try to create a function that prints "Hello (name)", the quotation marks and the comma appear alongside the string.
For example:
def sayHello(name = 'John'):
print('Hello ', name)
sayHello()
prints as:
('Hello ', 'John')
Any idea why it's the case?
Thanks!
You code would work as expected in Python 3.
Python 2 uses print statement, i.e command, rather than function.
The command understands your argument as a tuple (pair).
Correct use of print command in Python 2
print 'Hello,' name
Alternatives are
print 'Hello, %s' % name
See Using print() in Python2.x
for details
In python, () means a tuple. It will print "()" if its empty, and "(value1, value2, ...)" if it contains values.
In your example, you print a tuple which contains two values "Hello" and name.
If you want to print "Hello (name)", you could try:
print "Hello ", name
print "Hello " + name

Python : Another Name Error

I have two sets of code that essentially have the same goal but neither work and come up with the same name error. I'm trying to make it so they only letters are accept as answers, not numbers. When a number is entered as the input the program works fine but letters do not. Pleases also note that I am still new to python and am looking for basic commands if possible. I know their are many other questions like this one but none that I found answered my question. The error that comes up specifically points out the Name = input("What's your name?\n") line. Thank you in advance!
1
LetterCheck = True
while LetterCheck == True:
Name = input("What's your name?\n")
if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):
print('Your name must NOT include numbers.')
else:
LetterCheck = False
print(Name)
2
LetterCheck = True
while LetterCheck == True:
Name = input("What's your name?\n")
global Name
try:
Name = int(Name)
except ValueError:
Name = str(Name)
LetterCheck = False
else:
print("Your name must NOT include numbers")
print(Name)
The Error
What's your name?
45
Your name must NOT include numbers
What's your name?
Will
Traceback (most recent call last):
File "C:/Users/Will/Documents/Python/Task 1 Debugging.py", line 3, in <module>
Name = input("What's your name?\n")
File "<string>", line 1, in <module>
NameError: name 'Will' is not defined
if "0" or "1" or "2" or "3" or "4" or "5" or "6" or "7" or "8" or "9" in str(Name):
This will always tell you there is a number in your name, because "0" is a non-zero length string and therefore truthy. Python sees if "0" or and stops there because it already knows the whole thing must be true.
What you probably want is something more like:
if any(digit in Name for digit in "0123456789"):
Or, arguably better:
if any(char.isdigit() for char in Name):
The other one where you're trying to convert the name to an integer will only succeed in the conversion if the name is all digits, not if it contains a digit. That's not what you want so you shouldn't do it that way.
You're running this in Python2. In Python2, input evaluates the user's input AS CODE. This means when you do:
>>> input("Name: ")
Name: Will
It tries to evaluate to some variable named Will. There is no such variable, so it throws a NameError. You can test this by entering "Will" (note the quotes). Now it evaluates it as a string and should work properly. But of course you could also write import os; os.listdir() and get a list of the current directory followed by what will likely be a TypeError. input is not safe in Python2.
Instead (in Python2), use raw_input.
I would just like to point out a few things:
First, "1" or "2" or "3" or "4" will evaluate "1" or "2" which is true and stop. You have to write out "1" in name or "2" in name, etc. That's highly inefficient and you should look at the posted function for has_int() as that would be a better way to implement it.
Also a name may have digits and still won't probably be parsed as an int() and raise an error so the second check is not effective at determining if a string has any numbers, only if the string is only numbers
Finally, it's not necessary but it is good practice to name your variables with lowercase letters.
Also, your name error could be because of input if you python version is not 3. Try using raw_input() if that is the case.
The goal here is to check if a string contains numbers.
if it does, ask again.
else, quit
# return true if given string does not have any numbers in them.
def has_int(s):
return any(char.isdigit() for char in s)
# ask what the name is
name = input('What is your name?')
# check if this user input has int
while has_int(name):
# if it does, re-prompt
print('Name cannot include numbers')
name = input('What is your name?')
# finally, say the name
print('Your name is {}'.format(name))
Very glad that you have decided to reach out.
I think regular expressions (python module re) (more info here: https://docs.python.org/2/library/re.html) are right up your alley. Regular expressions will allow you to determine if your string matches a "mold" or a pattern, which you can define by yourself
Regular expressions are a very broad and deep subject that take a bit of time to get used to, but I think they're absolutely worth your time. Take this introductory, friendly tutorial: http://regexone.com/
Then, in python, you can try this:
import re
input_str = raw_input(">?") #reads user input
if re.match('[0-9]+', input_str): #if the input matches the pattern "one or more numbers in the string"
print "Only letters a-z allowed!" #error out of the program
sys.exit()
The thing of importance here is the part with [0-9]+, which means "one or more numbers, any of them from 0 to 9".
Alright, I know I messed up with my previous code but to make up for it I present a working alternative, OP can refactor their program a bit like the following:
import re
while True:
input_str = raw_input("What's your name? ") #reads user input
if ( re.match('[0-9]+', input_str) ): # while the input doesn't match the pattern "one or more numbers in the string"
print "Your name must NOT include numbers." #error out of the program
else:
break
print "if you see this, the entered name fullfilled the logical condition"
Good luck!

Categories

Resources