How to combine str and int variables? - python

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'])

Related

How to call upon values in a nested loop?

I'm working on my first exam for my programming class. I can't figure out how to call upon and sum the values of a given index in a nested loop. I need to sum the wage of each employee together as well as the hours of each employee together. These values are nested as [record] in [employee_records], as index 2 and 3, respectively. Any help would be greatly appreciated!
here's the error I'm getting:
line 54, in <module>
for y in record[2]:
TypeError: 'float' object is not iterable
code is as follows:
num_employees = int(input("Enter number of salespersons to be evaluated: "))
numNums = num_employees
employee_records = []
wage = None
lrange = [1, 2, 3, 4]
while num_employees > 0:
record = []
name = (input("Enter employee name: "))
try:
level = int(input("Enter this employee's level: "))
if level not in lrange:
print("Employee level must be from 1 to 4. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
except ValueError:
print("Employee level must be from 1 to 4. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
try:
hours = float(input("Enter hours worked by this employee: "))
except ValueError:
print("Entry must be a number. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
try:
sales = float(input("Enter revenue generated by this employee: "))
except ValueError:
print("Entry must be a number. Please re-enter employee's name.")
if numNums < num_employees:
num_employees += 1
continue
num_employees -= 1
record.append(name.capitalize())
record.append(level)
record.append(hours)
record.append("${:,.2f}".format(sales))
employee_records.append(record)
print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
for y in record[2]:
totalhours += y
for y in record[3]:
totalsales += y
print(totalhours)
print(totalsales)
You don't need a nested loop. Just use the fields directly. However, you should NOT be formatting the sales as a string. You need the raw number in order to do math. Format it when you print it, not before.
record.append(name.capitalize())
record.append(level)
record.append(hours)
record.append(sales)
employee_records.append(record)
print(employee_records)
totalsales = None
totalhours = None
for x in employee_records:
totalhours += record[2]
totalsales += record[3]
print(totalhours)
print(totalsales)

Bank system with accounts that use dictionary to store it but it only reads the first account

I'm creating a bank system with accounts but if I put 2 accounts or more the 2nd account can't be read and doesn't work in logging in only the first one that works
accounts = []
names = [item.get('fullname') for item in accounts]
customers = int(input("Number of customers: "))
while customers != 0:
fullname = str(input("Input Fullname: "))
while fullname in names:
print('Name already exist')
fullname = str(input("Input Fullname: "))
else:
pass
pins = str(input("Please input pin of your choice: "))
while len(pins) != 4:
print ('Error. Only 4 digit allowed')
pins = str(input("Please input pin of your choice: "))
else:
pass
balance = int(input("Please input a value of deposit to start and account: "))
account = [{"fullname": fullname, "pins": pins, "balance": balance}]
accounts1 = account.copy()
accounts.append(accounts1)
print(accounts)
customers -= 1
for i in range (len (accounts)):
if name == accounts[i]['fullname'] and pin == accounts[i]['pins']:
print('Your current balance is {} PHP'.format(accounts[i]['balance']))
else:
print("Account not found")
break
I think it's because the array will have double bracket after appending
The original code had multiple errors including a wrong indentation and the missing but referenced names list.
One - at least kind of okayish working - solution based on your code is:
accounts = []
names = [] # add the names list
customers = int(input("Number of customers: "))
while len(accounts) != customers:
fullname = str(input("Input Fullname: "))
while fullname in names:
print('Name already exist')
fullname = str(input("Input Fullname: "))
else:
pass
pins = str(input("Please input pin of your choice: "))
while len(pins) != 4:
print('Error. Only 4 digit allowed')
pins = str(input("Please input pin of your choice: "))
else:
pass
balance = int(
input("Please input a value of deposit to start and account: "))
account = {"fullname": fullname, "pins": pins, "balance": balance}
accounts.append(account)
names.append(fullname)
print(accounts)
# Authenticate before staring the loop
name = str(input("Authenticate: Input your full name: "))
pin = str(input("Authenticate: Input your pin: "))
balance = None
for account in accounts:
if name == account['fullname'] and pin == account['pins']:
balance = account['balance']
break
if balance == None:
# then we had no match - otherwise it should be some integer
print("Account not found")
else:
print('Your current balance is {} PHP'.format(balance))

Appending to list produces None

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)

Python: Returning array values from a function

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)

How do i print certain items in a list based on user input in python?

So far the user is supposed to enter their name account number and balance which gets put into list. then I ask for them to input their account number and im supposed to print out their specific number from the list instead of the whole list but cant get it to work.
customers = list()
acctnum = list()
balance= list()
count = 0
while count != 2:
name = input("Enter your name: ")
customers.append(name)
num = int(input("Enter account number: "))
acctnum.append(num)
bal = input("Enter Current Balance:$ ")
print()
balance.append(bal)
count = count + 1
print(customers)
print(acctnum)
print(balance)
personal = int(input("Enter account number: "))
print(personal)
if personal in acctnum:
print(acctnum)
I find dictionaries are useful in applications like this:
accounts = {}
for x in range(2):
name = input("Enter your name: ")
num = int(input("Enter account number: "))
bal = input("Enter Current Balance: $")
accounts[num] = {"name": name, "balance": bal}
print()
for k, v in accounts.items():
print(v["name"] + "'s account " + str(k) + " has $" + v["balance"])
personal = int(input("Enter account number: "))
if personal in accounts:
print("Hello, " + accounts[personal]["name"] + " you have $" + accounts[personal]["balance"])
The data right now is stored in independent lists. You would have to implement using an associative data type such as dictionaries (that are implemented in Python).

Categories

Resources