Factorial of a given number using sequential program - python-3.x

I am new to this python coding.So,please can someone find what is the problem with this code.
def factorial(n):
sum=1
for i in range(1..n+1):
sum=sum*i
print(sum)
return sum
v=int(input("enter the number:"))
factorial(v)
the error i get:
enter the number:4
Traceback (most recent call last):
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module>
factorial(v)
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial
for i in range(1..n+1):
AttributeError: 'float' object has no attribute 'n'

There are two ways you can write your program. To reformat your code so that it is in good form, you might organize your program like so:
def main():
variable = int(input('Enter the number: '))
print(factorial(variable))
def factorial(number):
total = 1
for integer in range(1, number + 1):
total *= integer
return total
if __name__ == '__main__':
main()
If instead you are trying to accomplish the same thing using the least amount of code, the following two lines will do the exact same thing for you:
import math
print(math.factorial(int(input('Enter the number: '))))

Related

Pass an array as command line argument to the script

I'd like to experiment codes from command line, so import argv form sys.
from sys import argv
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2 # round down if not an even
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
def main():
script, array, item = argv
binary_search(array, item)
When run it on the command line:
$ python3 binary_search.py [1, 2, 3] 8
Traceback (most recent call last): File "binary_search.py", line 94, in <module>
main() File "binary_search.py", line 89, in main
script, array, item = argvValueError: too many values to unpack (expected 3)
I tested and found that arguments passed from command line are treated as str by argv.
How can pass an array as argument?
There are a couple different ways you can do this...
using re
Using regular expressions may be one of the easiest ways of handling this.
from sys import argv
import re
def binary_search(array, item):
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2 # round down if not an even
guess = array[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
def main():
array = re.findall(r"[\w]+", argv[1])
array = [int(i) for i in array]
item = int(argv[2])
binary_search(array,item)
if __name__== "__main__":
main()
using exec()
You can also use exec() which may be more risky and complicated. Here's a simple example:
from sys import argv
command = 'mylist = {0}'.format(argv[1])
exec(command)
for item in mylist:
print(item)
example output:
C:\path>py foo.py [1,2,3]
1
2
3
The arguments on the command line are strings, they're not parsed like literals in the program.
argv construct the strings automatically to a list from command line arguments (as separated by spaces), in short,
sys.argv is a list.
Additionally, module argparse helps
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

I/O operation closed on file in python

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

Getting error "can't multiply sequence by non-int of type 'float'"?

Here in my program, I have given employee pay in string and I am multiplying that amount with int.
Getting an error:
TypeError: can't multiply sequence by non-int of type 'float'
Please hep me out in debugging this.
class Employee:
raise_amt=1.2 # class variable
def __init__(self,first,last,pay):
self.first=first
self.last = last # instance variables
self.pay = pay
self.email = first+"."+last+"#company.com"
def fullname(self):
return '{}{}'.format(self.first,self.last)
def apply_raise(self):
self.pay= int(self.pay * self.raise_amt)
#classmethod # alter the raise amt
def set_raise_amt(cls,amount):
cls.raise_amt=amount
#classmethod
def from_string(cls,emp_str):
first,last,pay= emp_str.split('-')
return cls(first,last,pay)
emp_str_1='Nanda-kishor-90000' #values are in string
new_emp_1=Employee.from_string(emp_str_1)
Employee.set_raise_amt(2.2)
print(new_emp_1.raise_amt)
print(new_emp_1.pay)
new_emp_1.apply_raise()
print('after raise:',new_emp_1.pay)
Output:
Traceback (most recent call last):
File "C:/Users/nanda.v/PycharmProjects/Python basics/practice continue and break statements.py", line 39, in <module>
new_emp_1.apply_raise()
2.2
File "C:/Users/nanda.v/PycharmProjects/Python basics/practice continue and break statements.py", line 19, in apply_raise
self.pay= int(self.pay * self.raise_amt)
90000
TypeError: can't multiply sequence by non-int of type 'float'
Python does not automatically convert strings to numbers. If you want it to be a float or an integer, you need to say so. Python doesn't always have a problem with multiplying strings, though. Multiplying a string just repeats it:
>>> my_string = 'blah'
>>> my_string * 2
'blahblah'
The problem in your code is that self.raise_amt is a float. It doesn't make sense to repeat a string a decimal number of times, so you get an error.
What you need is to convert pay to a float when you get it. That is simply: float(pay) in your __init__:
self.pay = float(pay)
This will error if the pay argument is not a valid string, but that should be expected.
The problem is that your pay variable is still a string when creating your class with from_string. Consider changing your constructor:
def __init__(self,first,last,pay):
self.first=first
self.last = last # instance variables
self.pay = int(pay)

Python 3: Checking for the length and data type. & Error Fix

I am having some problems with my project:
With the code I currently have, I am getting an error:
Traceback (most recent call last):
File "\Username\Folder\Folder2\design2.py", line 13, in <module>
elif numberplate3.isaplha():
AttributeError: 'str' object has no attribute 'isaplha'
Here is the code:
while True:
import time
numberplate1 = str(input("Enter in the first 2 letters of the numberplate"))
if numberplate1.isalpha():
print("Verification 1 Success")
numberplate2 = str(input("Enter in the next 2 chars of the numberplate"))
if numberplate2.isdigit():
print("Verification 2 Success")
numberplate3 = str(input("Enter the last 3 digits of the numberplate"))
if numberplate3.isdigit():
print("Verification 3 Fail")
break
elif numberplate3.isaplha():
print("Verification Passed")
start
elif numberplate2.isalpha():
print("Verification 2 Failed")
break
elif numberplate1.isdigit():
print("Return to the start")
break
start = time.time()
inp = input("Please press enter when car has left monitoring area\n>")
end = time.time()
print("Car took {:.2f} seconds ".format(end-start))
print("Car travelled at {:.2f} m/s. ".format(200/(end-start)))
The program will check the format of a numberplate, but I would also like for it to check for the length too. (It checks to see if it has a letter, number etc, but it needs to check for the length on each check)
If possible, a program that checks for the numberplate format would really help.
Checking for LETTER-LETTER-NUMBER-NUMBER LETTER-LETTER-LETTER (AB12 CDE) If not, I am fine with help on my current program
Thanks
Your first problem is just a typo: You misspelled 'isaplha'; it should be 'isalpha'.
For your other question: You can make your program a whole lot simpler by using a regular expression for matching the number plate, like this:
import re
while True:
numberplate = input("Enter the numberplate: ").lower()
if re.match("[a-z]{2}[0-9]{2}[a-z]{3}", numberplate):
print("Verification Success")
break
else:
print("Verification Failed")
Here, the regular expression "[a-z]{2}[0-9]{2}[a-z]{3}" means "two letters, two digits, three letters".

Why won't it write to the file?

So I have the code:
def logdata(x, y):
try:
f = open('multlog.txt', 'a')
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error, you tried to multiply by something that wasn't a number")
raise
finally:
f.close()
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(int(fn), int(sn))
And what I want it to do, is when it reaches a value error, for it to write to the file,"Error, you tried to multiply by something that wasn't a number". But, if the file reaches a value error if the user inputs a letter, say "j",ValueError: invalid literal for int() with base 10: 'j', it doesn't write to the file!
At least two problems:
The file is not open for writing (or appending) in the except block.
As #DSM points out in a comment, the ValueError is being raised when you call int()
I would rewrite to something like the below example.
If you use the with statement then you can do without the finally block.
def logdata(x, y):
with open('multlog.txt', 'a') as f:
try:
x = int(x); y = int(y)
f.write("{0:g} * {1:g} = {2:g}\n".format(x,y, (x*y)))
except ValueError:
f.write("Error")
print("This is a test program, it logs data in a text file, 'multlog.txt'")
fn = input("Enter the first number you'd like to multiply by: ")
sn = input("Enter the second number you'd like to multiply by: ")
logdata(fn, sn)

Resources