I am trying to take two long input integers (up to 10 digits) separated by space and display there sum.
I took the input into a string which are separated by space and then split them. After that I type caste them to int.
print "Enter two numbers"
a = raw_input()
a.split(" ")
sum = int(a[0]) + int(a[2])
print "\r", sum
Here I am not able to print the sum if the numbers are of even two digits.
You ignored the return value of str.split():
a.split(" ")
Assign that back to a:
a = a.split(" ")
Python strings are immutable, you cannot split the value of a in-place (let alone replace the type, splitting returns a list object rather than a new string).
Related
I am completely new to python, and am trying to print some elements of my list. In second print() I am getting error, which is: 'list indices must be integers or slices, not str'.
The output should be The sum of digits operation performs 1+4. Where am I wrong?
def sum_of_digits(s):
letters = []
numbers = []
for i in s:
if i.isalpha():
letters.append(i)
elif i.isdigit():
numbers.append(i)
print("The extracted non-digits are: {} ". format(letters), end="\n")
print("The sum of digits operation performs ", s.join(int(i, numbers[i])))
sum_of_digits("1aw4")
Let's examine s.join(int(i, numbers[i]))
int(a,b) mean convert a as an int with base b, for example
int('11011', 2) # 27
int('11011', 8) # 4617
int('11011', 10) # 11011
and i in your case is the last char of the string, even numbers[i] is not possible (that's where the exception is)
s.join would mean to put the original s string between each value of the given parameter, non-sens too
You may convert to int each char that is a digit, then just use sum
Sum result
def sum_of_digits(s):
letters = []
numbers = []
for i in s:
if i.isalpha():
letters.append(i)
elif i.isdigit():
numbers.append(int(i))
print("The extracted non-digits are: {} ".format(letters), end="\n")
print("The sum of digits operation performs ", sum(numbers))
The extracted non-digits are: ['a', 'w']
The sum of digits operation performs 5
Sum operation
def sum_of_digits(s):
letters = []
numbers = []
for i in s:
if i.isalpha():
letters.append(i)
elif i.isdigit():
numbers.append(i)
print("The extracted non-digits are: {} ".format(letters), end="\n")
print("The sum of digits operation performs ", "+".join(numbers))
The extracted non-digits are: ['a', 'w']
The sum of digits operation performs 1+4
numbers[i] causes that error because i is a string (it's the last character from the for i in s: loop). Since numbers is a list, indexes must be integers, not strings.
The argument to join should just be the list of strings that you want to join. You don't need to call int(), and you don't need to use i.
The join() method should be called on the string that you want to be the delimiter between each of the elements when they're joined. If you just want to concatenate all the elements, use an empty string, not s.
print("The sum of digits operation performs ", "".join(numbers))
This prints:
The sum of digits operation performs 14
DEMO
I wanted to write a rarther simple cipher program that can convert numbers to letters. So the user provides numbers as input and it gets decoded by the program and that's how you would read the secret message. The problem is that to be able to iterate through numbers i need variable type string and to (add 95 because of ascii codes) i need type int.
i have tried to take input as a string, i have tried converting it to int. I have even tried to convert it in the for loop to an int but i still get an error either that it has to be string or that this variable needs to an int.
a = int(input("Enter a number: "))
for numbers in a:
number = chr(numbers) + 95
print (number)
Your problem seems to be that you need to convert back and forth between different data types: strings, list of strings, and list of integers.
Your question might not be super helpful to others, but I hope this answer will help you at least :) I broke my answer from the comment into shorter steps. Each step has an example of what type of data you are dealing with at the end.
# Read a string like "8 5 12 12 15"
encoded = input("Enter some numbers, separated by spaces: ")
# Turn the string into a list of shorter strings.
# For example: ["8", "5", "12", "12", "15"]
# you should handle input errors here, too
encoded_list = encoded.split(' ')
# Conver the list of strings to a list of integers
# For example: [8, 5, 12, 12, 15]
encoded_numbers = [int(character) for character in encoded_list]
# Decode the numbers and turn them back into strings using chr()
# For example: ["h", "e", "l", "l", "o"]
character_list = [chr(number + 96) for number in encoded_numbers]
# Finally, turn the list of characters into a single string using
# join, then print it
print("Decoded message:")
print("".join(character_list))
I highly recommend playing with the interactive shell (just run python - or even better ipython if you have it installed). It's easier to check what type of data a function returns and experiment with it that way.
Now you're trying to get string and convert it to integer in first string, then you trying to put this integer into for loop.
I do not quite understand what you want from this code, but if you want to type a number of char in ascii ang get this char, use this:
a = input('Enter a number: ')
char = chr(int(a) + 96)
print('Decoded char: ' + char)
You need to iterate over a range of numbers, maybe 26?.
Then you must add 97 which is the ASCII value of a
for number in range(26):
char = f'{chr(number + 97)}'
print (char, end=' ')
output:
a b c d e f g h i j k l m n o p q r s t u v w x y z
From then on, you can easily navigate between the ASCII code and the letter representation; adding an offset modulo 26 will give you a Caesar cypher.
The reverse operation (from letter to ASCII code, to the original (0-26) number is as follows:
ord(char) - 97
So my programming assignment wants me to take a user inputted list of numbers, ints and floating, and then order them in descending order and replace any of the floating with "0". I have got the reorder part done but the replace is getting me lost.
Reading Numbers
Write a program that shall ask the user to enter several integer numbers on
the same line, separated by vertical bars surrounded by zero or more spaces
(e.g., “|” or “ |” or “| ” or “ | ”). The program then shall display the entered
numbers in the descending sorted order (from the largest to the smallest),
all on the same line, separated by vertical bars and spaces (“ | ”). If
any entry on the command line is not an integer number, the program shall
replace it with a 0. Use only “for” loop(s) or list comprehensions. Use exception
handling.
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|' :
").split("|")
# replace the floating numbers with "0"
for number in numbers:
print(type(number))
if number.isdigit() == False:
numbers.replace(number,'0')
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(key = float , reverse = True)
[print(number,end = ' | ') for number in numbers]
One change I made was switching all of the for number in numbers to for i in range(len(numbers)). This allows you to access the actual variable by index, while for number in numbers just gets the value.
Here is my solution. I tried to add comments to explain why I did what I did, but if you have any questions, leave a comment:
# takes input and split them to get a list
numbers = input("Please enter numbers separated by vertical bars '|'\n").split(
"|")
# strip any extra spaces off the numbers
for i in range(len(numbers)):
numbers[i] = numbers[i].strip(" ")
# replace the floating numbers and strings with "0"
for i in range(len(numbers)):
try:
# check if the number is an int and changes it if it is
numbers[i] = int(numbers[i])
except:
# set the item to 0 if it can't be converted to a number
numbers[i] = 0
# takes the list and reverse order sort and prints it with a "|" in between
numbers.sort(reverse = True)
# changes the numbers back into strings
numbers = [str(numbers[i]) for i in range(len(numbers))]
# makes sure that there are more than one numbers before trying
# to join the list back together
if len(numbers) > 1:
print(" | ".join(numbers))
else:
print(numbers[0])
the instructions permit you to use exceptions. the following should get you most of the way there.
>>> numbers = ['1', '1.5', 'dog', '2', '2.0']
>>> for number in numbers:
>>> try:
>>> x = int(number)
>>> except:
>>> x = 0
>>> print(x)
1
0
0
2
0
A program accepts a number of inputs, for instance numbers or integers, how do you print each and every one of them on a new line.
Eg. I enter this 2,4,5,2,38.
The program should display each one on a new line as this.
Item = input ("Enter your number")
#user enters the following numbers 5,2,6,3,2
#print out each number on a new line
# output
5
2
6
3
2
All saved i one variable.
All you need is a simple for loop that iterates over the input and prints it
data = raw_input('enter ints').split(',')
for n in data:
if n.isdigit():
print n
Note if you are using Pyhon 3.x, you need to use input instead of raw_input
The first row assigns user input data to data variable and splits items by space. (You can change this tow ',' instead)
The for loop does iteration on every item in that list and checks if it is a digit. Because the list elements are strings, we can use isdigit() method of string to test it.
>>> '5'.isdigit()
True
>>> '12398'.isdigit()
True
If you want to do it in another way, maybe using '\n'.join(data) method, which will join the list elements and join them with '\n'.
>>> inpu = raw_input('enter ints\n').split(',')
>>> inpu = [c.strip() for c in inpu]
>>> print '\n'.join(inpu)
1
2
3
4
This is actually the better way to go, as it is simpler than a for loop.
By typing in print() in python it will move to the next line. If it is a list you can do
for num in list:
print(num)
print()
You want to replace "list" with the name of your list.
You can also type in \n in your print function in quotes to move to a new line.
If the numbers are separated by a comma, you can split them by that comma, then join them by a new line:
>>> Item = input ("Enter your numbers: ")
Enter your numbers: 5,2,6,3,2
>>> Result = '\n'.join(Item.split(','))
>>> print(Result)
5
2
6
3
2
>>>
looks like I'm too late to the print party :)
this can work for you too ... wrap it in a function ideally
# assuming STDIN like: "2,4,5,2,38,42 23|26, 24| 31"
split_by = [","," ","|"]
i_n_stdin = input()
for i in split_by:
i_n_stdin = i_n_stdin.split(i)
i_n_stdin = " ".join(i_n_stdin)
#print(i_n_stdin)
for i in i_n_stdin.split():
print(i)
If you want to print a comma-separated list of integers, one integer at each line, you can do:
items = input('Enter a comma-separated list of integers: ')
print(items.replace(",", "\n"))
Example:
Enter a comma-separated list of integers: 1,13,5
1
13
5
You can improve by accepting ";" instead of "," and optional spaces using RegEx:
import re
items = input('Enter a comma-separated list of integers: ')
print(re.sub(r"[,;]\s*", "\n", items))
Example:
Enter a comma-separated list of integers: 2, 4, 5; 2,38
2
4
5
2
38
You can print in the new line by using by defining end parameter as '\n' (for new line) i.e print(x,end='\n')
>>> x=[1,2,3,4]
>>> for i in x:
print(i,end='\n')
output
1
2
3
4
you can use help function in python
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Python 3.x
items = input('Numbers:').split(',') # input returns a string
[print(x) for x in items]
Python 2.x
items = input('Numbers:') # input returns a tuple
# you can not use list comprehension here in python 2,
# cause of print is not a function
for x in items: print x
Just set variable end = '\n'
and print your numbers like:
print(" " + str(num1) + end, str(num2) + end, str(num3) + end)
Hi im trying to write a program which uses a repetition statement to allow users to enter 5 numbers and stores them in a list.Then allow the user to search the list for a number entered by the user and indicate whether the number has been found or not. Im quite stuck on this one, I've made as much of an effort as i can
data =raw_input('Please input 5 numbers: ')
print data
search =raw_input('Search for the numer: ')
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
data is a string, the for loop will loop over every character in this string. That's probably not what you want.
If you want to find an integer in a list of integers, split the input on whitespace and convert each to an integer using int.
ints = [int(x) for x in data.split()]
if int(search) in ints:
print "Found it"
You might try something like this
numbers = []
while len(numbers) < 5:
number = raw_input('Please input 5 numbers: ')
if number.isdigit():
numbers.append(int(number)) #may want to use float here instead of int
else:
print "You entered something that isn't a number"
search = raw_input('Search for the numer: ')
if int(search) in numbers:
print "Found it!"
your code indicates that you may be using sublists but it is unclear how you are creating them.
Issue 1: This line stores the input as a string in the variable data.
data =raw_input('Please input 5 numbers: ')
At this point it is necessary to split the string into a list, and converting the elements to integers.
If the user inputs numbers separated by a space, you can do:
data_list = data.split() # if the numbers are comma-separated do .split(',') instead
int_list = [int(element) for element in data_list]
Issue 2: The users search input should be converted to an integer
search =raw_input('Search for the numer: ')
search_int = int(search)
Issue 3: There is no need for indexing the sublist as you've attempted sublist[1].
The for-loop should then be:
for sublist in int_list:
if sublist == search_int:
print "Found it!", sublist
break