How can I control my user's Input - python

name = input('Enter your name please: ')
while name != str:
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
while ss != int:
ss = input('Please enter only numbers for your social security number:')
So I have this basic program that asks the user for his name and SS# and I wanted to do so the user can't input a str or a float where he is supposed to input an int. I tried this but it'll just loop forever because the If statement is checking to see if the input is the data type str or int, How can I do it to check if the variable is an int or a str?

You're trying to compare the value with a type. You should instead store the name and check if has only letters (.isalpha()) and try a type casting on the security number. If it fails, it's not a valid input. Using isnumeric() for the SSN is also an option. Something like:
name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False
while not valid_ss:
ss = input('Please enter only numbers for your social security number:')
try:
int(ss)
valid_ss = True
except ValueError:
valid_ss = False
or
name = input('Enter your name please: ')
while not name.isalpha():
name = input('Please enter only letters for your name: ')
ss = input('Enter your Social Security Number: ')
while not ss.isnumeric():
ss = input('Please enter only numbers for your social security number:')

name != str does not do what you think it does. The result of input() is always a string. If you only want to get certain types of strings, then you have to validate them yourself. For checking if something only contains letters or only contains numbers you can use name.isalpha() and name.isnumeric().
If you need something more complicated than what these or othe other builtin string methods provide, then you'll probably need to write a regular expression or other custom validation code.

Related

Writing Python functions

This code executes well, but I don't think this the best way to do it.
def bank_account(Name, number, username, passwrod):
Output = Name, number, username, passwrod
return Output
new_name = input ("Please Enter Your Name: ")
new_number = input ("What's your number please: ")
new_username = input ("Enter your UserName: ")
new_passwrod = input ("(Integers Only!) Enter your Passwrod Sir: ")
print("Your Data has been saved!", bank_account(new_name, new_number, new_username, new_passwrod))
Is there any other way to do it?
As the comments suggest, what you're trying to do is unclear!
Maybe something the bank_account function can do is validate the input?
For example you specify that the password must be numeric. For arguments sake let's say the same is true for the number. Also just assume that the name must only consist only of alphabetic letters.
def bank_account(name, number, username, password):
if not name.isalpha():
print('Your name must only contain letters!')
return 'Invalid'
try:
number = int(number)
password = int(password)
except ValueError:
print('Your number and password must be numeric!')
return 'Invalid'
return name, number, username, password
new_name = input("(alphas) Please Enter Your Name: ")
new_number = input("(ints) What's your number please: ")
new_username = input("Enter your UserName: ")
new_password = input("(ints) Enter your Password: ")
print("Your details:", bank_account(new_name,
new_number,
new_username,
new_password))
Hope this gives you an idea of something you can do with your bank_account function!

How to take user input as tuple and then printing said tuple

Very new at python and im trying to figure out how to write a program to ask the users to input the courses and teachers into a tuple and then have users input "done" as an end. To finish it off i need to print the tuple. Any tips?
such as:
"Please enter your courses:" math
"Please enter your teacher:" John
"Please enter your courses:" done
('math', 'john', etc...)
Since you want to add values iteratively, tuples will not be the best choice for this since they are immutable, You can use either dictionary or lists.
Using Lists:
arr = []
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
arr.append((course,teacher))
Using Dicts
d = {}
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
d[course]=teacher
The user can't input a tuple directly; you'll have to accept each input separately and assemble them into a tuple yourself:
course = input('enter course: ')
teacher = input('enter teacher:' )
mytuple = course, teacher
lst = []
while True:
course = input("Please enter the courses you are taking this semester: ")
if course == 'done':
break
professor = input("Please enter the professor's name for the course: ")
if professor == 'done':
break
lst.append((course, professor))
def convert(lst):
return tuple(lst)
print(convert(lst))
this is what i came up with, thank you

How to detect a invalid input and put the user into a loop until an acceptable answer is typed?

I'm trying to figure out how to get the user to type on letters and return numbers as invalid inputs only.
This is my code, I'm still unclear about the ValueError as if I run the code and type in letters it'll come out as an invalid input but if I put in numbers it comes in as valid.
while True:
try:
name = int(input("What is your name? "))
except ValueError:
print("Invalid response. Letters only please.")
continue
else:
break
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
int(input()) will expect an integer as an input, so when you type your name (unless you're name wholly consists of numbers), you will get a ValueError like you're experiencing now. Instead, you can use str(input()) to get the user input, then use the str.isdigit() method to check if it's a number.
name = str(input("What is your name? "))
if name.isdigit():
print("Invalid response. Letters only please.")
continue
else:
break
you can also try regex to check if a string contains a number:
bool(re.search(r'\d', name))
\d will matches for digits [0-9].
it will return True if the string contains a number.
full code:
import re
while True:
name = input("What is your name? ")
if bool(re.search(r'\d', name)):
print("Invalid response. Letters only please.")
else:
correctName = input("Your name is...'" + (name) + "', is this correct? \n Please use 'Y' as yes and 'N' as no.\n")
if correctName == "Y":
print("Thank you..!")
break
For Python3
while True:
name = input()
if name.isalpha():
break
For Python2
while True:
name = str(input())
if name.isalpha():
break

Dictionary phonebook with userInput, but with a twist

I have been working on this for too long. It should be simple and I've ran through many different combinations, however, I keep getting the code wrong and have no idea why. It works fine when I have manual input, but when I submit there is an error.
question prompt:
Write a program that keeps a dictionary of names and their corresponding phone numbers.
Repeatedly ask the user for a name. Then, do one of the following three things, depending on what they enter:
If they enter nothing, exit the program.
If they enter a name that exists as a key in your dictionary, simply print the corresponding phone number.
If they enter a name that is NOT in your dictionary as a key, ask the user for a phone number, and then put the name and phone number in your dictionary.
Print out the final dictionary.
my code:
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook:
number = input("Please enter number: ")
print "Phone number: " + number
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name in phoneBook:
print phoneBook[name]
if name == '':
break
print phoneBook
Expected result:
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
My result:
Phone number: 1234
Phone number: 5678
Phone number: 9999
1234
Phone number: 9999
5678
Phone number: 9999
{'Tracy': '9999', 'Karel': '9999', 'Steve': '9999'}
you must also access the dictionary keys for checking the existence of a name:
if not name in phoneBook.keys():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook.keys():
number = input("Please enter number: ")
phoneBook[name] = number
print "Phone number: " + number
name = input("Please enter a name(or press enter to end input): ")
else:
print phoneBook[name]
print phoneBook
Try the above code.
When a name is not in the phoneBook, then assign the name a number, so phoneBook[name] = number should be in the if not name in phoneBook.keys(): block. And then enter another name in the same if block.

Python: Input validate with string length

Ok so i need to ensure that a phone number length is correct. I came up with this but get a syntax error.
phone = int(input("Please enter the customer's Phone Number."))
if len(str(phone)) == 11:
else: phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
You can't have
if:
else:
Because the else, being inside the first if block, doesn't have a corresponding if.
It should be:
if:
this
else:
that
You may try this to be asking for the phone number until it is correct:
phone = ""
while len(str(phone)) != 11:
phone = int(input("Please enter the customer's Phone Number."))
phonumber.append(phone)
If you want to check also that the input is a number and not text, you should also trap the exception raised by int in that case, for example:
phone = ""
while len(str(phone)) != 11:
try:
phone = int(input("Please enter the customer's Phone Number."))
except ValueError:
phone = ""
phonumber.append(phone)

Categories

Resources