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.
Related
i create a program that reads a sequence of numbers, determines how many different numbers there are (we count the repetitions once), and writes the result to the standard output.
my first code:
f=int(input("String of numbers: "))
l=[]
for x in range(f):
string_numbers = int(input(f'Enter {x+1} string of numbers: '))
l.append(string_numbers)
mylist = list(dict.fromkeys(l))
print(len(mylist))
I wanted to take into account if the user entered a string too short or too long than declared. I wanted the user to type everything on one line. When I enter an incorrect string number, I get duplicated "incorrect string lengthincorrect string length"
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
if i < l:
print("incorrect string length", end='')
elif i > l:
print("incorrect string length", end='')
else:
It seems like you're mixing up your different variables -- f is what you want the length to be, l is just the number 2, and the way you're comparing those two has nothing to do with the actual input entered by the user, which is my_list.
Using variable names that indicate their meaning might make it easier to keep it all straight:
num_count = int(input("Length of string of numbers: "))
num_list = input('Enter numbers in the string, separated by spaces: ').split()
if len(num_list) == num_count:
print(f"there are {len(set(num_list))} different numbers")
else:
print("incorrect string length")
In the above code, num_count is the count of how many (non-unique) numbers you expect them to input, and num_list is the actual list. To figure out if the list is the expected length, compare num_count to len(num_list).
Note that since all you're doing is looking for unique values, converting the strings in num_list to int is not necessary (whether or not you use a set as I've done here).
You will most likely be better off using another function that ultimately has a while loop. This will make sure that when the user is giving the input that if anything is malformed you can then parse it checking and finally making sure to prompt the user again.
For example:
f=int(input("String of numbers: "))
my_list = input('Enter numbers in the string, separated by spaces: ').split()
list_of_integers=[]
l=len(str(list_of_integers))
for i in my_list:
list_of_integers.append((i))
mylist = list(dict.fromkeys(list_of_integers))
for i in range(f):
# XXX Here call your "input-function"
get_user_input(i, l)
def get_user_input(user_len, len):
while True user_len != len:
print('Incorrect Input')
user_len = int(input("String of numbers: "))
return
This is not exactly a working example but with what you have you get the idea that you want to do a while loop until your inputs match.
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 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.
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))
Sorry...I'm kind of a programming noob. I was looking at some problem sets online and I found THIS ONE. I wrote this much:
import random
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
(f,g,h,i,j)=x=input("Your 5 Chosen Numbers:")
My problem is that I don't know how to make the program print something like "Please enter 5 numbers separated by only a comma" if more or less than five are entered. Also how would I do that if I wanted it to display a different message every other time they made that mistake?
Try this approach:
input_is_valid = False
while not input_is_valid:
comma_separated_numbers = raw_input("Please enter a list of 5 numbers,separated by commas: ")
numbers = [int(x.strip()) for x in comma_separated_numbers.split(",")]
if len(numbers) != 5:
print "Please enter exactly 5 numbers"
else:
input_is_valid = True
Looking at your link I'd say:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
other_numbers = sorted(ri(1,53) for i in range(5))
print 'your numbers:','\t',other_numbers,'\t','powerball:','\t',powerball
It seems that's more or less what he asks from you.
If I'm correct, you want the user to submit his series so to see if its one of the sets extracted (amirite?)
then it could be fine to do:
import random
while True:
sets = input('how many sets? ')
if type(sets) == int:
break
else:
pass
while True:
myset = raw_input('your 5 numbers:').split()
if len(myset) != 5:
print "just five numbers separated ny a space character!"
else:
myset = sorted(int(i) for i in myset)
break
for i in range(sets):
ri = random.randint
powerball = ri(1,42)
numbers = sorted(ri(1,53) for i in range(5))
print 'numbers:','\t',numbers,'\t','powerball:','\t',powerball
if numbers == myset:
print "you won!" ##or whatever the game is about
else:
print "ahah you loser"
EDIT: beware this doesn't check on random generated numbers. So it happens one number can appear more than once in the same sequence. To practice you may try avoiding this behavior, doing so with a slow pace learning some python in the way it could be:
make a set out of a copy of the list "numbers" -- use set()
if its length is less than 5, generate another number
check if the new number is in the list
if it is, then append it to the list. if its not unique yet, GOTO point 1 :-)
sort the whole thing again
there you go
happy reading the docs!
My proposition:
import random
import sys
powerball=random.randint(1,42)
a=random.randint(1,53)
b=random.randint(1,53)
c=random.randint(1,53)
d=random.randint(1,53)
e=random.randint(1,53)
bla = ["\nPlease enter 5 numbers separated by only a comma : ",
"\nPlease, I need 5 numbers separated by only a comma : ",
"\nPLEASE, 5 numbers exactly : ",
"\nOh gasp ! I said 5 numbers, no more nor less : ",
"\n! By jove, do you know what 5 is ? : ",
"\n==> I warn you, I am on the point to go off : "]
i = 0
while i<len(bla):
x = raw_input(warn + bla[i])
try:
x = map(int, x.split(','))
if len(x)==5:
break
i += 1
except:
print "\nTake care to type nothing else than numbers separated by only one comma.",
else:
sys.exit("You wanted it; I go out to drink a beer : ")
(f,g,h,i,j)=x
print f,g,h,j,i
.
Some explanation:
.
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. A continue statement executed in the first suite skips the rest of the suite and continues with the next item, or with the else clause if there was no next item.
http://docs.python.org/reference/compound_stmts.html#index-801
.
.
x = map(int, x.split(','))
means that the function int() is applied to each element of the iterable which is the second argument.
Here the iterable is the list x.split(',')
Hence, x is a list of 5 integers
In Python 3, there is no more raw_input() , it has been replaced by input() that receives characters, as raw_input() in Python 2.
.
.