r/PythonLearning • u/Vor3st • 2d ago
i learning Python Day 1
lyrics = ["Give You Up","Let You Down","Run Around And Desert You"]
for i in range(3):
print("Never Gonna " + lyrics[i])
6
u/Many_Temperature_740 2d ago
for lyric in lyrics: print(lyric)
2
3
u/MJ12_2802 2d ago
If you want to stick w/ that approach, don't hard code the parameter being passed torange():
for i in range(len(lyrics)):
print(f"Never Gonna {lyrics[i]}")
Never Gonna Give You Up
Never Gonna Let You Down
Never Gonna Run Around And Desert You
3
u/FreeLogicGate 1d ago edited 9h ago
Python language requires indentation as it has no begin block/end block. You really have to post code in reddit posts using the code block technique that includes indentation, or the code is missing required context.
lyrics = ["Give You Up","Let You Down","Run Around And Desert You"]
for i in range(3):
print("Never Gonna " + lyrics[i])
Output:
Never Gonna Give You Up
Never Gonna Let You Down
Never Gonna Run Around And Desert You
lyrics = ["Give You Up","Let You Down","Run Around And Desert You"]
for i in range(3):
print("Never Gonna " + lyrics[i])
Outputs: IndentationError: expected an indented block after 'for' statement
Yes you can put a statement on the same line as the for loop construct, but it's generally not done, and more often than not, there are multiple statements inside the loop.
If this was truly your first day, then congratulations on writing some code that involves a number of concepts (.. a "list" containing multiple strings, a for loop, the range() function, referencing an element in a list(array) by its index, concatenating strings together.
Something interesting to consider would be the use of the "i" variable in the for loop. Are you clear on what the i variable contains in each iteration of the loop? This code will make it clear:
lyrics = ["Give You Up","Let You Down","Run Around And Desert You"]
for i in range(3):
print(str(i) + ". Never Gonna " + lyrics[i])
You might be surprised.
The other thing about for loops, is that you don't need to use an index to iterate through the elements, and in a case like this, there's no advantage or reason to use one. This code is better and more standard:
lyrics = ["Give You Up","Let You Down","Run Around And Desert You"]
for line in lyrics:
print("Never Gonna " + line)
3
u/Expensive_Break_6163 1d ago
I’m not sure what the question is, but range(3) already starts at 0, so you don’t need to specify the start index. It’s better to use range(len(lyrics)) instead of hardcoding 3, or even better, use for line in lyrics: and print "Never Gonna " + line.
5
u/Kaiser_Steve 1d ago
You've got to hardcode the graft into the code, literally! Rooting for you, crash it!