I know that there is another answer to this but that's for complex users. I'm a basic python user who started a couple of days ago. So I need a simple answer
Im trying to understand this line of code. Mostly the enumerate part. Could someone please what enumerate does.
f = open("solutions.txt", "r")
searchlines = f.readlines()
for i, line in enumerate(searchlines):
Thanks in Advance
enumerate is used to generate a line index, the i variable, together with the line string, which is the i-th line in the text file. Getting an index from an iterable is such a common idiom on any iterable that enumerate provides an elegant way to do this. You could, of course, just initialize an integer counter i and increment it after each line is read, but enumerate does that for you. The main advantage is code readability: the i variable initialization and increment statements would be book-keeping code that is not strictly necessary to show the intent of what that loop is trying to do. Python excels at revealing the business-logic of code being concise and to the point.
You can look at Raymond Hettinger's presentation to learn more about idiomatic python from these excellent notes.
Related
This question already has answers here:
Sum a list of numbers in Python
(26 answers)
Closed last month.
I have been stuck trying to write code that will dynamically take user input from a list and preform general arithmetic operators. In order to work around this I used indexing and slicing which did solve my problem temporarily but a new problem rose from doing this.
listgrades= []
num_students = int(input("How many students are you evaluating?"))
def student_info():
for i in range(0, num_students):
student_name=input("Enter your name here: ")
studnet_age=input("Enter your age here: ")
student_total_grade=int(float(input("What is your total grade")))
listgrades.append(student_total_grade)
student_info()
grades_sum= (listgrades[0] + listgrades[1] + listgrades[2]) / num_students
print(f"The average of all the student grades is {grades_sum}")
`
I'm trying to change the (listgrades[0] + listgrades[1] + listgrades[2]) to something more changeable, workable and scalable
I was trying to look and find a solution or a way to work around this but I hit a dead end and I ran out of ideas at this point.
I think a loop of some sorts might work for this but I'm not sure.
side note: I kinda looked into numpy and I can't use it since my school lab computers won't allow anything out of the default python module library.
I have some general advice and some specific suggestions.
For general advice, to see what built in methods are available is to use python itself.
At the command line type python3
then, within python type dir(list)
and you will see the available methods for lists.
You get more detailed information about any specific method by typing help and the class you are interested in followed by a dot, than the method name. For example help(list.count).
You can also type help(list) to get a more in depth list of all the functions and instructions for use. Type space to continue to the next screen, and b to backup a screen. Type q to end the help screens.
To exit python type exit()
More specifically, I agree that a loop would be a more dynamic direction to go, given you are asking how many students to evaluate in your input.
One way to loop through your list would be:
for x in listgrades:
sum = sum + x
Of course, you can perform other math operations inside the loop, or in similar loops. Presumably you will initialize your value before the loop.
At some point you may need to count how many grades are in your list. Fortunately, there's a built-in method for lists that gives you that information called count. You'll see this if you use python's dir(list) or help(list).
number_of_grades = listgrades.count
I think this will point you in the direction you were thinking with the code, without giving away much in exactly how, which is what you are learning. Best of luck!
hey everyone I need your help for my programming course, I am pursuing my undergraduate degree in psychology.
The question is:
The python application you will develop will receive the mathematical operation that the user wants to calculate and print the result on the screen.
This process will continue until the user enter "Done".
The application will terminate when the user enters the end.
Conditions and restructions:
1)you will operate with positive integers
2)only 4 operations will be used
3)remember the priority of the operation
4)you will use "*" as a cross
5)no brackets will be used
6)it is forbiddento use an external module
7)you are not responsible for the user's incorrect entries
8)bulit-in functions you can only use the following:
int
float
range
print
input
len
str
max
min
you can use all functions of list and str data structure.
there are some things to be considered:
since you write, no modules are allowed, I assume, this should only run in the CLI. This will make the exercise incredibly easier, since GUI and Python are a Love-Hate-Realionship of its own.
Assuming I understood your assign right, the user will type a list of expressions like "1*2+3/4-5" for example, typing "Done" will indicate, that these should processed and the result should be printed, right? If the User types end, the script will stop working.
Also, you will only have to handle positives, this also, and the fact that you don't have to validate the user entries, makes it very easy. I won't give you a full solution, since you should learn something with this assignment, but here are some hints, that may nudge you in the right direction.
Hints:
The input will be in a string, so handling strings will be a main task. You should look up the documentation to know, in what ways you can manipulate strings. Also have a closer look at helper functions like split, if you have the word Done more than one time in the string.
Strings are in fact just lists of letters, punctuation and numbers.
Since strings are just a list, you won't have a neatly stored 22 in there, it will be a [2][2] surrounded by an operation or the words Done or end. You will have to go through your string, break it up in smaller parts, and then from there on, call functions to do whatever there is to do.
Keep in mind, that there are literally millions of ways to achieve what you have to do, if you aren't familiar with programming, keep it simple, break it up in smaller steps and then just proceed through the exercise.
Hope this will help you. If it helped you or gave you a hint in the right direction, I would appreciate an upvote.
Have fun coding.
As you probably already figured by my question, I am pretty new to programming which is why this question is so basic. But I couldn't really find a question that had an answer to my problem so I thought I might just ask. I have a list that contains integers that I wanted to compare to each other so they can be sorted from highest to lowest. Now for that I wanted to use a for-loop that is executed exactly as many times as there are integers in my list. How do I do that? I tried:
for len(a): # (a is my list)
*code*
Thought it is returning me an error, saying that it couldn't be assigned to the function call. I am not sure why :/ . I hope you can help me.
for i in range(len(a)):
is the usual way; the official Python tutorial is a good place to start for understanding range(), and the fact that the loop is executed as many times as there are elements in your list when you first entered the loop
python_code
I want to take all inputs and convert them into list of lists. But this program is not taking all inputs as intended. I may have made a basic mistake but I couldn't get my head around it
Try using readline() rather than input() at every step from start. Because I don't see any problem in the loop, my best guess is because you are using input() you are not reading escape characters which are there in these kind of inputs.
Well, we got parables exam preparations and instead of me typing everything a million times, I thought of rather making a little Python script. It's done, but something's bugged. I've been stuck on it for around 30 minutes and just can't figure it out as my Python is a bit rusty.
You can find my code at: https://repl.it/#Rrrei/CurvySecondaryService
As mentioned before, for x in x: is indeed bad naming :p. You can easily get confused about what x you are talking about, the inner or the outer one.
Also a = input(..) makes a a string, a string multiplied by a number repeats the string in Python. e.g.:
'1'*5 == '11111'
To solve this, wrap input in a int: a=int(input(...))
You are going to append the string values. Python is not typesafe and a is a string after calling input()...
Here you can see a safe example with corrected values and better names (cleancode).
check my code
It´s the correct version of yours.
If you want the same form b=0 c=0....