How to access strings entered in loop? - python

This is the code.
n = int(input("Enter number of strings: "))
for i in range(n):
ai= input("Enter string ")
i=0
print(ai)
Why does it give last string and not the first string?
If I try to print a0 ,it gives error.
I know that I can use lists , but I didn't know about list when I wrote the program and now I have to change everything to use list.

Because you are overwriting the variable in each iteration of the loop, if you want to print all the strings added in the format you can use something like this
n = int(input('enter number of strings'));
ai = ''
for i in range(n):
ai += input('enter a string: ')+'\n'
i = 0
print(ai)
This will print your string.

You should use a list and append every input to the list instead:
n = int(input("Enter number of strings: "))
a = []
for _ in range(n):
a.append(input("Enter string: "))
print(a[0])

Related

Problems with the formatting

Write a program that requires users to enter integers, each in a separate line. The user indicates the end of the entry in a blank line. The program prints negated values. The program prints values ​​in the same line separated by a space.
n = input()
while n != "":
n = int(n)
print(-n, end=" ")
n = input()
print(-n, end=" ")
This code works, but it needs help with the formatting.
The input should look like this:
5
0
-11
The output should look like this:
-5 0 11 -2
Since you want to input all values first and then print you need save them all to a list. Then, print them out after you're doing inputting. You can do this by using join(), but note that you must convert from str to int and back to str with this.
all_nums = []
n = input()
while n != "":
all_nums.append(str(-int(i)))
n = input()
print(" ".join(all_nums))
Instead, if you would like to print the numbers out with a normal loop you can do this
all_nums = []
n = input()
while n != "":
all_nums.append(-int(i))
n = input()
for i in all_nums:
print(i, end=" ")

Adding elements to list after get 2 or more inputs on Python

def take_info(arr2,arr, number):
arr[0] = number
name = input()
arr[1] = name
grade = int(input())
arr[2] = grade
second_grade = int(input())
arr[3] = second_grade
arr2. append(arr)
def main():
number = int(input())
arr = [0] * 4
count =1
arr2 = // ? I dont know how to do it, range must be equal to count but how? Thats the point 1.
while number>0:
take_info(arr2,arr,number)
count +=1
number = int(input())
main()
take_info function must return while ' number >0 ', when the number is 0 or less than 0 loop would end. And I want to add these values and name to a list and the other list's each element should be list. Could anyone can help me ?
Any time you're repeating something, you probably want to use a loop. If you're using a loop to build a list, you probably want to use a list comprehension.
arr = [input() for _ in range(3)]
Given your updated question, I might do it like this:
def take_info(number):
return [number, input(), int(input()), int(input())]
def main():
return [take_info(number) for number in range(int(input()))]
print(main())
If it's important that the numbers count down instead of up, you can do that by modifying the range call so that it goes from N-1 to 0 instead of 0 to N-1.
Alternatively, if you want to have space separated inputs in one line, you can use this:
my_list = list(map(str,input().split()))
for i in range(len(my_list)):
if (isinstance(my_list(i), int)):
temp = int(my_list(i))
my_list.pop(i)
my_list.insert(i, temp)
Input: Car Hockey Cricket
my_list = ['Car', 'Hockey', 'Cricket']
Ofcourse, the data type would be the same here. You'd need to make changes after appending incase of int, float, etc.
The stereotype of Python is that “everything is a dict”. Your application might be such a case.
One way to organize the data you have coming in might be a dict where each entry is also a dict.
def take_info():
record = dict()
record['name'] = input('Name: ')
record['grade'] = int(input('Grade: '))
record['second_grade'] = int(input('Second grade: '))
return record
def main():
course_records = dict()
count = 0
number = int(input('ID number: '))
while number > 0:
course_records[number] = take_info()
count +=1
number = int(input('ID number: '))

How do I separate the numbers from an input in order to add them?

