This is my first coding class and I'm a little confused...
Im looking to write a program that prompts for a phone number and determines whether or not it's a valid 10-digit number by ignoring any punctuation. I have to write a function that takes the phone number string as a parameter and returns True if it is valid, and False if not. I also have to use a loop to iterate over the string and increment counter whenever I see a digit.
I'm not sure this is correct , but this is what I came with so far. I'm not sure how to create a loop to iterate over a string to determine True or False phone numbers.
main():
phone_number= input("Please enter a phone number in the format XXX-XXX-XXXX: ")
validNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c!= "-":
phone_number=input("Please inter a valid phone number:")
return False
elif
How about think the solution with step-by-step?
Check the number of "-" that split the number to three part.
Check the length of each XXX(or XXXX) at XXX-XXX-XXXX, if the each XXX has appropriate length(3, 3 and 4)
Check if each XXX(or XXXX) is decimal or not.
The code can be like:
def validNumber(phone_number):
p_num_list = phone_number.split('-') # get list of each XXX
if len(p_num_list) is not 3: # if the number has 3 part
return False
else:
if len(p_num_list[0]) is not 3: # Check length of each part
return False
if len(p_num_list[1]) is not 3:
return False
if len(p_num_list[2]) is not 4:
return False
if p_num_list[0].isdecimal() and p_num_list[1].isdecimal() and p_num_list[2].isdecimal(): # check if each part is decimal
return True
return False
if __name__ == '__main__':
p_num = input("Enter the phone number : ")
print(validNumber(p_num))
You could try something like this:
def valid_number(phone_number):
try:
number = [str(int(i)) for i in phone_number.split('-')]
except:
print('Error, only numbers allowed')
number = ''
if len(''.join(number)) == 10:
print('This is a valid phone number')
return True
else:
print('This is not a valid phone number')
return False
def main():
phone_number = input('Enter number in format xxx-xxx-xxxx: ')
valid_number(phone_number)
if __name__ == '__main__':
main()
int() is trying to convert the string into an integer, if it fails, its not a number, then it checks whether the number is 10 characters long or not returning then True or False.
Related
How can I write orders with loop, dictionary and if statement by python
If I want the output result from dictionary list and for the others input print a sentence
Here is my program could someone find what is the solution for the mistakes
def phone_guide():
guide_number = input("Enter a number:")
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
While guide_number == 1111111111:
print("Amal")
elif guide_number == 2222222222:
print("Mohammed")
elif guide_number == 3333333333:
print("khadijah")
elif guide_number == 4444444444:
print("Abdullah")
elif guide_number != numbers:
print("Sorry, the number is not found")
#This mean the number has to be from the dictionary list
else:
print("This is invalid number")
#This mean if the number less or more than 10 number or different value or string
phone_guide()
There are multiple issues you need to fix. The indentation is wrong and the loop has issues. You need to iterate over the dictionary and check if value exists.
def phone_guide():
print "Enter a number:"
guide_number = input()
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
for key,value in numbers.items():
if guide_number == value:
print(key)
return
print("Sorry, the number is not found")
phone_guide()
First of all, its unneccessarily complicated to store name: number if you want to check the number. Is it possible to reverse it like number: name?
numbers = {1111111111: "Amal", 2222222222: "Mohammed", ...}
Secondary you don't need all these if/elif/else statements. You can check if an item is in a dictionaries keys or values.
1111111111 in numbers.keys() or 1111111111 in numbers.values()
To match your phone numbers validity you can use a regex like this and check if typeof(phone_number) == int.
import re
invalid = 1234568
valid = 0123456789
re.match(r'\d+{10}', valid)
>>> True
re.match(r'\d+{10}', invalid)
>>> False
Given all these information you should be able to come to the solution.
There are multiple errors in your code. Go through the basics of python again.
def phone_guide():
guide_number = int(input("Enter a number:"))
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
for key, value in numbers.items():
if guide_number == value:
return key
return "This is invalid number"
def phone_guide():
guide_number = input("Enter a number:")
numbers = {"Amal": 1111111111, "Mohammed": 2222222222, "Khadijah": 3333333333, "Abdullah": 4444444444}
if guide_number == 1111111111:
print("Amal")
elif guide_number == 2222222222:
print("Mohammed")
elif guide_number == 3333333333:
print("khadijah")
elif guide_number == 4444444444:
print("Abdullah")
elif guide_number != numbers:
print("Sorry, the number is not found")
else:
print("This is invalid number")
Write your code as above. In python you can only use elif after if.
I am creating a Bingo console application in Python and am having a problem with (possibly) the remaining_selections() function.
The idea is when a user guesses a number in the list, that number gets replaced with an 'X' (single digit) or 'XX' (double digit).
After each user input, the list is checked to see if any there are any integers remaining in the list and if not the user has a BINGO.
The problem I'm facing is that the return value of the remaining_selections() function always returns True regardless of the logic I use.
The reason I suspect the problem is in the remaining_selections() function is because when I hard code a False value the code executes a 'Bingo!!'
Any ideas where I am going wrong??
It's not a large program so have included the entire code.
def draw_bingo_card():
'''
Draw bingo card from bingo_card list
'''
print(
f"\n",
f"----------------\n",
f" BINGO CARD\n",
f"----------------\n",
f"| {bingo_card[0]}|{bingo_card[1]}|{bingo_card[2]}|{bingo_card[3]}|{bingo_card[4]}|\n",
f"----------------\n",
f"|{bingo_card[5]}|{bingo_card[6]}|{bingo_card[7]}|{bingo_card[8]}|{bingo_card[9]}|\n",
f"----------------\n",
f"\n",
)
def remove_number(number):
'''
Check if the number chosen matches a number in the list
If a number matches, change the value to an X
'''
for i, item in enumerate(bingo_card):
if item == number:
if number < 10:
bingo_card[i] = "X"
else:
bingo_card[i] = "XX"
def remaining_selections():
'''
Check the bingo_card list and if any values
are not X or XX return True (indicating that
there are remaining selections)
'''
integers_exist = False
for item in bingo_card:
if item != "X" or item != "XX":
integers_exist = True
return integers_exist
# Bingo Card List
bingo_card = [7,26,40,58,73,14,22,34,55,68]
# Draw Bingo Card to Terminal
draw_bingo_card()
while True:
try:
user_input = int(input("Please enter a number between 1 and 80 inclusive: "))
#####################
# DEBUGING STATEMENT
if user_input == 0:
print(bingo_card)
#####################
# Check to see if user has entered a valid integer range
if user_input < 1 or user_input > 80:
print("ERROR: Numbers betwen 1 and 80 are only valid")
continue
else:
remove_number(user_input)
draw_bingo_card()
if remaining_selections():
continue
else:
print(
"\n",
"***********\n",
"* BINGO!! *\n",
"***********\n"
)
break
except:
# User has entered an invalid selection
print("ERROR: Invalid selection. Please choose an INTEGER VALUE between 1 and 80 inclusive")
continue
def remaining_selections():
'''
Check the bingo_card list and if any values
are not X or XX return True (indicating that
there are remaining selections)
'''
integers_exist = False
for item in bingo_card:
if item != "X" and item != "XX": # it should be `and` instead of `or`
integers_exist = True
return integers_exist
you could simplify it even more with:
if item not in ["X", "XX"]:
...
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()
So I'm new to python and I'm writing a program that accepts a phone number in the format XXX-XXX-XXXX and changes any letters to their corresponding numbers. I need to check the entry and make sure it's in the correct format, and if its not, allow it to be reentered. I'm having a hard time getting it to prompt me for a new number, and even when that works sometimes, it will still translate the original, wrong phone number.
This is my code so far:
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return False
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return False
return True
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
.....etc this part isn't important
You probably want to use a while loop to force the user to input a valid number. Something like:
def main():
phone_number = ""
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translateNumber(phone_number)
(You may need to replace input with raw_input if you're using Python 2.7,)
Here is a full, working solution.
import re
from string import maketrans
phone_match = re.compile("^(\w{3}-\w{3}-\w{4})$")
def validPhone(number):
match = phone_match.match(number)
if match:
return match.groups(0)[0]
return None
phone_number = ''
while not validPhone(phone_number):
phone_number = raw_input("Give me your digits!: ")
phone_in = "abcdefghijklmnopqrstuvwxyz"
phone_out = "22233344455566677778889999"
transtab = maketrans(phone_in, phone_out)
print phone_number.lower().translate(transtab)
Examples:
Give me your digits!: 949-POO-PTOO
949-766-7866
Give me your digits!: 555-HOT-KARL
555-468-5275
I'm trying to find a way to fix this syntax error. I can't seem to find it to make the program run correctly.
This is my code below
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def error(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
AND the fixed is ...
digits = 0
wrong = 0
test = raw_input("Please enter a 4 digit integer:")
def start(test):
if test.isdigit():
if wrong(test)==True:
print 'Invalid input. Four integers must be entered.'
else:
numbers = []
for a in test:
digits.append(a)
a=calc(int(digits[0]))
b=calc(int(digits[1]))
c=calc(int(digits[2]))
d=calc(int(digits[3]))
code = str(c)+str(d)+str(a)+str(b)
print 'The encrypted integer is:',code
else:
print 'You input wrong. Use numbers only.'
def calc(num):
num+=7
num%=10
return num
def wrong(test):
if len(test)<4 or len(test)>4:
return True
else:
return False
start(test)
You've called a function named wrong() but defined a function named error(). Is that the problem you're seeing?
Don't you mean if error(test)? 'wrong' is not a function.