Validating user input program syntax eror - python-3.x

How does one answer this question.
1. A dramatic society wants to record the number of tickets sold for each of their four performances. Ask the user to enter the number of tickets sold for each performance. The number must be between 0 and 120. Print an error message if an invalid number is entered and ask them to re-enter until they enter a valid number. Print the total number of tickets sold and the average attendance for a performance.
import re
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = re.match("[0-120]",p)
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """,average)
My python book didn't really explain the correct syntax for the re module and the try except else function. Can someone point out if there is anything wrong with the code. This was my first go at validating user input.

You cannot use regular expression to see whether a number is between a certain range, and even if you did, it would be silly considering how easy it is to check if a number is between numbers in Python:
valid = 0 < p < 120
Here is your code after the fix:
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = 0 < p < 120
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """, average)
More on: Expressions in Python 3

Related

Having an issue relating to finding an Armstrong number from a list in Python [duplicate]

n=int(input("Enter a Number: "))
x=0
y=0
z=0
while(n>0):
x=n%10
y=x**3
z=z+y
n=n//10
print (z)
#The z here is the same value which I enter, yet it doesn't work.
#If I enter 407 as n, z becomes (4^3)+(0^3)+(7^3) which is 407
if (z==n):
#But even when 407==407, it just wont print the bottom statement
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
#it prints that it isn't an Armstrong number
After the while loop, n already became 4//10 which is 0, so it'll never equal z which is 407.
You will want to keep a copy of the original input for comparison.
As a general advice, use a debugger or at least print() your objects to see where the assignments went wrong.
Without using any built-in method
Armstrong number is 371 because 3**3 + 7**3 + 1**3 = 371. according this rule 123 is not Armstrong number because 1**3 + 2**3 + 3**3 is not equal to 123
def count_digit(n):
count = 0
while n > 0:
count += 1
n //= 10
return count
def is_armstrong(n):
given = n
result = 0
digit = count_digit(n)
while n > 0:
reminder = n % 10
result += reminder ** digit
n //= 10
return given == result
is_armstrong(371)
>> True
is_armstrong(123)
>> False
You can take in your initial number as a string so we can more easily convert it to a list. We can then map to create that list of ints. After we can use list comprehension to raise all int in that list to the power that is the len of our list. If the sum of this list equals our input, then we have an Armstrong number.
n = input('Enter a number: ')
nums = list(map(int, n))
raised = [i**len(nums) for i in nums]
if sum(raised) == int(n):
print('The number is Armstrong')
else:
print('The number is not Armstrong')
Expanded list comprehension:
raised = []
for i in nums:
i = i**len(nums)
raised.append(i)
print(raised)
Alternate for map:
nums = []
for i in n:
i = int(i)
nums.append(int(i))
I corrected your code:
n = int(input("Enter a Number: "))
x = 0
y = 0
z = 0
num = n
while n > 0:
x = n % 10
y = x**len(str(num))
z = z+y
n = n//10
print(z)
if (z == num):
print ("The number is Armstrong")
else:
print ("The number isn't Armstrong")
But you can still do it in many ways better. Look at the code of vash_the_stampede and ggorlen.
Or:
def isArmstrong(n):
print(f"{n} is {'' if int(n) == sum(int(i)**len(n) for i in n) else 'not '}an Armstrong number")
isArmstrong(input("Please enter a number: "))
Definition: a number n is an Armstrong number if the sum of each digit in n taken to the power of the total digits in n is equal to n.
It's important to keep track of the original number n, because it'll be needed to compare against the result of z (your variable representing the sum). Since you're mutating n in your while loop, there's no grounds for comparison against your original input, so if (z==n): isn't working like you expect. Save n in another variable, say, original, before reducing it to 0.
Additionally, your code has arbitrarily chosen 3 as the number of digits in the number. For your function to work correctly for any number, you'll need a way to count its digits. One way is to convert the number to a string and take the length.
I strongly recommend using descriptive variable names which reduces the chance of confusing yourself and others. It's only apparent that z represents your sum and x your remainder by virtue of reading through the code. If the code was any longer or more complex, it could be a nightmare to make sense of.
Lastly, Python is not a particularly flexible language from a style standpoint. I recommend adhering to the style guide as best as possible to keep your code readable.
Here's a working example:
def armstrong(n):
total = 0
original = n
digits = len(str(n))
while n > 0:
total += (n % 10) ** digits
n //= 10
return total == original
if __name__ == "__main__":
while 1:
print(armstrong(int(input("Enter a Number: "))))
Output:
Enter a Number: 407
True
Enter a Number: 1234
False
Enter a Number: 23
False
Enter a Number: 8
True
Enter a Number: 371
True
Try it!
total=0
def Armstrong(n):
m=list(n)
global total
for i in m:
total+=pow(int(i),len(n))
if total==int(n):
print ("it is Armstrong number")
else:
print("it is not Armstrong number")
Armstrong(input("enter your number"))
print(total)

How would I integrate input() within iterative loop?

