Appending to list produces None - python

Code:
for a in range(1,n+1):
name = input("Enter name of passenger ")
age = int(input("Enter age of passenger"))
sex = input("Enter sex of passenger")
lis= [name,age,sex]
passengers = passengers.append(lis)
print("All passengers are :")
print(passengers)
I have tried this to make a ticket making software, but the names of passengers are not getting added to passengers list. The result shown is None.

You are assigning the result of append() to the passengers variable but append() returns None. Simply remove the assignment:
for a in range(1,n+1):
name = input("Enter name of passenger ")
age = int(input("Enter age of passenger"))
sex = input("Enter sex of passenger")
lis= [name,age,sex]
passengers.append(lis)

The return value of .append() is None. Which is what you're assigning to your variable.
What you'd want instead is to define your passengers prior to your loop then append to it as follows
passengers = []
for a in range(1,n+1):
name = input("Enter name of passenger ")
age = int(input("Enter age of passenger"))
sex = input("Enter sex of passenger")
lis=[name,age,sex]
passengers.append(lis)
print("All passengers are :")
print(passengers)

Related

TypeError: list indices must be integers or slices, not str in python ( using list) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 11 months ago.
I'm trying to use list in this one but I had the bug in the last line stumarks[CourseID] = [(StuID,marks)]
Here is my code :
courselist = []
class course:
def __init__(self,id,name):
self.id = id
self.name = name
#classmethod
def CourseInfo(cls):
return cls(
input("Enter the course ID : "),
input("Enter the course name : ")
)
def cif():
for i in range(getNumOfCourses()):
cse = course.CourseInfo()
courselist.append(cse)
stumarks = []
def MarkInput():
CourseID = input("Enter the course's ID : ")
if CourseID not in [CourseInfo.id for CourseInfo in courselist]:
print(" The course's id isn't founded! Please try again!")
else:
nm = int(input("Number of student that you want to enter marks: "))
for i in range(nm):
while True:
StuID = input("Enter a student's ID : ")
if StuID not in [StudentInfo.id for StudentInfo in studentlist]:
print("The student's ID isn't founded! Please try again! ")
continue
break
marks = float(input("Enter the mark: "))
if CourseID in stumarks:
stumarks[CourseID].append((StuID,marks))
else:
stumarks[CourseID] = [(StuID,marks)]
Could anyone help me with this one? Thank you!
The problem is that CourseId is not cast to an integer and is hence treated as a string. Try changing:
CourseID = input("Enter the course's ID : ")
to
CourseID = int(input("Enter the course's ID : "))

How to store users input into dictionary? Python

I want to create a simple app to Ask user to give name and marks of 10 different students and Store them in dictionary.
so far only key:value from the last input is stored into dictionary.
can you please check my code?
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks = {student_name.title():student_mark}
print(marks)
Your current code has two issues: first, it doesn't save the values of each student inside the loop. Second, it always rewrites the entire dictionary with a single key/value pair, that's why it doesn't work.
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name.title()] = student_mark
print(marks)
You need your code to be inside your loop. Also the way you put value inside your dict is not right. This should do the trick
marks = {}
for i in range(10):
student_name = input("Enter student's name: ")
student_mark = input("Enter student's mark: ")
marks[student_name] = student_mark
print(marks)

Solving TypeError when concatenating a string

