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.
Related
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")
Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.
I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:
count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2
But the program fails with:
ValueError: invalid literal for int() with base 10: 'Sina dumb\n'
depending on if I leave the newline in or not.
Please what am I doing wrong, and how can I make it better?
In python2.x or python 3.x
sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.
I think you need this(assuming)
import sys
input_var = input() # or raw_input() for python 2.x
# entering Sina dumb
>>>print(len(input_var.split()))
2
Update
If you want to count how much input you enter.Try this
import sys
from itertools import count
c = count(1)
while True:
input_var = input()
print ("you entered " + str(next(c)) + " inputs")
On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)
On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.
input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.
you could try regular expression:
import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)
I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.
I'm trying to solve a Krypto Problem on https://www.spoj.pl in Python, which involves console input.
My Problem is, that the Input String has multiple Lines but is needed as one single String in the Programm.
If I just use raw_input() and paste (for testing) the text in the console, Python threats it like I pressed enter after every Line -> I need to call raw_input() multiple times in a loop.
The Problem is, that I cannot modify the Input String in any way, it doesn't have any Symbol thats marks the End and I don't know how many Lines there are.
So what do I do?
Upon reaching end of stream on input, raw_input will return an empty string. So if you really need to accumulate entire input (which you probably should be avoiding given SPOJ constraints), then do:
buffer = ''
while True:
line = raw_input()
if not line: break
buffer += line
# process input
Since the end-of-line on Windows is marked as '\r\n' or '\n' on Unix system it is straight forward to replace those strings using
your_input.replace('\r\n', '')
Since raw_input() is designed to read a single line, you may have trouble this way.
A simple solution would be to put the input string in a text file and parse from there.
Assuming you have input.txt you can take values as
f = open(r'input.txt','rU')
for line in f:
print line,
Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here
buffer = ''
while True:
try:
line = raw_input()
except EOFError:
break
if not line:
break
buffer += line
Write a program that outputs the first number within a file specified by the user. It should behave like:
Enter a file name: l11-1.txt
The first number is 20.
You will need to use the file object method .read(1) to read 1 character at a time, and a string object method to check if it is a number. If there is no number, the expected behaviour is:
Enter a file name: l11-2.txt
There is no number in l11-2.txt.
Why is reading 1 character at a time a better algorithm than calling .read() once and then processing the resulting string using a loop?
I have the files and it does correspond to the answers above but im not sure how to make it output properly.
The code i have so far is below:
filenm = raw_input("Enter a file name: ")
datain=file(filenm,"r")
try:
c=datain.read(1)
result = []
while int(c) >= 0:
result.append(c)
c = datain.read(1)
except:
pass
if len(result) > 0:
print "The first number is",(" ".join(result))+" . "
else:
print "There is no number in" , filenm + "."
so far this opens the file and reads it but the output is always no number even if there is one. Can anyone help me ?
OK, you've been given some instructions:
read a string input from the user
open the file given by that string
.read(1) a character at a time until you get the first number or EOF
print the number
You've got the first and second parts here (although you should use open instead of file to open a file), what next? The first thing to do is to work out your algorithm: what do you want the computer to do?
Your last line starts looping over the lines in the file, which sounds like not what your teacher wants -- they want you to read a single character. File objects have a .read() method that lets you specify how many bytes to read, so:
c = datain.read(1)
will read a single character into a string. You can then call .isdigit() on that to determine if it's a digit or not:
c.isdigit()
It sounds like you're supposed to keep reading a digit until you run out, and then concatenate them all together; if the first thing you read isn't a digit (c.isdigit() is False) you should just error out
Your datain variable is a file object. Use its .read(1) method to read 1 character at a time. Take a look at the string methods and find one that will tell you if a string is a number.
Why is reading 1 character at a time a better algorithm than calling .read() once and then processing the resulting string using a loop?
Define "better".
In this case, it's "better" because it makes you think.
In some cases, it's "better" because it can save reading an entire line when reading the first few bytes is enough.
In some cases, it's "better" because the entire line may not be sitting around in the input buffer.
You could use regex like (searching for an integer or a float):
import re
with open(filename, 'r') as fd:
match = re.match('([-]?\d+(\.\d+|))', fd.read())
if match:
print 'My first number is', match.groups()[0]
This with with anything like: "Hello 111." => will output 111.