I'm a beginner at python and wanted to have a crack at my first personal project which is a score calculator for a student's subjects. I wanted to run a for loop that asks the user to input their scores for each of the individual subjects through an input() within a for loop. However, it would only take a singular string argument.
scores = {}
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(0, years):
scores = input("Score for subject?",x)
total += int(scores)
Any help would be great, thanks!
If you wanted to keep track of scores by subject and find total score then...
subjects = dict( Math = 0, English = 0, Science = 0, History = 0 )
scores = dict()
total = 0
for sub in subjects.keys():
score = input( f"Score for {sub}? >" )
if score:
total += int( score )
scores[sub] = score
print( total )
for sub,tot in scores.items():
if tot > 0:
print( sub, tot )
The variable x never defined and used, just remove it may solve your problem.
scores first defined as a dict, then you re-define it without using it.Remove it make code more clear.
code:
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(years):
scores = input("Score for subject?")
total += int(scores)
print(total)
result:
How subjects have you completed? 5
Score for subject?1
Score for subject?2
Score for subject?3
Score for subject?4
Score for subject?5
15
In the code sample:
x is an undefined variable.
scores = {} the 'scores' dictionary is useless as later you redefine it as a string.
Just removing the ,x in line 5 will make the code execute properly.
>>> total = 0
>>> for i in range(int(input("How many subjects have you completed? "))):
... total += int(input("Score for subject? "))
...
How many subjects have you completed? 3
Score for subject? 70
Score for subject? 80
Score for subject? 90
>>> total
240

Find average of given numbers in input

I've to create a program that computes the average of a collection of values entered by the user. The user will enter 0 as a sentinel value to indicate that no further values will be provided. The program should display an appropriate error message if the first value entered by the user is 0.
Note: Number of inputs by the user can vary. Also, 0 marks the end of the
input it should not be included in the average
x = int(input("Enter Values\n"))
num = 1
count = 0
sum = 0.0
if x == 0:
print("Program exits")
exit()
while (x>0):
sum += num
count += 1
avg = (sum/(count-1))
print("Average: {}".format(avg))
You were not taking input inside while loop. You were taking input on the first line for once. So your program was not taking input repeatedly.
You may be looking for this -
sum = 0.0
count = 0
while(1):
x=int(input("Enter Values: "))
if x == 0:
print("End of input.")
break;
sum+=x;
count+=1;
if count == 0:
print("No input given")
else:
avg = sum/count;
print("Average is - ",avg)
Your code does not work because int function expect only one number.
If you insert the numbers one by one, the following code works:
num = int(input("Enter a value: "))
count = 0
sum = 0.0
if num <= 0:
print("Program exits")
exit()
while (num>=0):
sum += num
count += 1
num = int(input("Enter a value: "))
avg = (sum/count)
print(f"Average: {avg}")

Calculate phone bill(python)

Trying to return to data question is user enters incorrect number.
I need need to know how to return to the question again if incorrect number is entered
import math
p=float(input('Please enter the price of the phone: '))
print('')
data=int(input('Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '))
tax=p*.0925
Total=p+tax
print('')
print ('If your phone cost',p,',the after tax total in Tennessee is',round(Total,2))
print('')
if data==1:
datap=30
print('The price of one gig is $30.')
elif data==3:
datap=45
print('The price of three gig is $45.')
elif data==6:
datap=60
print('The price of six gigs is $60.')
else:
print(data, 'Is not an option.')
#I need need to know how to return to the question again if incorrect number is entered
pmt=Total/24
bill=(datap+20)*1.13
total_bill=bill+pmt
print('')
print('With the phone payments over 24 months of $',round(pmt,2),'and data at $',datap,
'a month and line access of $20. Your total cost after tax is $',round(total_bill,2))
You should enter an infinite loop and only break out of it when the user has entered a valid input.
import math
costmap = {1: 30, 3: 45, 6: 60}
price = float(input('Please enter the price of the phone: '))
datamsg = 'Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: '
while True:
try:
data = int(input(datamsg))
except ValueError:
print('must input a number')
continue
tax = price * .0925
total = price + tax
print('If your phone cost {}, the after tax total in Tennessee is {}'
.format(price, round(total, 2)))
try:
datap = costmap[data]
print('The price of one gig is ${}.'.format(datap))
break
except KeyError:
print('{} is not an option try again.'.format(data))
pmt = total / 24
bill = (datap + 20) * 1.13
total_bill = bill + pmt
print('With the phone payments over 24 months of ${}'.format(round(pmt, 2)))
print('and data at ${} a month and line access of $20.'.format(datap))
print('Your total cost after tax is ${}'.format(round(total_bill, 2)))
You can also simplify your if/else clause by defining a dict to map inputs to cost values. If the value does not exist it throws an exception which you can catch, issue an error and go around the loop again.
Finally I'd recommend you try running your code through a pep-8 checker such as http://pep8online.com/. It will teach you how to format your code to make it easier to read. At present your code is more difficult to read than it could be.

Python game - players take turns to subtract from a number

Here is the scenario:
Ask the user for a number which must be between 20 and 30. The user and the computer take it in turns to subtract 1, 2 or 3 from the current value. The last player to subtract a value loses.
Here's what I have so far
import random
while True:
count = int(input("Enter a number between 20 and 30"))
if count < 20 or count > 30:
print("That number is not in range")
else:
print("\nLet's play")
print("\nSubtract 1, 2, or 3 from", count)
# Player moves
def playermove():
while True:
number = int(input("\nWhat number would you like to subtract"))
if number > 1 and number <4:
print("\nyou subtracted", number, "there is", count-number, "left")
print("\nMy turn!")
break
else:
print("\nplease enter 1,2 or 3")
def computermove():
computernum = random.randint(1,3)
print("\nI subtracted", computernum, "there is", count-computernum, "left")
print("\nMake your move")
Get the initial count from the user something like this:
def get_count():
count = 0
while count < 20 or count > 30:
count = int(input("Enter a number between 20 and 30"))
if count < 20 or count > 30:
print("That number is not in range")
else:
return count
count = get_count()
Next, start playing the game.

Resources