Integer to letters with a loop - python

I'm trying to create a program on python that will take 3 integers and convert them into letter's using their ASCII but I'm not sure what is wrong with this program. Can you help me?
num = []
letter = []
x = 0
numx = 0
for x in range(0,3):
numx = int(input('Enter an integer'))
num.append(numx)
letter.append(str(chr(num[x]))
print(letter)

I think your issue is just that you only have two closing parens for three open parens in the third line of the loop. Making the change, your code seems to work for me.
Also, since you're doing the append inside the loop, there's no reason to use num[x] instead of numx directly. Unless you're using it for something else, you can get rid of num entirely. And your call to str is unnecessary.

To convert ASCII numbers into a string, you could do the following:
letters = []
for x in range(0,3):
numx = int(input('Enter an integer: '))
letters.append(str(chr(numx)))
print(''.join(letters))
For example:
Enter an integer: 65
Enter an integer: 66
Enter an integer: 67
ABC
letters is a list of the numbers converted to letters, and the join() is used to concatenate them all together (without adding anything between them).

Related

basic encryption in python using loop and if elif

I am trying to make a caesar cipher encryption program in python using loop and if/elif, but I my program returns unwanted results. There may be a little error in my programming logic and maybe someone wants to help me to fix it.
this input :
caesar
2
and should show an output:
ecguct
but my program show output : caesar #thats wrong
This my code I'm trying:
x = []
ch = ""
i = 0
x = input(" enter words : ")
y = int(input("enter number : "))
for i in range(len(x)):
i+1
ch = x[i]
if(ord(ch)>=ord('a') and ord(ch)<=ord('z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('z')):
(ord(ch)- ord('z')-ord('a')-1)
x[i]=ch
elif(ord(ch)>=ord('A') and ch<=ord('Z')):
chr(ord(ch)+y)
elif(ord(ch)>ord('Z')):
(ord(ch)- ord('Z')+ord('A')-1)
x[i]=ch
print(x)
I feel unsure about iteration that I made i+1 , and also x[i]=ch it's right syntax?. Also I use ord() to change value string to integer. I need your opinion to fix it.
You got several bugs in your code. First of all you have to turn your calculations to char again using the chr() function. Sometimes you do, sometimes you don't. Then you can't index strings - here x[i]=ch. Instead you have to assign your result to a new string using += operator or some other append method. At last your if and elif does not cover the overflows it should. In case you input a string with a letter y, z, Y or Z it will overflow. The if-questions covering those overflows need to be nested inside the top level if-elif which processes the different upper case and lower case letters.
There is also a minor bug within the overflow calculation where you use a - minus instead of a + plus operation.
Here is the slightly fixed version of your code:
x = input(" enter words : ")
y = int(input("enter number : "))
y = y % 26 # limit y to the amount of possible letters
result = ""
for ch in x:
if(ch>='a' and ch<='z'):
ch = chr(ord(ch)+y)
if(ch>'z'):
ch = chr(ord(ch)- ord('z')+ord('a')-1)
elif(ch>='A' and ch<='Z'):
ch = chr(ord(ch)+y)
if(ch>'Z'):
ch = chr(ord(ch)- ord('Z')+ord('A')-1)
result += ch
print("input:", x)
print("output:", result)
You also can iterate directly over the letters of a string like 'for ch in x' does without the need of extra indexing with x[i]. The ord(...) function is not required for comparison of characters.
Some further shrinking:
x = input(" enter words : ")
y = int(input("enter number : "))
result = "".join ( [ [ # encrypting a string by adding a number to all letters
c, chr((ord(c)-ord('Aa'[c.islower()])+y)%26+ord('Aa'[c.islower()]))
] [ c.isalpha() ] for c in x ] )
print("output:", result)
This code is harder to read and should cover some remarks on what it actually does. If you have some more code, shrinking might make it easier to understand because otherwise you have tons of files and modules within a project.

I write the code in python to count digits of a number but It doesn't work for some numbers

In order to count digits of a number I write this code in python:
a=int(input('number: '))
count=0
while a!=0:
a=a//10
count=count+1
print('number has ',count,'digits')
It works well for inputs like 13,1900,3222,.... But It give an error for numbers like: 3^21, 2^3,3*4,...
It say:
ValueError: invalid literal for int() with base 10: '3**21'
3**21 is integer input So why it gives this erroer,and How Should I fix this?
The int() constructor accepts string representation of ints, which 2**5 is not, this is an math operation, you may use eval to compute that. I've add an additionnal variable value to keep track of the initial value and print it at then end
value = eval(input('number: '))
a = value
count = 0
while a!=0:
a = a//10
count += 1
print(value, 'has', count, 'digits')
⚠️ CAREFULL eval is dangerous
You can try
a=input('number: ') # entered 3**21
if a.isalnum():
a = int(a)
else:
exec("a = {}".format(a))
count=0
while a!=0:
a=a//10
count=count+1
print('number has ',count,'digits')
Output
number has 11 digits
This code will cast a to int only if a contained only digits else it will execute python command to store the expiration that entered to expiration and not int.
Neither '3^21' nor '3**21' are integers. They are strings with Python expressions that would evaluate to integers if the Python interpreter evaluated them.
>>> 3^21
22
>>> 3**21
10460353203
The int builtin only accepts strings such as '100', '22' or '10460353203'.
(int also has a base argument that defaults to 2 and allows you to issue commands like int('AA', 16), but it still does not allow you do pass the kind of string-expressions you are trying to pass.)
You must eval() the expression first if you want an integer
eval('3**21')
# 10460353203
and to simply count digits (like digits number is string length) :
num_digits = len(str(eval('3**21')))
print(num_digits)
# 11
So your code could be :
a=input('number: ')
num_digits = len(str(eval(a)))
print('number has ',num_digits,'digits')

i'm doing a code but i don't see what i'm doing wrong. i keep getting this error 'ValueError: invalid literal for int() with base 10: '2a'

def EnterRLE():
Data=[]
AmountOfLines = int(input("How many lines of RLE compressed data do you want to enter? "))
if AmountOfLines >= 3:
Lines = 1
while Lines <= AmountOfLines:
Data.append(input("Please enter the compressed data one line at a time: "))
Lines=Lines+1
for index in range (0,AmountOfLines):
SubStr = Data[index]
index=0
for index in range (0,len(SubStr)):
number = int(SubStr[index:index+2])
character = SubStr[index+2]
print ("numberpart is: ", number)
print ("character is :", character)
print (number*character)
EnterRLE()
i'm doing a code but i don't see what i'm doing wrong.
What you are doing wrong is entering 2a when prompted by input("How many lines of RLE compressed data do you want to enter? ") and passing the entered string to int() without validation.
So, if I understand this correctly one line of your input is formatted like this:
[2 digit number][1 char][2 digit number][1 char] ...
One block consists of 3 characters, so you want your index to be incremented by 3 each round. To achieve that you can fix your for loop like this:
for index in range (0, len(SubStr), 3):
You haven't given enough information so I assume that you have always 1 digit followed by 1 character in the string.
If your string SubStr starts with '2a' and index is 0 then SubStr[index:index+2] will give you '2a' and that can't be converted to an integer.
If you have 2 digits followed by 1 character in the string you'll get another problem. If your string SubStr starts with '22a' and index is 1 then SubStr[index:index+2] will give you '2a' again. You will have to increase the step you use for traversing the string.
I rewrote the code to make it more pythonic while assuming that you have always 1 digit followed by 1 character in the string. A fix for 2 digits is easy.
def enter_rle():
amount_of_lines = int(
input("How many lines of RLE compressed data do you want to enter? "))
if amount_of_lines < 3:
return
data = []
for _ in range(amount_of_lines):
data.append(input("Please enter the compressed data one line at a time: "))
for line in data:
for index in range(0, len(line), 2):
number = int(line[index])
character = line[index + 1]
print(f'numberpart is: {number}')
print(f'character is : {character}')
print(character * number)
enter_rle()

Line 8: ValueError: invalid literal for int() with base 10: ' '

I'm a beginner programmer. I want to write a program that gives me the maximum product of all the products of 4-adjacent digits in an input number.
So, if the input is "12345678"
Possible selections are 1234, 2345,3456,4567,5678 and the largest product is 5*6*7*8.
My code:
number = str(input("Enter a number:"))
i = 0
L = []
while (i!=len(number)-3):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
print(L)
print(number)
print(max(L))
I need to apply this to a 1000-digited number. My code works for 8-digited input number and gave an answer for a 500-digited number.
But I tried it with a 600-digited number and it throws this error.
I understand ValueError is an error that appears when the argument given to a function call has correct type, but inappropriate value. There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
the error is for '' an empty string that cannot be converted to an integer. But I cannot understand where/why the empty string was formed.
I have read a few other answers of this Error type, but all involve code that use features of Python I am NOT familiar with and hence cannot understand. I'm just a beginner! So, please help!
And apologies for breaking any rules laid out with regards to question formation!
You've got a space there, not an empty string. Most likely, you just hit the space bar at the end of your input, and Python can't convert that to an integer. You can either just ensure that you don't leave a space at the end, or do some checking of your input (e.g., add a line number = number.strip() to remove any trailing whitespace).
Validate your input as numeric, and strip any whitespace:
number ='123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890'
def foo(number):
number = number.strip()
if number.isdigit():
i = 0
L = []
while (i in range(len(number)-3)):
a = int(number[i])
b = int(number[i+1])
c = int(number[i+2])
d = int(number[i+3])
product = a*b*c*d
L.append(product)
i = i+1
return max(L)
This functions should return a None if user has provided invalid input (e.g., "Alexander"), this should avoid the error you describe:
There are also examples of when the user gives a string "Alexander" as input in code Eg: int(input("Enter a number"))
You can also simplify this using a generator statement for a set of only the unique results:
def foo2(number):
number = number.strip()
if number.isdigit():
return max({int(number[i]) * int(number[i+1]) * int(number[i+2]) * int(number[i+3]) for i in range(len(number)-3)})

number/numbers to list by using input() [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 6 years ago.
Maybe this is a very basic question but i am a beginner in python and couldnt find any solution. i was writing a python script and got stuck because i cant use python lists effective. i want user to input (number or numbers) and store them in a python list as integers. for example user can input single number 1 or multiple numbers seperated by comma 1,2,3 and i want to save them to a list in integers.
i tried this ;
def inputnumber():
number =[]
num = input();
number.append(num)
number = map(int,number)
return (number)
def main():
x = inputnumber()
print x
for a single number there is no problem but if the the input is like 1,2,3 it gives an error:
Traceback (most recent call last):
File "test.py", line 26, in <module>
main()
File "test.py", line 21, in main
x = inputnumber()
File "test.py", line 16, in inputnumber
number = map(int,number)
TypeError: int() argument must be a string or a number, not 'tuple'
Also i have to take into account that user may input characters instead of numbers too. i have to filter this. if the user input a word a single char. i know that i must use try: except. but couldn't handle. i searched the stackoverflow and the internet but in the examples that i found the input wanted from user was like;
>>>[1,2,3]
i found something this Mark Byers's answer in stackoverflow but couldn't make it work
i use python 2.5 in windows.
Sorry for my English. Thank you so much for your helps.
In your function, you can directly convert num into a list by calling split(','), which will split on a comma - in the case a comma doesn't exist, you just get a single-element list. For example:
In [1]: num = '1'
In [2]: num.split(',')
Out[2]: ['1']
In [3]: num = '1,2,3,4'
In [4]: num.split(',')
Out[4]: ['1', '2', '3', '4']
You can then use your function as you have it:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
number = map(int,num)
return number
x = inputnumber()
print x
However you can take it a step further if you want - map here can be replaced by a list comprehension, and you can also get rid of the intermediate variable number and return the result of the comprehension (same would work for map as well, if you want to keep that):
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num]
x = inputnumber()
print x
If you want to handle other types of input without error, you can use a try/except block (and handle the ValueError exception), or use one of the fun methods on strings to check if the number is a digit:
def inputnumber():
num = raw_input('Enter number(s): ').split(',')
return [int(n) for n in num if n.isdigit()]
x = inputnumber()
print x
This shows some of the power of a list comprehension - here we say 'cast this value as an integer, but only if it is a digit (that is the if n.isdigit() part).
And as you may have guessed, you can collapse it even more by getting rid of the function entirely and just making it a one-liner (this is an awesome/tricky feature of Python - condensing to one-liners is surprisingly easy, but can lead to less readable code in some case, so I vote for your approach above :) ):
print [int(n) for n in raw_input('Number(s): ').split(',') if n.isdigit()]
input is not the way to go here - it evaluates the input as python code. Use raw_input instead, which returns a string. So what you want is this:
def inputnumber():
num = raw_input()
for i, j in enumerate(num):
if j not in ', ':
try:
int(num[i])
except ValueError:
#error handling goes here
return num
def main():
x = inputnumber()
print x
I guess all it is is a long-winded version of RocketDonkey's answer.

Categories