problem with Input() function when don`t want user enter number - python

i wrote an script , i want to know how to prevent when user enter number i show a message 'number is not OK! just string') .
Thanks.
#! /usr/bin/ipython3
a=input('Please enter your Name : ')
if a=='mohammadreza':
print(" ")
print ('i found you finally')
print(" ")
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')

You have a string. And if you want to check if it is a number, you can use the following code:
a.replace('.','',1).isdigit()
So you can create a new elif like this:
elif a.replace('.','',1).isdigit():
print("number is not OK! just string")

problem here is input always return a string. isdigit handle this for you but it fails with floats (this is the reason behind "replace . solution").
Another approach could be:
#!/usr/bin/env python
def is_a_number(s):
'''try to convert a string to int and float'''
try:
int(s)
return True
except:
pass
try:
float(s)
return True
except:
pass
return False
def main():
a=input('Please enter your Name : ')
if a=='foo':
print ('i found you finally')
elif is_a_number(a):
print('number is not OK! just string')
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')
if __name__ == '__main__':
main()

Related

Not getting any results

I am trying to write code to find the length of a string, and to return "invalid entry" when an integer is entered.
def length_of_string(mystring):
if type(mystring) == int:
return "invalid entry"
else:
mystring = input("enter the string ")
return len(mystring)
When I try to execute this function it doesn't give me an error, nor does it produce any solution.
You should move out mystring = input("enter the string ") from else and call the function from main or other place.
def length_of_string(mystring):
if type(mystring) is int:
return "invalid entry"
else:
return len(mystring)
mystring = input("enter the string ")
print(length_of_string(mystring))
If you want the string to be always requested from the user:
def length_of_string():
mystring = input("enter the string ")
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string())
If you want to use the function with a parameter:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string("a string")) # prints 8
print(length_of_string(1)) # prints invalid entry
print(length_of_string(input("enter the string "))) # prints [input length]
The problem is that you have not called the function. Functions (similar to classes) do not run until you execute them.
Calling them is easy. You just have to call the function name. You also have to pass the necessary parameters to the function (here it is mystring).
length_of_string('Hello World')
To get what is returned you will need to pass it to a variable or print it/perform some other action.
print(length_of_string('Hello World'))
Also if type(mystring) == int: will not work input() is always a string. The thing to do is to test it and see if it can be made into an integer:
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
Entire code:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
print(length_of_string('Hello World'))
If you pass a string by parameter, it does not make sense to overwrite it again.
I think the solution is:
def length_of_string(mystring):
if (isinstance(mystring, str)):
print "Length of the string: ", len(mystring)
else:
print "Type invalid"

Python 3.x input variable

I want to get user input of a code that has to be 11 numbers long and must not contain any characters. Otherwise the question to enter will be repeated.
code=input("Please enter your code ")
while len((code)) !=11: #here should be something to nullify strings inout :)
code = input("Please enter your code and in numbers only ")
There is definitely a better solution for this, just can't think of any.
This might be what you're after
def validate(s):
for char in s: #iterate through string
if not char.isdigit(): # checks if character is not a number
return False # if it's not a number then return False
return True # if the string passes with no issues return True
def enter_code():
while True: #Will keep running until break is reached
code = input("Please enter your code: ") #get user input
# if the length of input and it passes the validate then print 'Your code is valid'
if len(code) == 11 and validate(code):
print('Your code is valid')
break #break out of loop if valid
# if code fails test then print 'Your code is invalid' and return to start of while loop
print('Your code is invalid')
if __name__ == '__main__':
enter_code()

Menu prompt doesn't work

I have written an application in Python to work with strings, i made a menu prompt from which i can select an operation to do, i tested all the functions, they work well, except the menu and main functions, that when i enter my choice nothing happens. Here's the code:
import re
import os
def searchInFile(searched, file):
try:
f = open(file)
except IOError.strerror as e:
print("Couldn't open the file: ", e)
else:
sea = re.compile(searched, re.IGNORECASE)
for line in f:
if re.search(sea, line):
print(line, end='')
def validateWithPattern(string):
patt = re.compile('([a-z0-9-_.])+#([a-z]+.)([a-z]{2,3})', re.IGNORECASE)
if re.search(patt, string):
print("Valid")
else:
print("Not valid!")
def menu():
print("|================MENU=================|\n", end='')
print("|0- Exit the program |\n", end='')
print("|1- Validate mail address |\n", end='')
print("|2- Search a string in a file |\n", end='')
print("|=====================================|\n", end='')
b = input("->")
return b
def main():
b = 10
while b != 0:
b = menu()
if b == 1:
a = input('Enter you mail address: ')
validateWithPattern(a)
elif b == 2:
a = input('Enter the file name: ')
c = input('Enter the string: ')
searchInFile(c, a)
elif b == 0:
os.system("PAUSE")
else: print("Choice error")
if __name__ == "__main__":
main()
Your b variable you are returning from menu function is a string, not an integer, so you can't compare it with numbers (input is automatically saved as string). If you use return int(b) instead of return b, it will be ok.
Also, I think your else: print("Choice error") should be indented the same way your if and elif are, since you probably want to write "Choice error" only if b is not one of given choices. The way it is indented in your code will print "Choice error" after the while loop ends and it will not print that message if you input the value it can't recognize (for example 3).

Python Syntax Error (except ValueError:)

I have a small code which is just for me to get more used to python and I have encountered a problem with try and except.
I am trying to get the code below to ask a question and receive an answer using raw_input. If you know what the syntax error in line 22 is? (except ValueError)
Thank you very much.
def start():
print("Type start")
prompt_sta()
def prompt_sta():
prompt_0 = raw_input ("Enter command start")
try:
if prompt_0 == "start":
prompt_sta()
elif prompt_0 == "begin":
print ("You must learn to follow commands")
prompt_sta()
elif promt_0 == "help":
print ("Commands:")
print ("Help")
print ("start")
print ("begin")
prompt_sta()
else:
print ("Please enter a valid command.")
prompt_sta()
print ("Type start")
**except ValueError:**
def outside_house():
print("There is a strange man outside.")
Just in case the error that IDEL is showing has ** on both sides and if you know any better ways for doing what I am trying to do please tell me. Thanks
You need to provide a body for except: statements:
try:
a = "something"
except ValueError:
pass # empty body

Checking user input via raw_input method

I'm trying to use raw_input to get input from the user, i want to catch the instances where the user may enter a number. I've been searching threw stack overflow and various other websites and i haven't come across anything that made much sense to me. Since raw_input always returns a string is it even possible to catch such an instance?
class Employee(object):
def __init__(self,name,pay_rate,hours):
self.name = name
self.pay_rate = pay_rate
self.hours = ("mon","tues","wed","thursday","friday","saturday","sunday")
def __str__(self):
return self.name
#property
def weekly_total(self):
return sum(self.hours)
#classmethod
def from_input(cls):
while True:
try:
name = raw_input("Enter new employee name\n")
except ValueError:
print("\n This is a integer ")
continue
else:
break
while True:
try:
pay = input("Enter pay rate ")
except ValueError:
print("You must enter a value ")
continue
else:
break
while True:
try:
hours = input("Enter a tuple for days monday through sunday ")
except ValueError:
print("use must enter a tuple with 7 integer values")
continue
else:
break
return cls(name,pay,hours)
employee = Employee.from_input()
print str(employee)
I would split this into separate functions; there are neater ways to do this, but I have made them as similar as possible so you can see the process:
def get_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
print "Please enter an integer."
else:
return i
def get_non_int_input(prompt):
while True:
s = raw_input(prompt)
try:
i = int(s)
except ValueError:
return s
else:
print "Please don't enter an integer."

Categories

Resources