I assigned these variables:
x = "1"
name = str(input("Enter Name :"))
gender = str(input("Enter Gender (M/F) :")).lower
year = int(input("Enter Year of Birth :"))
postcode = str(input("Enter Postcode :"))
Then I got I got a part of the string postcode.
partCode = postcode[0:3]
Then I converted the year in to a string.
birthYear = str(year)
After, I tried concatenating all the strings:
username = name + birthYear + gender + partCode + x
And I receive this error:
TypeError: can only concatenate str (not "builtin_function_or_method") to str
How can I solve it?
The above error is because gender is not a string
replace
gender = str(input("Enter Gender (M/F) :")).lower
with
gender = str(input("Enter Gender (M/F) :")).lower()
Try this :
x = "1"
name = str(input("Enter Name :"))
gender = str(input("Enter Gender (M/F) :")).lower()
year = int(input("Enter Year of Birth :"))
postcode = str(input("Enter Postcode :"))
partCode = postcode[0:3]
birthYear = str(year)
username = name + birthYear + gender + partCode + x
You don't need to convert any of the input variables their all read in as str.
This will do
x = "1"
name = str(input("Enter Name :"))
gender = str(input("Enter Gender (M/F) :")).lower()
year = str(input("Enter Year of Birth :"))
postcode = str(input("Enter Postcode :"))
The issue is you didn't have () for the lower function so your gender variable was <built-in method lower of str object at 0x7fb7152ffc38>. That should explain your error

How to Append Grades on List per student in Dictionary Python

Students = {}
def IslemYap():
Input = int(input("Process Number: "))
if Input == 1:
StudentName = input("Student Name: ")
for i in range(1,8):
Students.update({StudentName:[input()]})
print(Students)
IslemYap()
Im trying this but don't working. 7 times per student append grades.
you always overwrite it and never fill the grades in a proper list.
Students = {}
def IslemYap():
Input = int(input("Process Number: "))
if Input == 1:
StudentName = input("Student Name: ")
for i in range(1,8):
Students[StudentName] = Students.get(StudentName,[]) + [input()]
print(Students)
IslemYap()
You can add the grades to a list and simply add it to the correspondent student in the dictionary
Students = {}
def IslemYap():
Input = int(input("Process Number: "))
grades = []
if Input == 1:
StudentName = input("Student Name: ")
for i in range(1,8):
grades.append(input())
Students.update({StudentName: grades})
grades = []
print(Students)
IslemYap()

How to combine str and int variables?

For this problem, I need to "separate" or identify individual sets of 3 different user inputs: a name, an address, and a salary. Then the program needs to find the highest salary and print the name and the address of the person that it belongs to.
I'm not sure how I can do this in Python.
I know I can use max(salary) but how can I print the associated name and address?
I'm trying to do this using a while loop.
Edit:
Ok, so I'm a beginner so I apologize if this is too basic.
This is what I came up with so far.
name = str(raw_input("Input name: "))
address = str(raw_input("Input address: "))
salary = int(raw_input("Input salary or a number < 0 to end program: "))
x = []
while salary > 0:
name = str(raw_input("Input name: "))
address = str(raw_input("Input address: "))
salary = int(raw_input("Input salary or a number < 0 to end program: "))
x.append(salary) #this returns error: 'int' object is not iterable
m = max(salary)
print #should print name, address associated with max(salary)
Thank you
max_salary = None
max_index = None
salary = 1
index = 0
x = []
while salary > 0:
name = raw_input("Input name: ")
address = raw_input("Input address: ")
salary = int(raw_input("Input salary or a number < 0 to end program: "))
if max_salary is None or salary > max_salary:
max_salary = salary
max_index = index
index += 1
x.append("{} {} {}".format(name, address, salary))
if max_index is not None:
print(x[max_index])
Another way (preferred):
x = []
while True:
name = raw_input("Input name: ")
address = raw_input("Input address: ")
salary = int(raw_input("Input salary or a number < 0 to end program: "))
if salary < 0:
break
x.append((name, address, salary))
if x:
print("{} {} {}".format(*max(x, key=lambda t: t[2])))
This should be working fine.
people=[]
elements= int(input('enter the number of people you want: '))
for i in range(elements):
name= input('enter the name of person %d: '% (i+1))
address= input('enter the address: ')
salary= int(input('enter the salary: '))
person={}
person['name']=name
person['address']= address
person['salary']= salary
people.append(person)
# getting the max from all the salaries and the max
sal_max= max([x['salary'] for x in people])
# matching the max salary:
for i in people:
if i['salary']==sal_max:
print (i['name'], i['address'])

Categories

Resources