new - 1 month ago 5x
Python Question

# How do I subtract from an array and an user input?

I'm using Grok Learning for this code. I have to do something like:

Weather report

Write a program that asks the user when it rained this week, and then tells them how many days were rain free.

An interaction with your program should look like this:

Which days had rain? Monday Tuesday Wednesday

Number of days without rain: 4

Or like this:

Which days had rain? Thurs

Number of days without rain: 6

You don't need to check whether the user's input makes sense (i.e. whether they have entered valid days of the week).

This is my current code:

``````day = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
day1 = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
days = input("Which days had rain? ")
for days in day:
count = days - day
print("Number of days without rain: " + str(len(day)) + count)
``````

I'm not sure how this will work, because I want to minus the 'day' with 'days' and print out how much is left as an integer. I'm confused. Please help! Thank you!

Answer

Your first problem is that when you ask the user for input, you are going to get a string. So, if you input something like this: Monday Tuesday hotdog, then your days variable will look like this:

`"Monday Tuesday hotdog"`

So, as you said, you don't care what the input is, as long as you can get how many days. Which implies a number. Therefore, you want to get the length of that string. Or in other words, how many words in the string. Which you can simply get like this:

``````len(days.split())
``````

So, now you have how many days. All you have to do is simply subtract:

``````7 - len(days.split())
``````

So, your code can simply be made as such:

``````days = input("Which days had rain? ")
print("Number of days without rain: {}".format(7 - len(days.split())))
``````

Demo:

``````Which days had rain? m w f s
Number of days without rain: 3
``````

Or:

``````Which days had rain? Monday Thursday
Number of days without rain: 5
``````
Comments