I'm new to Python, so please bear with me. I'm trying to write a program involving a function that takes a number K as an input, reads K names one at a time, stores them into a list, and then prints them.
Not sure whether or not I should use a "for" or "while" loop, so I'm trying with "while" loop first.
k = input ("How many names?\n")
def names():
lst = []
while True:
name = input("Enter name:")
if = int(k)
break
return lst
names()
What I'm hoping to see is a list of names, and that list would be cut off after K number of names.
I've been receiving this error message:
File "<ipython-input-21-24a26badc1b5>", line 7
if = int(k)
^
SyntaxError: invalid syntax
The difference between while and for loops is thus:
If you want to do something a specific number of times, or once for every element in some collection, use a for loop.
If you want to do something an indefinite number of times, until a certain condition is met, use a while loop.
The way to implement what you want using a for loop is this:
k = input("How many names?\n")
def names():
lst = []
for i in range(int(k)): # creates a list `[0, 1, 2, ..., k-1]` and iterates through it, for `k` total iterations
name = input("Enter name:")
lst.append(name)
return lst
names()
Now, you could do this using a while loop - by setting a variable like x=0 beforehand, and increasing it by one for every iteration until x == k, but that's more verbose and harder to see at a glance than a for loop is.
#Green Cloak Guy explained very well why a for loop would be appropriate for your task. However if you do want to use a while loop you could do something like this:
def get_names(num_names):
names = []
i = 1
while i <= num_names: # equivalent to `for i in range(1, num_names + 1):`
current_name = input(f"Please enter name {i}: ")
names.append(current_name)
i += 1
return names
def main():
num_names = int(input("How many names are to be entered? "))
names = get_names(num_names)
print(f"The names are: {names}")
if __name__ == '__main__':
main()
Example Usage:
How many names are to be entered? 3
Please enter name 1: Adam
Please enter name 2: Bob
Please enter name 3: Charlie
The names are: ['Adam', 'Bob', 'Charlie']
Equality comparisons in Python are done with a
==
You also need some sort of thing to compare int(k) to. If you're trying to count loops you could do something like
x = 0
while True:
name = input("Enter name:")
lst.append(name)
x+= 1
if x== int(k)
break
That's exactly what a for loop is for - looping "for" a certain number of times. A while loop is for indefinite loops where you keep looping until something is no longer true.
Still, it might be instructive to see both, so you can better understand the difference. Here's the for loop. It will loop k times. See the Python wiki for more details.
k = int(input ("How many names?\n"))
def names():
lst = []
for i in range(k):
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
return lst
names()
And here's the same thing as a while loop. The loop continues until the loop condition is not true, so you just need to come up with a conditional that is true for the first k loops, and not thereafter. This will do:
k = int(input ("How many names?\n"))
def names():
lst = []
i = 0
while i < k:
name = input("Enter name:")
lst.append(name) # I'm assuming you want to add each name to the end of lst
i += 1
return lst
names()
Notice how in a while loop you have to initialise and increment the iterator (i) yourself, which is why a for loop is more suitable.
Finally, notice how neither example uses break. break is a fine way to end a loop, but if it's not necessary then you're better off not using it - generally it is only used to end a loop by exception (that is, for some reason that is not the main loop conditional). Using it for normal loop endings leads to less logical code that is harder to follow.
Related
I am trying to make a simple program that uses for loops, if-elif-else statements, and input to take three "employees" salaries and compare them to see if A, any of them have the same salary. Or B if non of them have the same salary. So far, this is what I got but both strategies I've tried haven't been successful and I don't understand why :(. All help is appreciated, and spare me for I'm still new to coding and I'm trying to teach myself through these exercises. Thank you kindly!
salarylist = []
salarylist = list(map(int, salarylist))
maxLengthList = 3
while len(salarylist) < maxLengthList:
salary_of_employee = int(input("Enter your salary: "))
salarylist.append(salary_of_employee)
print("salary of employees are:\n")
print(type(salarylist))
print(salarylist)
print(type(salarylist))
x = salarylist
if salary_of_employee == salarylist[x]:
print(f"these are the same salary.{salary_of_employee} and {salarylist[x]}")
else:
print('non of the salaries are the same.')
############################################################################
empOne = salarylist[0]
empTwo = salarylist[1]
empThree = salarylist[2]
if empOne == salarylist[0]:
print("these are the same salary.")
elif empTwo == salarylist[1]:
print('these are the same salary')
elif empThree == salarylist[2]:
print('these are the same salary')
else:
print('non of the salaries are the same.')
I have tried running your code and it gives a horrible error.
I clearly understood your desire. Most of your logic don't meet it.
So I decided to RE-Code everything based upon your requirements {for loops, if, elif, else statement, 3 employees etc..}
MAX_LEN = 3
COUNTER = 1
LIST_SAL = []
while MAX_LEN >= COUNTER:
ASK_SAL = int(input('Enter your salary :'))
LIST_SAL.append(ASK_SAL)
COUNTER+=1
print(LIST_SAL)
for check in LIST_SAL:
if LIST_SAL.count(check)>1:
print('Same salaries presented in the list')
break
else:
print('Salaries of employees are unique!')
break
Okay so ..
I created a variable max_len = 3 which is the total number of employees and then I initiated the variable COUNTER to 1 so that it iterates in the while loop and gets incremented by 1 each time.
Therafter a variable named ask_sal asks the user for salaries {3 times} and appends each input to the LIST_SAL variable {a list}. And then I printed the list for visualisation.
There after I accessed the elements in the list {list_sal} by a for loop with the variable check which looks for the number of time an element repeats in the list all by the help of count() function Which, IF greater then one prints "SAME salaries presented" OR else prints "Unique salary"..
You might be wondering why have I used 2 break statements..
Well they are used to break the further iteration as the if or else condition are met in the first iteration.
If you try removing the break statements, the print function will work the number of times the same salaries occur in the list.
Hope I helped you.. I am too , a newbie in programming yet I love it and practice a lot .
Keep grinding and Working hard
When you have the list of salaries, create a set from that list and compare the length, if same length then salaries will be unique, otherwise there will be at least one common salary
lst2 = set(salarylist)
if(len(lst2) == len(salarylist)):
print("Non of the salaries are the same.")
else:
print("Same salaries found")
To find the same salaries loop through the the set and check count of elements in the list, if greater than one, then duplicate.
for sal in lst2:
if(salarylist.count(sal) > 1):
print("Duplicate here")
so, I came across this question, where I have to create a list, take the elements as input from the user. After doing so, I have to check whether the elements entered by the user are 'Unique' or 'Duplicate', and this has to be done while the program is running. i.e if the input entered is duplicate, then I have to terminate the program then and there, otherwise proceed.
I have written the following code (Python):
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0,num):
q = int(input('element %d: '%(i+1)))
list.append(q)
print(list)
cnt = 0
for i in range(0,num):
if(list[i]==q):
cnt = cnt+1
if(cnt>1):
print('Duplicate')
else:
cnt = cnt+0
if(cnt==0):
print('Unique')
print('\nProgram Terminated!')
The thing is that, I know that I might have to use the break statement in the loop where I check whether the values are equal, but I somehow can't place it correctly.
Thank you! :)
If you want to check each time the user puts in a new element, i think this is the solution to your question:
list = []
num = int(input('enter no. of elements in list: '))
for i in range(0, num):
q = int(input('element %d: ' % (i+1)))
if q not in list:
print('Unique')
list.append(q)
else:
print('Duplicate')
break
print(list)
print('\nProgram Terminated!')
I'm trying to code a calculator with several options, just for the leraning experience, and one of these options is 'average', I want the user to be able to input as many values as he wants to, but it's not working yet, what should I change?
This is my code for the average so far:
elif ui1 == subop1_2:
1 = [input("Input your values, separate with a comma").split(',')]
result = sum(1) / float(len(1))
print("The average is {}".format(result))
time.sleep(10)
Since there were a lot of things pointed out, here goes an answer.
num_list = input("Input your values, separate with a comma: ").split(',')
num_list = [float(elem) for elem in num_list]
result = sum(num_list) / float(len(num_list))
This will fail if the user enters an empty string or characters...
Every thing you wrote was perfectly fine except a few mistakes...
1) Change all 1s to a valid variable name. Lets say, a.
2) Remove the square brackets around the input() function
3) Add a this line before the line where you assign the variable, result.
a = [int(x) for x in a]
Here is the code,
a = input("Input your values, separate with a comma").split(',')
a = [int(x) for x in a]
result = sum(a) / float(len(a))
print("The average is {}".format(result))
first of all u cannot name a variable:1 change that to "a" or something and it should work out
I would do it like this:
inp = input("Input your values, separate with a comma")
values = list(map(float,inp.split(',')))
avg = sum(values)/len(values)
print("The average is {}".format(avg))
I'm a beginner and taking an intro Python course. The first part of my lab assignment asks me to create a list with numbers entered by the user. I'm a little confused. I read some other posts here that suggest using "a = [int(x) for x in input().split()]" but I'm not sure how to use it or why, for that matter. The code I wrote before based on the things I've read in my textbook is the following:
while True:
num = int(input('Input a score (-99 terminates): '))
if num == -99:
break
Here's the problem from the professor:
Your first task here is to input score values to a list called scores and you
will do this with a while loop. That is, prompt user to enter value for scores
(integers) and keep on doing this until user enters the value of -99.
Each time you enter a value you will add the score entered to list scores. The
terminating value of -99 is not added to the list
Hence the list scores should be initialized as an empty list first using the
statement:
scores = []
Once you finish enter the values for the list, define and called a find called
print_scores() that will accept the list and then print each value in the list in
one line separate by space.
You should use a for-loop to print the values of the list.
So yeah, you want to continually loop a scan, asking for input, and check the input every time. If it's -99, then break. If its not, append it to the list. Then pass that to the print function
def print_list(l):
for num in l:
print(num, ' ', end='')
l = []
while True:
s = scan("enter some number (-99 to quit)")
if s == "-99":
break
l.append(int(s))
print_list(l)
the print(num, ' ', end='') is saying "print num, a space, and not a newline"
I think this will do the job:
def print_scores(scores):
for score in scores:
print(str(score), end = " ")
print("\n")
scores = []
while True:
num = int(input('Input a score (-99 terminates)'))
if num == -99:
break
scores.append(num)
print_scores(scores)
scores = [] creates an empty array and scores.append() adds the element to the list.
print() will take end = ' ' so that it separates each result with a space instead of a newline (\n') all while conforming to the requirement to use a loop for in the assignment. str(score) ensures the integer is seen as a string, but it's superfluous here.
This is actually not an elegant way to print the scores, but the teacher probably wanted to not rush things.
I'm trying to make a simple program that will take all of your lottery numbers, and compare them (using set intersect) with the winning numbers that you input.
I've gotten the groundwork laid where you enter your numbers, it gets submitted to a sublist, which will then be converted into five separate sets, which will be used to compare. However, when you run the script, the while loop will not break when the length of the list is 5 (this is the goal).
Can someone explain what I'm doing wrong? Or maybe even a better way of working this whole program. I'm relatively new to the world of Python, I'm just diving in, and trying to make this program work.
# Start Program
def set_convert(list):
conversion = set(list)
return conversion
def comparison(winning_numbers, my_numbers):
pass
def main():
print('Welcome to the Lottery Checker v1.0!')
winning_numbers = [int(x) for x in input('Enter the winning numbers(Sep w/ Spaces): ').split()]
winning_set = set_convert(winning_numbers)
my_numbers = []
while True:
numbers = [int(x) for x in input('Enter your numbers(Sep w/ Spaces Max: 5): ').split()]
if len(numbers) == 6:
my_numbers.append(numbers)
print('Added! Want to add more?')
elif len(my_numbers) == 5:
break
else:
pass
else:
pass
print('Here are your numbers: {}. Good luck! :-)'.format(my_numbers))
main()
Replace
elif len(my_numbers) == 5:
with
elif len(numbers) == 5:
Also, it is advisable that you don't use the keyword list as an argument for the function set_convert. Rather, define it as:
def set_convert(mylist):
conversion = set(mylist)
return conversion
And finally, you don't need to pass in my_numbers and winning_numbers into the function comparison as arguments since they are available in the outer scope.