Try / Except, back to try - python-3.x

I have this code
def ID():
ID = input("Enter ID: ")
try:
int(ID)
print("Good ID")
except ValueError:
print("Not a string")
ID()
how can I do to try again to input the ID without restarting the code?

You could use a while loop. There are several ways. Here is one:
def ID():
goodID = False
while not goodID:
ID = input("Enter ID: ")
try:
int(ID)
print("Good ID")
goodID = True
except ValueError:
print("Not a string") # do you mean int??
ID()
I would suggest to read also this.

Related

i want to print dictionary keys and values separately with given string in python for my project

I'm not able to finish the project given below if someone help me with the particular function paasenger_login ...help me out
The project is flight reservation system with basic pyhton programming
a. Passenger
1. sign in
2.check availability and fare
3.book ticket
b. Cashier
1.approve
2.issue ticket
the code is below
s=[]
class passenger:
pass
class book:
d={}
f={}
pact=1-000-000
new=0
class cashier:
def caslogin():
while True:
print("\t1.Filling Tickets\n\t2.passenger Info\n\t3.Approve Tickets\n\t4.Logout")
x=input()
if x=='1':
if (book.new==0):
flight=int(input("Enter the no of flights: "))
for i in range(flight):
print("Enter name of the flights: ")
q=input()
print("Enter the price for to travel:\n")
op=[]
op.append(input())
book.d[q]=op
print("Successfully loaded:\n")
book.new=1
else:
print("\n\tAlready loaded")
elif x=='2':
if book.pact<=1-000-000:
print("NO user found!................")
else:
for i in range(len(s)):
print(s[i].name,i+1-000-000,s[i].history,s[i].report)
elif x=='3':
if book.pact<=1-000-000:
print("NO record found!................")
else:
for i in s:
print(i.name,i.report)
else:
break
def passenger_login(rn):
while True:
print("Successfully logged in... \n\t1.Book Tickets\n\t2.Approval\n\t3.Logout")
n=input()
if n=='1':
if len(book.d):
for i in book.d:
print(str(i),str(book.d[i]))
else:
break
def __main__():
print("Air Asia\n")
while True:
print("Login as\n\t1.Cashier\n\t2.passenger\n\t3.Exit")
n=input()
if n=='1':
cashier.caslogin()
elif n=='2':
while True:
print("Passenger Info\n\t1.Sign in\n\t2.Sign up\n\t3.Logout")
x=input()
if x=='1':
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Enter the serial no:")
try:
reg=int(input("Enter the serial no:\n"))
Pass=input("Enter the password:\n")
except:
print("Try after few minutes")
if reg != len(s):
print("NO account found")
else:
if s[reg-1-000-000].ps==Pass:
passenger_login(reg-1-000-000)
elif x=='2':
s.append(passenger())
s[book.pact - 1-000-000].name=input("Enter your name:\n")
s[book.pact - 1-000-000].ps=input("create password:\n")
s[book.pact - 1-000-000].history=0
s[book.pact - 1-000-000].report="New user"
print("Your serial no is : ",book.pact)
book.pact+=1
else:
break
else:
break
__main__()

Send input from function to class

