I need assistance for my little program (python lists) - python

I will give you my python code (it's pretty basic and small) and if you can,tell me where i am wrong.I am noob at coding so your help will be valuable.thanks a lot and don't hate :)
lista=[]
for i in range(100):
a=input("give me a number")
if a%2==0:
a=0
else:
a=1
lista=lista+a
print lista
P.S: I code with python 2 because my school books are written with that in mind.

You need to use append method to add an item to the end of the list.
lista.append(a)
And you need to convert the str returned by input() to int.
The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
a = int(input("give me a number"))
Try this:
lista=[]
for i in range(2): # Changed from 100 to 2 for my own testing
a = int(input("Give me a number: "))
a = 1 if a%2 else 0
lista.append(a)
print(lista)
Outputs:
[0,1]
EDITED:
So i cant use Lista=lista +a?I thought i could..my book says i can..thanks for your solution,it works!
You can use += operator (similar to extend()) but it requires a list operand. Not an int. So, you need to convert your int to a list. Try this:
lista += [a]
list.append(a) is faster, because it doesn't create a temporary list object. So, better to use append.

Related

How do I use slices properly

I have just learned the index and slicing in python. After I learned, I got a good idea to make. The idea briefly is that instead of writing the sequence in the code, I want the user to choose a start and an end and print the result. I have written the code and it showed no problems, but when I ran it, it didn't work :(
So I need help to make it run as I imagined.
`
mystring = "Omar Marouf Zaki"
print("Choose First Number")
x = input()
print("Choose Second Number")
y = input()
print(mystring[x:y])
Convert the Strings to Int.
input() return string so you need to do print(mystring[int(x):int(y)]) to make x and y ints
If you want cleaner code, you could convert your input to an int before assigning it to x and y, like this:
x = int(input())
# ...
y = int(input())
# Now you can use [x:y] without problems becuase both x and y are integers
print(mystring[x:y])

inputted list keeps being interpreted as string

So I made this little code at school, and i know that input() can understand lists as is. I tried it again at home but it doesnt work. My school computer has python 2. something while my laptop has 3.4.
The code looks like this
a = input()
list = []
count = 0
for y in range(1, len(a)):
min = a[count]
for x in range(count +1, len(a)):
if min > a[x]:
min = a[x]
print(min)
a[count] = min #str object does not support item assignment
count=count+1
print (a)
I want to input a list such as [1,2,3,4,5] but what happens is, it reads the whole thing as a string, along with the commas, when i want to see it as a list of integers.
Python 3's input returns a string (same as Python 2's raw_input), whilst Python 2's input evaluates the text. To get similar behaviour, if you've got a valid Python list that can be evaluated, then you can use ast.literal_eval, eg:
import ast
a = ast.literal_eval(input())
# do other stuff with `a` here...
So you'd enter something like [1, 2, 3, 4, 5] as your input, and you'll end up with a being a Python list.
I assume your input would be something like: "1 2 3 4 5" -- judging by the code which comes later. This oufcourse is a string. If you want to work with the numbrs in the string as integers you need to:
a = input()
a = map(int, a.split())

Wrong output for function that computes the sum of the digits in an integer

I'm required to write a function that computes and returns the sum of the digits in an integer.
Here's my code:
def main():
number1=input("Enter a number: ")
number=list(number1)
i=0
while len(number)!=i:
numbers=[]
x=int(number[i])
numbers.append(x)
number.remove(number[i])
print(numbers)
x=float(sum(numbers))
print(x)
main()
The output looks like:
Enter a number: 123
[3]
3.0
I'm not sure why 1 and 2 aren't in the list, and aren't used to compute the sum... any suggestions?
You reinitialize numbers inside the loop. Don't do that, move that outside of the loop instead:
numbers=[]
while len(number)!=i:
# ...
otherwise you end up resetting the list for each and every digit.
It's good for you to learn the basics before you try advanced stuff, but just for fun, here is the way an experienced Python coder would solve this problem:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(int(ch) for ch in number1))
x = main()
print(x)
We can use the builtin function sum() to sum the digit numbers, and we get the digit numbers with a "generator expression" that loops over the string directly while calling int().
This is just a taste of the fun stuff you will be learning soon in Python. :-)
You can also do it in a more functional way, if you are interested in this kind of programming. It would then look like this:
def main():
number1=input("Enter a number: ") # for Python 2.x, need to use raw_input()
return float(sum(map(int, number1))
x = main()
print(x)

Adding slicing numbers using a loop

I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....
you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic
>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16
>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'
It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).

Python truncating numbers in integer array

I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.

Categories

Resources