I'm very new to Python and I've made a program which asks a user to select 2 numbers. The first must be between 1 and 10 and the second must be between 100 and 200. The program then asks the user to select a 3rd number between 1 and 5. Call these 3 numbers X, Y, and Z respectively The program then counts from X to Y in steps of Z.
Expected behaviour: If the user chose 10, 105, and 5, then Python should print 15, 20, 25, and so on, up to 105. Also, if the user tries to enter a value outside of those specified by the program, it will reject the input and ask the user to try again.
The program works but, like I said, I'm very new to Python so I would be very surprised if I've done it in the most optimal way. Do you think there's anyway to simplify the below code to make it more efficient?
Here's the code:
x = int(input("Please enter any number between 1 and 10: ").strip())
while x > 10 or x < 1:
print("No! I need a number between 1 and 10.")
x = int(input("Please enter any number between 1 and 10: ").strip())
y = int(input("Now enter a second number between 100 and 200: ").strip())
while y > 200 or y < 100:
print("No! I need a number between 100 and 200.")
y = int(input("Please enter any number between 100 and 200: ").strip())
print("Now we're going to count up from the first to the second number.")
print("You can count every number, every second number, and so on. It's up to you.")
z = int(input("Enter a number between 1 and 5: ").strip())
while z > 5 or z < 1:
print("No. I need a number between 1 and 5!")
z = int(input("Enter a number between 1 and 5: ").strip())
print("You have chosen to count from {} to {} in steps of {}.".format(x, y, z))
input("\nPress Enter to begin")
for q in range(x,y):
if q == x + z:
print(q)
x = x + z
The program works, but my gut instinct is telling me there must be a cleaner way to do this. Any suggestions you may have would be massively appreciated.
Cheers!
You can replace the loop with:
for q in range(x,y,z):
print(q)
Adding the third parameter to the range expression causes it to count up in steps.