entry = input("Enter a word:")
if entry == whatever:
print("print this")
I keep getting error whatever is not defined. Why? I want to define it through input
whatever is a string which you are comparing your input with, so you need to put it in quotes. As in
if entry == 'whatever':
Now a small demo after the necessary edit will output
Enter a word:whatever
print this
Related
I'm working on an assignment:
My input is supposed to be a name, it could be anything.
The output is supposed to be the length of the name.
e.g.
Currently, I have:
print(input("What is your name? ")
print(len(input)
But the second half isn't correct.
If you need to DO something with the value, then you have to store it in a variable:
name = input("What is your name? ")
print(name)
print(len(name))
I think I located the problems in your code. This is what it should look like:
n = input("What is your name? ")
print((len(n))
I tested and switched things up a bit by adding a variable called "n" and giving it the input value. Then I wrote a changed into string version of the len of n... If that makes sense.
I put three brackets in the second line because the first one is for the print statement, the second one len, and the last one for the int.
Don't worry too much as it was an honest mistake! :)
PS. This is the better version of the code:
n = input("What is your name? ")
print("Your name has "+len(n)+" letters")
According to your question, your one line code can done in this way:
print(len(input("what is your name ?")))
So, I'm trying to make someone input a string and make python search for the string in the first column, if found then output the entire row.
How'd I go about doing this? (using gspread)
If I understand your question correctly this is the code:
line = ("abcd")
try:
string = input("Please enter a string: ")
if string in line:
print(line)
else:
print("Your input is not in line.")
except ValueError:
print("An error has occured")
The in statement checks to see if the input is in the text and if it is then it prints it out. (You have to change line to match what you want and for multi-line use """ text """). The try and except statements make the program more robust - especially if you can only enter numbers (integers or floats). It won't crash thus is a good habit to get into. You can google the suffixes for except as there is quite a few.
I've been playing around with strings and I've found that when one inputs a string into a input function it gives an error.
I was wondering how to print "invalid" if a string was typed for an input variable. I want to do this the simplest way possible and the function should be the input and not the raw_input and I don't want to use try or except because that would complicate the code I'm planning to create.
testing_variable = input ("enter a number:")
# if a string is entered print invalid
if testing_variable == "":
# the "" is what im using if a string is entered and im having a hard time solving this
#Tips or advice of any coversion of the input would be helpful
print "invalid"
Using the input function in Python 2 is generally a bad idea. It is equivalent to eval(raw_input()), and thus expects the user to input a valid Python expression. If they type in something that is not valid Python, you'll always get an error.
While you could catch various exceptions and translate them into useful error messages, a better approach is to use raw_input and do your own validation for the specific types of input you want to be able to handle. If you only want to accept numbers, try converting the string you get from raw_input to int or float (and catching ValueError exceptions which indicate non-numeric input). For your desired result of printing "invalid":
try:
result = int(raw_input("enter a number"))
except ValueError:
print "invalid"
This is the most Pythonic way to solve the issue. If for some reason you don't want to use exception handling, you can save the string you get from raw_input and analyze it first to make sure it has only the characters you expect before converting it to a number. For base 10 integers this is not too hard, as only digits need to be checked for, and the isdigit method on a string will check if it contains only digit charaters:
str_input = raw_input("enter a number")
if str_input.isdigit():
result = int(str_input)
else: # string contains non-digit characters
print "invalid"
It's quite a bit more complicated to validate the input string if you want to support floating point numbers, as there's no convenient function like isdigit that will check all the characters for you. You could do it if you really wanted to, but I'd strongly recommend going with the exception catching code style shown above and just passing the string to float to see if it works.
Python 2.7 supports input and raw_input.
So, with input, you are expected to wrap your input with quotes. If you are wanting to avoid this, then use raw_input.
Example with raw_input:
>>> raw_input('hi ')
hi hey
'hey'
If you are looking to force the user to always enter a digit, then you can wrap it in a try/except as such:
try:
i = int(raw_input("Enter a number: "))
except:
print("you did not enter a number")
This is the best way in my opinion:
testing_variable = input ("enter a number:")
try:
number_var = int(testing_variable)
print(number_var)
except ValueError:
print("Invalid")
Without using try you can do:
testing_variable = input ("enter a number:")
if not testing_variable.isdigit():
print("Invalid")
In this program i am making a dictionary.
When i run this program and enter 1 in the menu the program asks me to search meaning, but when i type the word 404(which is in the dictionary) it says Word donot exist in dictionary. Where does this problem come from?
print("This is a dictioinary")
print("\t\t\tWelcome to Geek Translator Game")
dictionary={"404":"Message not found","googler":"person who seaches on google"}
choose=None
while(choose!=0):
choose=input('''0.Exit
1.search meaning
2.Add Word
3.Replace meaning''')
if choose is 0:
print("bye")
if choose is 1:
word=input("Enter the word\n")
if word in dictionary:
meaning=dictionary[word]
print(meaning)
else:
print("Word donot exist in dictionary")
if choose is 2:
word=input("Enter the word\n")
if word in dictionary:
print("Word already exists in dictionary")
print("Try replacing meaning by going in option 3")
else:
defination=input("Enter the defination")
dictionary[word]=defination
if choose is 3:
word=input("Enter the term\n")
if word in dictinary:
meaning=input("Enter the meaning\n")
dictionary[word]=meaning
else:
print("This term donot exist in dictionary")
input() interprets user input as a Python expression. If you enter 404, Python interprets that as an integer. Your dictionary, however, contains a string.
You'll have to enter "404" with quotes for this to work correctly. Your better option would be to use raw_input() instead, to get the raw input the user typed without it having to be formatted as a Python expression:
word = raw_input("Enter the word\n")
Do this everywhere you use input() now. For your user menu input, you should really use int(raw_input("""menu text""")) rather than input(). You might be interested in Asking the user for input until they give a valid response to learn more about how to ask a user for specific input.
Next, you are using is to test user choices. That this works at all is a coincidence, as Python has interned small integers you are indeed getting the same 0 object over and over again and the is test works. For almost all comparisons you want to use == instead however:
if choose == 0:
# ...
elif choose == 1:
# etc.
I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb