0

In my code I have variables e.g Up1, Up2 .....so on. It is related to buying tickets for train. The user inputs the time in form of integers as seen below but not full time in form of (hh:mm) I want python to take integer input from user, attach it with string 'Up'(and here the integer) to create the variable mentioned above e.g. Up9 for 9:00 Now python needs to find the number of seats for that particular train and compare if the number of seats entered by user is within the available range of seats. However in the line (while Tickets_to_buy > Uptime_:) the Uptime_ is a string and python rejects it. How to convert this str(Uptime_) to a variable name so rather than str(Up9) it will become a variable (Up9) and python fetches its value to compare it with other variable ...

Uptime = int(input('''Please enter the time of uptime from below:
    9 for 09:00
    1 for 11:00
    3 for 03:00
    5 for 15:00'''))
Downtime = int(input('''Please enter the time of downtime from below:
    0 for 10:00
    2 for 12:00
    4 for 14:00
    6 for 16:00'''))

Uptime_ = ('UP' + str(Uptime))

Tickets_to_buy = 0

while Tickets_to_buy > Uptime_:
    Tickets_to_buy = int(input('Please enter number of tickets you would like to buy. It should be less than', Uptime_)) 
  • As opposed to what your title says, use a dict! `vals = {"UP9: }` and then: `Uptime_= vals[f"UP{Uptime}"]` – Tomerikoo Feb 23 '21 at 15:40

1 Answers1

0

Not sure why you don't like dictionaries ... but you could also use tuples here:

You have variables now:

UP1 = varFor1
UP9 = varFor9

instead make that a tuple to correlates directly to your user input:

varList = ((9, varFor9), (1, varFor1))

In your code, now, you just change how you set Uptime_ to:

for each in varList:
     if each[0] = Uptime:
          Uptime_ = each[1]

That being said, if you set your variable outputs into a dictionary:

varList = { 9 : "varFor9", 1 : "varFor1" }

You can do the same thing, but assign Uptime_ in a single line still:

Uptime_ = varList[Uptime]

And, whenever you're working with user input, you might want to put a try/except around where you're trying to enact their inputs in case the fat finger or put in a value you didn't want/expect.

Kyle Hurst
  • 252
  • 2
  • 6
  • The problem for me is that i have never practiced any code with dictionaries. Moreover i do not know what to change in my code to create and utilize a dictionary. Still due to your emphasize on dictionaries i will learn it soon. Thanks for help. –  Feb 23 '21 at 16:27
  • I was also intimidated by dictionaries, but now they are super useful. Stackoverflow is very helpful in finding ways to access and utilize them. Good luck with your project! – Kyle Hurst Feb 23 '21 at 16:38