Python 3 Caesar cipher, help please - python-3.x

hi im trying to create a Caesar cipher using Python 3, the question is in the text, chapter 5 question 7, I have this so far but i keep getting this error message when i try to run the program and cant figure out why.
program:
def main():
print("This program executes a Caesar cipher for a string")
word = input("Please enter word: ")
key = input("Please enter the number of positions in the alphabet you wish to apply: ")
message=""
for ch in word:
word= chr(ord(ch)+key)
newWord =(message + word)
print (newWord)
main()
Error:
Traceback (most recent call last):
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 14, in <module>
main()
File "/Users/krissinger/Documents/programing /my graphics/delete.py", line 10, in main
word= chr(ord(ch)+key)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

word= chr(ord(ch)+key)
ord(ch) gives the integer value for that chr. Adding it with a string gives a TypeError, since the + operator is used differently for integers and strings. If you want key to be an int, you must do:
key = int(input("....")
Then, you can add them together.

Related

AttributeError: 'builtin_function_or_method' object has no attribute 'writerow

i'm trying to edit only a specific set of columns of a row in a csv file for a school project but not having much luck, and am now running into the error when trying to see if using dictwriter will work as I need the last two columns im not wanting to be edited to still exist:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\C0027838_csc1034_project2_2021\main.py", line 104, in <module>
writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
AttributeError: 'builtin_function_or_method' object has no attribute 'writerow
Here's the section of code i'm trying to get working:
if choice == "4":
with open("mock_data.csv", newline='') as file:
reader = csv.DictReader(file)
client = list(reader)
editClient = int(input("Please enter the index number of the client you wish to edit: "))
print("Please enter the details for each of the following: ")
for i in range(len(existing_clients[0])):
newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ": ")
existing_clients[editClient][i] = newDetails
changes = input("Are you sure you'd like to make these changes? Enter Yes or No")
if changes == ("Yes"):
# Newline fixed the spacing issue I was having
with open("mock_data.csv", "w+", newline="") as file:
writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
writer.writeheader()
for line in client:
writer.writerow(line)
And an example of my csv file:
first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
Jens,Eldrid,Honorable,Male,13/11/2021,Research Associate,967.64,79.15
Enrichetta,Pinkerton,Honorable,Female,29/11/2021,Software Engineer I,1182.94,6.10
Merwyn,Abraham,Mrs,Male,23/05/2022,Associate Professor,1071.10,93.88
Cheers!
I've tried slicing but obviously that gets rid of the last two columns which i need for later in the program so if you can help me fix this or point me toward another method that would be great :)
cheers!

(Python 3) Program closes upon input

I created a Pig Latin translator. I run the program, it opens, I enter a word, and as soon as I hit 'enter' the program closes. Why is this?
userWord = input('Enter any word:')
pig = "ay"
if len(userWord) > 0 and userWord.isalpha():
word = userWord.lower()
first = word[0]
new = word[1:] + first + pig
print(new)
else:
print("INPUT INVALID")
Python does not interpret what you typed in as a string. You will need to put "" to denote it is a string.
For example:
Enter any word: blah
Traceback (most recent call last):
File "test.py", line 4, in <module>
userWord = input('Enter any word: ')
File "<string>", line 1, in <module>
NameError: name 'blah' is not defined
But if you put ""
Enter any word:"blah"
lahbay

Factorial of a given number using sequential program

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: '))))

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".

I can't convert my variable from integer to string

This is the code:
import time
import os
os.system("cls")
a=1
while True:
if a>512:
a=1
print (a + " kb")
if a<1024:
print (a + " bytes")
a *= 2
time.sleep(.5)
But it gives me this error:
> Traceback (most recent call last):
> File "Sequence1.py", line 10, in <module>
> print (a + " bytes")
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
If I changed it to a string then my if statements wouldn't work. Sorry if this question has been asked before. Thanks.
While you need a to be integer for you logic you need it as string just for presentational purposes. So convert it only when printing it. You have several ways to do that, as you certainly know. Some of them:
print('{0} bytes'.format(a))
print('%s bytes' % a)
print(str(a) + ' bytes')

Resources