I am trying to have the user input a series of numbers (separated by commas) to receive the total of them.
I have tried (with no luck):
values = input("Input some comma seprated numbers: ")
numbersSum = sum(values)
print ("sum of list element is : ", numbersSum)
values = input("Input some comma seprated numbers: ")
list = values.split(",")
sum(list)
print ("The total sum is: ", sum)
If the user inputs 5.5,6,5.5 the expected output will be 17.
You're almost there.
After splitting, the values will still be strings, so you have to map them to float.
values = "5.5,6,5.5" # input("Input some comma seprated numbers: ")
L = list(map(float, values.split(",")))
print ("The total sum is: ", sum(L))
Output:
The total sum is: 17.0
Side note: Please don't name your variables list or sum, otherwise you will shadow the python built-ins!
After you split the values by comma into a list, you need to convert them from strings to numbers. You can do that with
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [float(x) for x in lst]
total = sum(lst)
print("The total sum is: ", total)
For reference, see List Comprehensions in Python.
(Also, you shouldn't use list as a variable name, since that's a function in Python.)
You have to convert the inputs to float:
numbers = input("Input some comma seprated numbers: ")
result = sum([float(n) for n in numbers.split(',')])
print(result)
You have to convert to numbers before adding them together.
For example, you could convert them all into floats:
input_str = input("Input some comma seprated numbers: ")
# Option1: without error checking
number_list = [float(s) for s in input_str.split(',')]
# Option2: with error checking, if you are not sure if the user will input only valid numbers
number_list = []
for s in input_str.split(','):
try:
n = float(s)
number_list.append(n)
except ValueError:
pass
print("The list of valid numbers is:", number_list)
print("The sum of the list is:", sum(number_list))
# empty list to store the user inputs
lst = []
# a loop that will keep taking input until the user wants
while True:
# ask for the input
value = input("Input a number: ")
# append the value to the list
lst.append(value)
# if the user wants to exit
IsExit = input("enter exit to exit")
if 'exit' in IsExit:
break
# take the sum of each element (casted to float) in the lst
print("The sum of the list: {} ".format(sum([float(x) for x in lst])))
OUTPUT:
Input a number: 5.5
enter exit to exitno
Input a number: 6
enter exit to exitno
Input a number: 5.5
enter exit to exitexit
The sum of the list: 17.0
It's hard to know what went wrong w\o a sample of the error\output code.
I think the issue is in getting the sum of list (very bad name btw) when it's a list of strings.
please try the following
values = input("Input some comma seprated numbers: ")
lst = values.split(",")
lst = [int(curr) for curr in lst]
sum(lst)
print ("The total sum is: ", sum)
This code will work when expecting integers, if you want floats then change the list comprehension.
Try not to name objects with the same name of standard objects such as list,int,str,float etc...
use below
print('sum of input is :',sum(list(map(float,input('Input some comma separated numbers: ').split(',')))))

Only the last item is being appended to a list in a while loop (Python)

I'm trying to create a program that gets each digit of an inputted number into a list using a while loop. However, it only appends the last digit of the number to the list.
Code -
num = int(input("Enter a number: "))
numstr = str(num)
numlen = len(numstr)
x = 0
while x < numlen:
digits = []
a = numstr[x]
digits.append(a)
x = x + 1
print(digits)
So if I were to put in 372 as the number, the list would just simply be ['2'] with a length of 1.
Try this code:
digits = [i for i in str(num)]
You cannot do better than digits = list(str(num)). In fact, since input returns a string, even the conversion to a number is not necessary:
num = input("Enter a number: ")
digits = list(num)
(You still may want to ensure that what's typed is indeed a number, not a random string.)

Python 2D lists appending data to a location

Wondering if someone can help me on this. I know I can append data to a 1D list by using .append. What I am having trouble figuring out is how to append data to a 2D list and have Python place the data in the right list in the right spot.
I need to create a program that runs x times (with each name having 2 pairs of values), and after each time append the user input to a list. So at the end, I need something like this:
[[Name] [1,2] [3,4]]
[[Name] [4,5] [6,7]]
etc….
How do I tell Python which List and position to place the Names and values in ?
This is what I have so far for code.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = [ [], [] ]
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
counter = counter + 1
main()
OK - so I modified the code and added in a line to append the data, after the line with the counter + 1.
list.append([[name],[first_val,first_val2], [sec_val,sec_val2]])
What I would now like to do is print the list out (via rows and columns), but am getting a IndexError. This occurs when I try to enter/print out more than 4 values. The error appears to be in the last line. Is there a way I can modify the code to stop this and print out as many values as have been requested by the user ?
for r in range(how_many):
for c in range (how_many):
print list [r][c]
And yes, I will look into using tuples as well at some point.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = []
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
counter = counter + 1
Assume we are reading the values from stdin (as in the question body)
you can use lists:
list = []
....
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
but a tuple seems to be a better fit here:
t = (name, (first_val, first_val2), (sec_val, sec_val2))
list.append(t)
Since the values are not likely to change, a tuple feels like the better choice.
Think about how a field would be accessed in each case:
list:
name = list[i][0][0]
tuple:
name = list[i][0]
Again...it just seem more natural...

Categories

Resources