I wanted to get some user input on a seat number on a train I wanted the program to check if the seat is valid( ie more than available seats. Eg: inputted seat: 101, seat limit: 100 ). If the seat no. is valid I want the program to continue and if invalid to ask again for the seat number.
import sys
seat = int(input("Seat Number: ")) # The seat number inputted by the user
if seat > 100:
print("Seat limit exceeded")
# restart?
If the seat is more than 100 I want the program to ask again for a seat no.
You can reverse the logic, use an infinite loop, and break when a valid seat number is inputted (ie, keep asking for input and stop when given a valid one):
while True: # infinite loop
seat = int(input("Seat Number: ")) # The seat number inputted by the user
if seat <= 100:
break
print("Seat limit exceeded")
# code to be executed after a valid input is given
while True:
seat = int(input("Seat Number: "))
if seat > 100:
print("Seat limit exceeded, choose another one")
else:
print("Seat is valid")
break
output:
Seat Number: 110
Seat limit exceeded, choose another one
Seat Number: 45
Seat is valid
Process finished with exit code 0
seat = int(input("Seat Number: "))
while(seat < 0 or seat > 100):
print('Invalid seat Number')
seat = int(input("Seat Number: "))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.