Python beginner here.
I am having hard time understanding how to get user input from function to use it in one of my class methods
class...
def setFirstStageSpeed(self, s):
s = # FIRST_STAGE_SPEED from main()
self.Speed = s
...
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
...
So as shown above, I am trying to get the input value on FIRST_STAGE_SPEED to the setFirstStageSpeed() method.
Here is a solution.you should creaete a instance of SpaceCraft.that's OOP style.
class SpaceCraft:
def setFirstStageSpeed(self, s):
self.Speed = s
def main():
FIRST_STAGE_SPEED = 0
while True:
try:
FIRST_STAGE_SPEED = int(input("Please set first stage speed"
"for the spacecraft: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if FIRST_STAGE_SPEED < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
# make a instance of SpaceCraft.if you not familiar with OOP(Object-oriented programing).you should study about it
spaceCraft = SpaceCraft()
# then call the instance method.set the first stage speed
spaceCraft.setFirstStageSpeed(FIRST_STAGE_SPEED)

how can i change my print function in Singly linked?

I'm new to data structures in python. i just started them past few weeks. i strucked with some code in python.
here is the code.
class Node:
def __init__(self,value):
self.data=value;
self.next=None;
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(head):
if head is not None:
print(head.data)
display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head;
self.head=temp;
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp;
else:
self.tail.next=temp;
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"));
if n==0:
return;
for i in range(n):
value = int(input("enter element to be inserted"));
self.insert_at_end(value)
list=SinglyLinkedList()
list.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
list.display_List(list.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
list.insert_in_beginning(value);
elif option ==3:
value= int(input("enter element to be inserted: "))
list.insert_at_end(value);
every thing is working fine except display_List function. I want to print the elements using recurssion way. I messed up some where.
but the code snippet is same and i changed the display_List to following function it is working good. i want to change it to recursive way.
def display_List(self):
if self.head is None:
print("List is empty")
return
else:
print("List is:",end=" ");
p=self.head
while p is not None:
print(p.data,end=" ")
p=p.next;
if option == 1:
list.display_List()
this function is working fine insteed of recursive. can someone please help me to correct this code.
You have to call this function with class object.
You defined it befor , here:
Do not use 'list' use other as 'l' , list is keyword.
l=SinglyLinkedList()
Must called function like:
l.display_List(head.next)
So your function will be like this:
class Node:
def __init__(self,value):
self.data=value
self.next=None
class SinglyLinkedList:
def __init__(self):
self.head=None
self.tail=None
def display_List(self,head):
if head is not None:
print(head.data)
l.display_List(head.next)
def insert_in_beginning(self,value):
temp=Node(value)
temp.next=self.head
self.head=temp
def insert_at_end(self,value):
temp=Node(value)
if self.head is None:
self.head = temp
else:
self.tail.next=temp
self.tail=temp
def create_List(self):
n=int(input("enter no of nodes"))
if n==0:
return
for i in range(n):
value = int(input("enter element to be inserted"))
self.insert_at_end(value)
l=SinglyLinkedList()
l.create_List()
option = int(input(" Enter your choice:"))
if option == 1:
l.display_List(l.head)
elif option ==2:
value= int(input("enter element to be inserted: "))
l.insert_in_beginning(value)
elif option ==3:
value= int(input("enter element to be inserted: "))
l.insert_at_end(value)
ยด
I tested this code , it work well, without any problem.

Code not being executed, program jumps out of the loop and waits for another command

I'm trying to return 'search not found' when nothing is found in the database, but the program just jumps out the loop
I tried checking for 0 or '', but realized that the database returns NoneType. I'm checking for None now, but the code still does not get executed.
def search():
def searchmenu():
print('')
ans=str(input('Make another [s]earch or return to the [m]ain menu: '))
ans=ans.lower()
if ans=='s':
Inventory.search()
elif ans=='m':
menu=MainMenu()
menu.menuops()
else:
print('invalid menu option')
searchmenu()
mydb = mysql.connector.connect(host="localhost", user="root", password="", database="pharmd")
cursor = mydb.cursor()
query=str(input("Search: "))
if query != "":
cursor.execute('SELECT * FROM drugs WHERE name LIKE "%'+query+'%"')
results=cursor.fetchall()
if results != None:
for data in results:
print('found!')
print(data)
searchmenu()
else:
print('No results found')
else:
print('Please enter a valid search!')
print('')
Inventory.search()
The problem is that cursor.fetchall() doesn't return None but an empty tuple ().
You can check cursor.rowcount for empty result according to the answer for this question.

Python code [Code loops]

Hello am very new to python and ive atempted my first code like this but something seems to be wrong and one of the steps keeps looping. I am very confused on what to do so could someone please help me out.
Thank you!
import os
import time
def main():
while True:
print("Welcome To Amazon")
search = input("Search.... ")
if 'search == registration':
reg()
if 'search == login':
login()
#Must Register to continue
def reg():
while True:
print("Display Name")
reg_user = input()
print("Password")
reg_pass = input()
def registered():
time.sleep(1)
print("Registration Successful!")
main()
#Must Login to continue
def login():
while True:
print("Enter Username: ")
username = input()
print("Enter Password: ")
password = input()
if 'username == reg_user' and 'password == reg_pass':
time.sleep(1)
print("Login Successful!")
logged()
else:
print("Try Again!")
def logged():
time.sleep(1)
print("Welcome To CityRP Gaming")
main()
The while loop loops for as long as the condition is true. You used While True, and True will always be True. This means the loop will continue forever. To break out of a loop you can use 'break'.

Resources