Python: Input validate with string length - python

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)

Related

Finding the oldest and ending on specific user input

I have just started Python and I am attempting a simple exercise. It's to end a program on a user specified input and then finding the oldest age from a set of ages entered. I got the user input but having issues with the oldest age aspect. Where am I going wrong? I think I may not be 100% on the "None" aspect. Here is code below:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
elif name.strip() == 'Yvonne':
if largest is None or largest < age:
largest = age
print("Oldest age is: ", largest)
break
The output I get is the wrong number being selected as the oldest:
You’ve got your test for largest in the wrong place:
largest = None
while True:
name = str(input("What is your name? enter Yvonne to end program."))
if name.strip() != 'Yvonne':
age = int(input("Please enter your age"))
if largest is None or largest < age:
largest = age
else:
print("Oldest age is: ", largest)
break

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!

Passing 'ValueError' & 'continue' in a function and call it

I am trying to check user inputs to ensure that:
1) It is a floating number
2) Floating number is not negative
I am trying to put above 2 checks into a function and call it after user has input into a variable.
However, I cant seem to put 'ValueError' & 'continue' in a function that I can call. Is this possible?
I have tried below code, but it repeats from the top when I key in 't' for salCredit, or any of the next few variables. The code will work if I were to repeat 'ValueError' & 'continue' for every variable. I'm just wondering if there is a shorter way of doing do?
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
#checkInputError(accBal)
salCredit = float(input("Enter your Salary: "))
#checkInputError(salCredit)
creditCard = float(input("Credit Card Spend (S$): "))
#checkInputError(creditCard)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
interestCalculator()
Expected results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Salary: 500
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a valid number.
Enter your Salary: 500
Current results:
Scenario 1: if user inputs 't'
Enter your Account Balance: 5000
Enter your Salary: t
Please enter a valid number.
Enter your Account Balance:
Scenario 2: if user inputs negative number
Enter your Account Balance: 5000
Enter your Salary: -50
Please enter a positive number.
Credit Card Spend (S$):
You could create a function that continues prompting for input until a valid float is input
def get_float_input(prompt):
while True:
try:
user_input = float(input(prompt))
if user_input < 0:
print("Please enter a positive number.")
continue # start the while loop again
return user_input # return will break out of the while loop
except ValueError:
print("Please enter a valid number.")
mul_AccBal = get_float_input("Enter your Account Balance: ")
salCredit = get_float_input("Enter your Salary: ")
creditCard = get_float_input("Credit Card Spend (S$): ")
Try this:
def interestCalculator():
#User inputs required for calculation of interest earned.
while True:
invalid = True
while invalid:
try:
mul_AccBal = float(input("Enter your Account Balance: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
salCredit = float(input("Enter your Salary: "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
invalid = True
while invalid:
try:
creditCard = float(input("Credit Card Spend (S$): "))
invalid=checkInputError(salCredit)
except ValueError:
print("Please enter a valid number.")
continue
def checkInputError(userInput):
if userInput < 0:
print("Please enter a positive number.")
return True
return False
interestCalculator()
you need to break you while loop if all the input is successful (also note that the continue at the end of the while loop is unnecessary). and if you want to have a validation for every number separately, you could do something like this:
def get_float(message, retry_message="Please enter a valid number."):
while True:
try:
ret = float(input(message))
if ret >= 0:
return ret
else:
print(retry_message)
except ValueError:
print(retry_message)
def interestCalculator():
mul_AccBal = get_float("Enter your Account Balance: ")
salCredit = get_float("Enter your Salary: ")
creditCard = get_float("Credit Card Spend (S$): ")

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.

How can I control my user's Input

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.

Categories

Resources