Syntax error in python, need help for a project - python

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.

Related

Python script not producing output

I have been tasked with reading values inputted by a user(using a while loop) to then store them in a list/array whilst using try: except: to determine if a given input is invalid. In continuation, if the user inputs "done" as a value it will break the loop and print() the total, sum, and average of all the imputed values.
I have gotten this snippet so far:
class Input:
def __init__(self, number_input_value, total_to_be_calculated, main_value):
self.number_input_value = 0
self.total_to_be_calculated = 0.0
self.main_value = input('Enter A Number: ')
self.number_input_value1 = float(self.main_value)
def loop_get_inputs(self):
while True:
self.main_value
if self.main_value == 'done':
break
try :
self.number_input_value1
except :
print('INVAL["VAL"]')
continue
self.number_input_value = self.number_input_value1
self.total_to_be_calculated = self.total_to_be_calculated + self.number_input_value1
print ("Finished successfully!")
print (
self.total_to_be_calculated,
self.number_input_value,
self.total_to_be_calculated/self.number_input_value
)
if __name__ in '__main__':
Input
I have no clue what's wrong, because when it runs it outputs nothing.
Output:
>>>
You need create an instance of the class 'Input' and call the method:
##(self, number_input_value, total_to_be_calculated, main_value)
inp = Input(100, 1000, 10)
#call the method
inp.loop_get_inputs()
Basically:
1 - You have to initialize your class/object before using it.
2 - Having code on the construct is not recommend. You should call a public method of the class to start the "process".
3 - That try-except wasn't doing much. You can, for example, surround the string (from input()) cast to float and print INVALID if the input can't be casted.
4 - You can use += to simplify a = a + b
5 - lower() will convert user input to lowercase, meaning that DONE, done and DoNe (etc) will be considered as "quit" input.
Does this make sense?
class Input:
def __init__(self):
self.number_inputs = 0
self.total = 0.0
def run(self):
self.__get_user_values()
print(f"total: '{self.total}'")
print(f"number_inputs: '{self.number_inputs}'")
print(f"average: '{self.total / self.number_inputs}'")
def __get_user_values(self):
while True:
value = input('Enter A Number: ')
if value.lower() == 'done':
break
if self.__is_valid_input(value):
self.total += float(value)
self.number_inputs += 1
def __is_valid_input(self, value) -> bool:
try:
float(value)
return True
except ValueError:
print('INVAL["VAL"]')
return False
if __name__ in '__main__':
input_wrapper = Input()
input_wrapper.run()

True and false phone numbers in Python

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.

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()

Python - Input Validation

I'm looking to create code which requires an integer greater than 2 to be input by a user before continuing. I'm using python 3.3. Here's what I have so far:
def is_integer(x):
try:
int(x)
return False
except ValueError:
print('Please enter an integer above 2')
return True
maximum_number_input = input("Maximum Number: ")
while is_integer(maximum_number_input):
maximum_number_input = input("Maximum Number: ")
print('You have successfully entered a valid number')
What I'm not sure about is how best to put in the condition that the integer must be greater than 2. I've only just started learning python but want to get into good habits.
This should do the job:
def valid_user_input(x):
try:
return int(x) > 2
except ValueError:
return False
maximum_number_input = input("Maximum Number: ")
while valid_user_input(maximum_number_input):
maximum_number_input = input("Maximum Number: ")
print("You have successfully entered a valid number")
Or even shorter:
def valid_user_input():
try:
return int(input("Maximum Number: ")) > 2
except ValueError:
return False
while valid_user_input():
print('You have successfully entered a valid number')
My take:
from itertools import dropwhile
from numbers import Integral
from functools import partial
from ast import literal_eval
def value_if_type(obj, of_type=(Integral,)):
try:
value = literal_eval(obj)
if isinstance(value, of_type):
return value
except ValueError:
return None
inputs = map(partial(value_if_type), iter(lambda: input('Input int > 2'), object()))
gt2 = next(dropwhile(lambda L: L <= 2, inputs))
def take_user_in():
try:
return int(raw_input("Enter a value greater than 2 -> ")) # Taking user input and converting to string
except ValueError as e: # Catching the exception, that possibly, a inconvertible string could be given
print "Please enter a number as" + str(e) + " as a number"
return None
if __name__ == '__main__': # Somethign akin to having a main function in Python
# Structure like a do-whole loop
# func()
# while()
# func()
var = take_user_in() # Taking user data
while not isinstance(var, int) or var < 2: # Making sure that data is an int and more than 2
var = take_user_in() # Taking user input again for invalid input
print "Thank you" # Success
def check_value(some_value):
try:
y = int(some_value)
except ValueError:
return False
return y > 2
Hope this helps
import str
def validate(s):
return str.isdigit(s) and int(s) > 2
str.isdidig() will eliminate all strings containing non-integers, floats ('.') and negatives ('-') (which are less than 2)
int(user_input) confirms that it's an integer greater than 2
returns True if both are True
This verifies that the input is an integer, but does reject values that look like integers (like 3.0):
def is_valid(x):
return isinstance(x,int) and x > 2
x = 0
while not is_valid(x):
# In Python 2.x, use raw_input() instead of input()
x = input("Please enter an integer greater than 2: ")
try:
x = int(x)
except ValueError:
continue
The problem with using the int() built-in shown in other answers is that it will convert float and booleans to integers, so it's not really a check that your argument was an integer.
It's tempting to use the built-in isinstance(value, int) method on its own, but unfortunately, it will return True if passed a boolean. So here's my short and sweet Python 3.7 solution if you want strict type checking:
def is_integer(value):
if isinstance(value, bool):
return False
else:
return isinstance(value, int)
Results:
is_integer(True) --> False
is_integer(False) --> False
is_integer(0.0) --> False
is_integer(0) --> True
is_integer((12)) --> True
is_integer((12,)) --> False
is_integer([0]) --> False
etc...

Checking whether user has input a number or not?

I made a simple script which finds the Square root of a number. The user inputs a number and it finds the square root and shows the result. I want it to check whether the input was a number or not. If it was a number it'll continue else it'll show a message, and reset.
I tried using:
while num != int(x):
print "That is not a valid number"
return self.page()
But that only shows an error.
Can someone help me out on this?
Here is the code:
import math
import sys
class SqRoot(object):
def __init__(self):
super(SqRoot, self).__init__()
self.page()
def page(self):
z = 'Enter a number to find its square root: '
num = int(raw_input(z))
sqroot = math.sqrt(num)
print 'The square root of \'%s\' is \'%s\'' % (num, sqroot)
choose = raw_input('To use again press Y, to quit Press N: ')
if choose == 'Y' or choose == 'y':
return self.page()
elif choose == 'N' or choose == 'n':
sys.exit(0)
print "SqRoot Finder v1.0"
print "Copyright(c) 2013 - Ahnaf Tahmid"
print "For non-commercial uses only."
print "--------------------------------"
def main():
app = SqRoot()
app()
if __name__ == '__main__':
main()
One of the python principles is EAFP:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false.
x = raw_input('Number?')
try:
x = float(x)
except ValueError:
print "This doesn't look like a number!"
If you don't want to use the ask forgiveness method, here is a simple function which should work on any valid float number.
def isnumber(s):
numberchars = ['0','1','2','3','4','5','6','7','8','9']
dotcount=0
for i in range(len(s)):
if (i==0 and s[i]=='-'):
pass
elif s[i]=='.' and dotcount==0:
dotcount+=1
elif s[i] not in numberchars:
return False
return True
Note: You can add base 16 easy by changing numberchars to:
numberchars = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']

Categories

Resources