This is my first post here, and I'm a bit lost on this scenario since I'm new to loops. I'm being asked to write a program that takes an integer input, and uses that input to print out the corresponding values on a CSV/Excel list. I was able to get to a point where it printed both the names and values based on the input, but the formatting is not the right way I need it to be, and my script is a bit clunky.
Specifically, I have to print states and populations. If I put in 5, it will print out both the names and populations from 0 to 5.
I can't use Pandas, as I'm still a beginner, and this is for a course.
This is where I am.
print('Give me a number thats 0 - 50:')
user_num = int(input())
for name in state_names:
if name == state_names[user_num]:
names = state_names[0:user_num]
for pop in state_populations:
if pop == state_populations[user_num]:
pops = state_populations[0:user_num]
print(f'{names}, {pops}')
If the input was 3, the output comes out to:
['Michigan', 'Georgia', 'Ohio'], [9986857, 10617423, 11689100]
instead of
Michigan 9986857
Georgia 10617423
Ohio 11689100
which is the output I need.
What can I do to shorten it and make it produce that output?
If I understand you correctly you can use zip() function:
state_names = ['Michigan', 'Georgia', 'Ohio', 'New York']
state_populations = [9986857, 10617423, 11689100, 99999]
print('Give me a number:')
user_num = int(input())
for n, p in zip(state_names[:user_num], state_populations[:user_num]):
print(f'{n:<10} {p:>10}')
Prints:
Give me a number:
3
Michigan 9986857
Georgia 10617423
Ohio 11689100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With