Strings formatting in Python - python-2.7

I have to write a program in python that prompts for a phone number of 10 digits and two dashes,with dashes after the area code and next three numbers.Also to diplay if the phone number is valid format or not

I've got a short program here which does what you need.
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
x = validNumber(phone_number)
print x
def validNumber(phone_number):
for j,k in enumerate(phone_number):
if j in [3,7]:
if k != '-':
phone_number=input('Please enter a valid phone number: ')
return phone_number
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return phone_number
return phone_number
It will continually ask the user to put in the write one, until he does.

Related

user_input() = input("Please enter a number: ") ^ SyntaxError: cannot assign to function call

Ask the user to enter a number and check if the input is 'POSITIVE', 'ZERO', 'NEGATIVE'
def is_positive():
# input() returns str
user_input() = input("Please enter a number: ")
# cast input into int -> int()
n = int(user_input)
# check conditions
if n > 0:
print("POSITIVE")
elif n == 0:
print("ZERO")
else:
print("NEGATIVE")
Close just change the user input variable name to have no parentheses like so. The parentheses are meant for when you are calling a function which is why an error was raised.
user_input = input("Please enter a number: ")

why does the while loop not work?

I'm creating a program that takes in the users grade(A-F), health(0-100) and economic output(0-100). I need a while loop for when the user inputs a value wrong e.g A for health. why does the loop keep repeating? how do I do this for the grade as well?
name = raw_input(' Enter your name: ')
grade = raw_input(' Enter your grade: ')
string_two = raw_input(' Enter your economic out put: ')
while string_two not in range (0,100):
print 'please enter a value between 0 and 100.'
string_two = raw_input(' Enter your economic out put: ')
string_one = raw_input(' Enter your health: ')
while string_one not in range (0,100):
print 'please enter a value between 0 and 100.'
string_one = raw_input(' Enter your health: ')
health == int(string_one)
economic_output == int(string_two)
if economic_output > 85:
print name + ' you are exceptional! Welcome aboard!'
elif grade == 'A':
print name + ' you are exceptional! Welcome aboard!'
elif economic_output > 60:
if health > 60:
if grade == 'B' or 'C':
print 'Congatulations ' + name +'!' + ' Come aboard!'
else:
print 'Sorry, ' + name + ' but you dont meet the criteria and cammot be permitted to board. '
The while loop keeps repeating because raw_input always returns a string object, regardless if you typed digits only or something else. string_two not in range (0,100) is always true because a string cannot be in any range of ints.
So what you can do. If I were you, I would define a function which would ask the user to enter something in a while loop until his input satisfies some pattern (just as you are trying to do in your code) and convert it to a specific type if necessary. There is a very useful tool to check a string for matching some pattern, it is called regular expressions (RE).
import re
def inputAndValidate(prompt, pattern, convertFunc=str):
result = raw_input(prompt)
while re.match(pattern, result) is None:
print 'Input pattern is "' + pattern + '". Please enter a string matching to it.'
result = raw_input(prompt)
return convertFunc(result)
Putting a piece of code being used several times to a function is a good practice. So here I defined a function called inputAndValidate with 2 mandatory parameters - a prompt to be displayed for user to let him understand what do you want from him, and the pattern to check his input. The third parameter is optional - it's a function which will be applied to the user input. By default, it's str, a function converting something to a string. User input is already a string, so this function will do nothing, but if we need an int, we'll pass int as the third parameter and get an int from the inputAndValidate function, and so on.
re.match(pattern, string) returns a match object if the string did match the pattern, and None if it didn't. See official re documentation for more information.
Usage of the function
name = inputAndValidate('Enter your name: ', r'.+')
# This pattern means any string except empty one. Thus we ensure user will not enter an empty name.
grade = inputAndValidate('Enter your grade (A-F): ', r'[A-F]')
# This pattern means a string containing only one symbol in the A-F range (in the ASCII table).
economic_output = inputAndValidate('Enter your economic output (0-100): ', r'\d{1,3}', int)
# This pattern means a string containing from one to three digits. `int` passed to the third parameter means the result will be an int.
health = inputAndValidate('Enter your health (0-100): ', r'\d{1,3}', int)
# Same as the previous one.
re module documentation also contains information about the regular expressions language, it can help you understand the patterns I used.

Fraction Value Operations in Python 2.7

I want to make a program where fraction values can be operated mathematically.
I've made a code but it show me an error.
TypeError: both arguments should be Rational instances.
print "We'll ask you for two fraction values."
print "After taking values from you, we'll use python built in operaters to make it happen."
from fractions import *
value_1_one = raw_input("Please enter 1st value : ")
value_1_two = raw_input("Please enter 1st two value : ")
value_2_one = raw_input("Please enter 2nd one value.")
value_2_two = raw_input("Please enter 2nd two value.")
vaule_1 = Fraction(value_1_one, value_1_two)
value_2 = Fraction(value_2_one, value_2_two)
print "We have %i and %i as values." % (value_one, value_two)
print "What kind of operation you would like to make."
print "Like Add, Sub, Multi, Devide"
op_kind = raw_input(">>>")
if "Add" in op_kind:
print (value_1 + value_2)
elif "Sub" in op_kind:
print (value_1 - value_2)
elif "Multi" in op_kind:
print (value_1 * value_2)
elif "Devide" in op_kind:
print (value_1 / value_2)
else:
print "Ask Mr. Ramanuj for further details."

Input validation python 2.7.13

I am trying to validate input that is going into a list. The input needs to be an integer. How I have it works if I input an integer or a single letter. but if I enter something like 'qw' the program crashes. What can I do to better validate the input? Here is my code:
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = raw_input("Enter the number of pints donated: ")
check = isinstance(pints[counter], int)
while check == False:
print "Please enter an integer!"
pints[counter] = input("Enter the number of pints donated: ")
counter = counter + 1
As written, check will always evaluate to False, because raw_input() only returns a string, never an integer. Then you'll get stuck in an infinite while loop, because you don't update check in it.
Instead of isinstance, use the string isdigit() method.
check = pints[counter].isdigit()
You'll also need to re-evaluate check inside the loop. But really, you don't need check at all.
pints[counter] = raw_input("Enter the number of pints donated: ")
while not pints[counter].isdigit():
print "Please enter an integer!"
pints[counter] = raw_input("Enter the number of pints donated: ")
I suspect you also want to convert pints[counter] to an int once you have a suitable input.
You're using the LBYL method (Look Before You Leap). You can also use the EAFP (Easier to Ask Forgiveness than Permission) method by just trying to convert the input to an int and catching the exception if the input is bad:
while True:
try:
pints[counter] = int(raw_input("Enter the number of pints donated: "))
break
except ValueError:
print "Please enter an integer!"

Pycharm issuing an error

This is the code in question:
#i/p from user
print "enter your number"
a=sys.stdin.readline()
if(a==6):
print('entered a 6!')
else:
print('you did not enter a 6')
If I enter 6, it is supposed to return entered a 6!,but it is returning you did not enter a 6.
Why is this happening?
You should use:
a = int(sys.stdin.readline())
or
a = int(raw_input())
Your code is reading the input as a string, and you are comparing it to an integer. You need to convert the input for a to an int before making the comparison.