I want to write a program to have the (name, age, height) where name is string, age and height are numbers for at least 2 users. So I have tried to use a while True loop but it breaks after just one entry (name, age, height). This is because number of items in the list is tree. How could I make a tuple so that the number of items would count as one for all the name, age and height? or is there any easy way?
data=[]
while True:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append(name)
data.append(age)
data.append(height)
if len(data) <2:
print "you need to enter at least 2 users"
else:
break
print data
Try
data=[]
while len(data) < 2:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append({
'name': name,
'age': age,
'height': height,
})
print data
It is because you put name instead of dict of user information (name, age, height).
You can use range
Ex:
data=[]
for _ in range(2):
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append((name, age, height))
print(data)
Or: using a while loop.
data=[]
while True:
name = raw_input("Please enter your name: ")
age = int(raw_input("Please enter your age: "))
height = int(raw_input("Please enter your height: "))
data.append((name, age, height))
if len(data) == 2:
break
print(data)
Related
I don't know what is the error of my code can anyone help me to fix this code.
age = ""
while int(len(age)) == 0:
age = int(input("Enter your age: "))
print("Your age is " + age)
You wanted a string for age but you transformed this age into an integer inside your loop :)
You can write :
age = ""
while age == "":
age = input("Enter your age: ")
print("Your age is " + age)
In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.
So you can simplify your while loop:
age = ""
while not age:
age = input("Enter your age: ")
print("Your age is " + age)
You cast age to be an int inside of your while loop, while using the len(age) as the comparison.
int does not have a length.
You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.
age = ""
while len(age) == 0:
age = input("Enter your age: ")
print("Your age is " + age)
I'm trying to display the names except the 'name' and trying to get the average of age without 'age' on the list and lastly get the average of the grade without the 'Grade'.
I have a problem I'm trying to print the names of the list without the first row in the list(['Name', 'Age', 'Grade']) without pop or removing them from the list.
studentDB = [['Name', 'Age', 'Grade'], ['Con', 20, 90.2],
['Juan', 45, 70.2], ['Jed', 39, 100.0]]
while True:
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
for s in range(1, len(studentDB)):
print("")
print(f"There are in the {s} student table. The people included in the list are.")
else:
print("Invalid input")
Here is the output that I wanted to do
This is the online compiler: https://www.programiz.com/python-programming/online-compiler/
There can be many ways to solve this. One could be to use starting index in range and use slice while calculating average of age or grades.
from statistics import mean
while True:
# Use the start index in range.
for i in range(len(studentDB)):
print(i, studentDB[i])
print("\n********** Hackathon ***********")
CRUD = """1- Add
2- Delete
3- Edit
4- Print Report
----------------
Enter a number: """
choice = float(input(CRUD))
if (choice == 1):
Name = input("Please Enter your Name: ")
Age = int(input("Please Enter your Age: "))
Grade = float(input("Please Enter your Grade: "))
studentDB.append([Name, Age, Grade])
print(studentDB)
elif (choice == 2):
Del = int(input("Please Enter the row you want to delete: "))
studentDB.pop(Del)
elif (choice == 3):
Del1 = int(input("Please Enter the row you want to delete: "))
Name1 = input("Please Enter your Name: ")
Age1 = int(input("Please Enter your Age: "))
Grade1 = float(input("Please Enter your Grade: "))
studentDB.pop(Del1)
studentDB.insert(Del1,[Name1, Age1, Grade1])
print(studentDB)
elif (choice == 4):
#here is the problem
# Use slice to get the row from index 1 afterwards
print(f"There are in the {len(studentDB) - 1} records in the student table. The people included in the list are.")
print(",".join([student[0] for student in studentDB[1:]]))
average_age = mean([row[1] for row in studentDB[1:]])
average_grades = mean([row[2] for row in studentDB[1:]])
# Print average age and grades here
else:
print("Invalid input")```
from SimpleGraphics import *
f = open("shape.txt","w")
print("Please provide the necessary information below.")
while (True):
s=input("please select one of following shapes (line, rect, elipse or quit): ")
if s=="line":
f.write(s+"\n")
y=float(input("please enter you Y value: "))
f.write(str(y)+"\n")
x=float(input("please enter you X value: "))
f.write(str(x)+"\n")
h=float(input("please enter the value for the height: "))
f.write(str(h)+"\n")
w=float(input("please enter the value for the width: "))
f.write(str(w)+"\n")
c=input("please enter the colour: ")
f.write=(c+"\n")
print(h)
if s=="quit":
break
f.close()
I'm trying to understand how to use functions properly. In this code, I want to return 2 arrays for pupil names and percentage scores. However I am unable to return the array variables from the first function.
I've tried using different ways of defining the arrays (with and without brackets, both globally and locally)
This is the relevant section of code for the program
#function to ask user to input name and score
def GetInput():
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
I'm expecting to be asked to enter the values for both arrays.
I'm instead getting:
Traceback (most recent call last):
File "H:/py/H/marks.py", line 35, in <module>
name, mark = GetInput()
File "H:/py/H/marks.py", line 7, in GetInput
names[counter] = input("Please enter the student's name: ")
NameError: global name 'names' is not defined
You need to use dictionary instead of list if your want to use key-value pairs. furthermore you need to return the values outside of for loop. You can try the following code.
Code:
def GetInput():
names = {} # Needs to declare your dict
percentages = {} # Needs to declare your dict
for counter in range(0, 3):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages # Return outside of for loop.
name, mark = GetInput()
print(name)
print(mark)
Output:
>>> python3 test.py
Please enter the student's name: bob
Please enter the student's score %: 20
Please enter the student's name: ann
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{0: 'bob', 1: 'ann', 2: 'joe'}
{0: 20, 1: 30, 2: 40}
If you want to create a common dictionary which contains the students' name and percentages, you can try the following implementation:
Code:
def GetInput():
students = {}
for _ in range(0, 3):
student_name = input("Please enter the student's name: ")
valid = False
while not valid:
student_percentages = int(input("Please enter the student's score %: "))
if student_percentages < 0 or student_percentages > 100:
print("Please enter a valid % [0-100]")
continue
valid = True
students[student_name] = student_percentages
return students
students = GetInput()
print(students)
Output:
>>> python3 test.py
Please enter the student's name: ann
Please enter the student's score %: 20
Please enter the student's name: bob
Please enter the student's score %: 30
Please enter the student's name: joe
Please enter the student's score %: 40
{'ann': 20, 'bob': 30, 'joe': 40}
You forgot to set the names and percentages as empty dictionaries so you can use them. Also the "return" should be outside of the for loop.:
def GetInput():
names={}
percentages={}
for counter in range(0,10):
names[counter] = input("Please enter the student's name: ")
valid = False
while valid == False:
percentages[counter] = int(input("Please enter the student's score %: "))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
Probably this may help to you.
#function to ask user to input name and score
def GetInput():
names=[]
percentages=[]
for counter in range(0,3):
names.append(input("Please enter the student's name: "))
valid = False
while valid == False:
percentages.append(int(input("Please enter the student's score %: ")))
if percentages[counter] < 0 or percentages[counter] > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
return names, percentages
name, mark = GetInput()
print(name,mark)
This is implemented by using two lists. (Not suggested for keeping records. Better use dictionary as done below.)
counter = 10
def GetInput():
names = []
percentage = []
for i in range(counter):
names.append(input("Please enter the student's name: "))
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
return names, percentage
students, marks = GetInput()
The following is implemented by using dictionary, and for this, you do not need the variable counter.
def GetInput():
records = dict()
for i in range(counter):
name = input("Please enter the student's name: ")
valid = False
while not(valid):
try:
percent = int(input("Please enter the student's score between 0 and 100%: "))
if percent >= 0 and percent <= 100:
#percentage.append(percent)
valid = True
break
else:
continue
except ValueError:
print("\nEnter valid marks!!!")
continue
valid = True
records[name] = percent
return records
record = GetInput()
Change the value of counter to how many records you want. This takes care of marks to be between 0 and 100 (included) and to be integer. Its better if you implement it with dictionary.
Wouldn't it be better to have name and percentage in one dict?
#function to ask user to input name and score
def GetInput():
name_percentage = {}
for counter in range(0,10):
name = input("Please enter the student's name: ")
valid = False
while not valid:
percentage = int(input("Please enter the student's score %: "))
if percentage < 0 or percentage > 100:
print("Please enter a valid % [0-100]")
else:
valid = True
name_percentage[name] = percentage
return name_percentage
name_percentage = GetInput()
print(name_percentage)
I need to ask a user how many people are booking in , max 8 people then take that amount and ask for user 1 details, user 2 details etc.save details to be printed later.Not sure what to I'm very new to python.
manager_name = raw_input("please enter managers Name: ")
email_address = raw_input("please enter your Email Address: ")
phone_number = raw_input("please enter your Phone number: ")
print("-----------------------------------------------------")
print ("Our Stuido can Accommodate up to max 8 musicians")
print("-----------------------------------------------------")
amount_of_band_members = int(raw_input("please enter the amount of band members"))
values = []
for i in range(amount_of_band_members):
values.append(int(input('Please enter Muscians Names & Insterments: ')))
manager_name = raw_input("please enter managers Name: ")
email_address = raw_input("please enter your Email Address: ")
phone_number = raw_input("please enter your Phone number: ")
print("-----------------------------------------------------")
print ("Our Stuido can Accommodate up to max 8 musicians")
print("-----------------------------------------------------")
amount_of_band_members = int(raw_input("please enter the amount of band members"))
if amount_of_band_members >8:
print ("Sorry we can only Accommodate maxuim 8 Musicians")
else :
print raw_input("please enter musicians and insterments")
while amount_of_band_members <8:
print raw_input("please enter next name")
amount_of_band_members +=1