Using python 3.6
How do I incorporate 0 or negative input to raise an error and let the user try again?
like <=0
#loop to check valid input option.
while True:
try:
choice = int(input('Enter choice: '))
if choice>len(header):
print("Invalid choice!! Please try again and select value
either:",end=" ")
for i in range(1,len(header)+1):
print(i,end=",")
else:
break
choice = int(input('\nEnter choice: '))
except ValueError as ve:print('Invalid response, You need to select
the number choice from the option menu') # Catch your local
ValueError and continue your loop
usr_choice = header[choice - 1]
max_val = None
max_obj = None
--here is the full code --
import os.path
import sys, traceback
def main():
print('Welcome to CSV Analytics!')
try:
fname = None
# running an infinite loop and will break only will another attribute and another file choice selected as 'n'
while True:
# will take file name input only when fname is not None
if fname is None:
fname = input('Enter the name of the file you would like to process: ')
if not validateFile(fname):
fname = None
continue
# obtaing header from the file
with open(fname) as fp:
header = fp.readline().strip().split(',')
# first column is object name, so skipping that and getting rest of the columns
header = header[1:]
seq = 1
# printing the options menu which are header in the file
for attribs in header:
print(str(seq)+'.', attribs)
seq += 1
#loop to check valid input option.
while True:
try:
choice = int(input('Enter choice: '))
if choice>len(header):
print("Invalid choice!! Please try again and select value either:",end=" ")
for i in range(1,len(header)+1):
print(i,end=",")
else:
break
choice = int(input('\nEnter choice: '))
except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your local ValueError and continue your loop
usr_choice = header[choice - 1]
max_val = None
max_obj = None
# finding maximum value for the given attribute selection
for line in fp:
attr_list = line.strip().split(',')
# when max_val is none set the max_val and max_obj to attribute of first line
if max_val is None:
max_val = attr_list[choice]
max_obj = attr_list[0]
# verifying maximum value of given attribute choice here
if attr_list[choice] > max_val:
max_val = attr_list[choice]
max_obj = attr_list[0]
print('Largest', usr_choice, 'value is', max_obj, 'with', max_val)
another_attr = input('Would you like to conduct another analysis on an attribute? (y/n) ')
if another_attr == 'y':
continue
else:
while True:
another_file = input('Would you like to evaluate another file? (y/n) ')
if another_file == 'y':
fname = input('Enter the name of the file you would like to process: ')
if validateFile(fname):
break
else:
continue
else:
return
# catches all file I/O errors
except IOError:
print('Errored while doing I/O operations on the file')
#traceback.print_exc(file=sys.stdout)
# all non file I/O errors captured here
except:
print('An error occurred')
#traceback.print_exc(file=sys.stdout)
def validateFile(fname):
if os.path.exists(fname):
return True
else:
print('File not found, try with correct file name')
return False
if __name__=='__main__':
main()
You just need to modify the following code, Let me know if you have any doubt. You need to check the input value whether it is 0 or negative in the if condition itself.
#loop to check valid input option.
while True:
if choice>len(header) or choice<=0:
print("Invalid choice!! Please try again and select value either:",end=" ")
for i in range(1,len(header)+1):
print(i,end=",")
else:
break
choice = int(input('\nEnter choice: '))
Using python 3.6 How do I incorporate 0 or negative input to raise an error and...
Python: def combo(): play = True while play: x = int(input('How many people\'s information would you like to see: ')) print() for num in range(x): name() age() hobby() job() phone() print() answer = input("Would you like to try again?(Enter Yes or No): ").lower() while True: if answer == 'yes': play = True break elif answer == 'no': play = False break else: answer = input('Incorrect option. Type "YES" to try again or "NO" to leave": ').lower()...
Can you please enter this python program code into an IPO Chart? import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the non-numbers #if user enters letters, then except will show the message, Numbers only! try: c=int(input("Enter your choice: ")) if(c>=1 and c<=3): return c else: print("Enter number between 1 and 3 inclusive.") except: #print exception print("Numbers Only!")...
Describe the necessary user inputs from the program using the following table format. Choose the appropriate data type to store each user input and explain your choice. Input data type chosen and why Note that you are expected to take into consideration the value(s) of each transaction category. For example, your program should assess the transaction amount of each bill paid by the user before classifying it under the bill payment category. Below is the python program: from math import...
Can you add code comments where required throughout this Python Program, Guess My Number Program, and describe this program as if you were presenting it to the class. What it does and everything step by step. import random def menu(): #function for getting the user input on what he wants to do print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the...
Write a PYTHON program that allows the user to navigate the lines of text in a file. The program should prompt the user for a filename and input the lines of text into a list. The program then enters a loop in which it prints the number of lines in the file and prompts the user for a line number. Actual line numbers range from 1 to the number of lines in the file. If the input is 0, the...
I need this python program to access an excel file, books inventory file. The file called (bkstr_inv.xlsx), and I need to add another option [search books], option to allow a customer to search the books inventory, please. CODE ''' Shows the menu with options and gets the user selection. ''' def GetOptionFromUser(): print("******************BookStore**************************") print("1. Add Books") print("2. View Books") print("3. Add To Cart") print("4. View Receipt") print("5. Buy Books") print("6. Clear Cart") print("7. Exit") print("*****************************************************") option = int(input("Select your option:...
For my computer class I have to create a program that deals with making and searching tweets. I am done with the program but keep getting the error below when I try the first option in the shell. Can someone please explain this error and show me how to fix it in my code below? Thanks! twitter.py - C:/Users/Owner/AppData/Local/Programs/Python/Python38/twitter.py (3.8.3) File Edit Format Run Options Window Help import pickle as pk from Tweet import Tweet import os def show menu():...
I am currently facing a problem with my python program which i have pasted below where i have to design and implement python classes and record zoo database and takes user input as query. the error i am recieving says that in line 61 list index is out of range. kindly someone help me with it as soon as possible. Below is the program kindly check and correct it. Thanks! class Animal: def __init__(self, name, types, species, mass): self.name=name self.type=types...
Python Error: Writing a program to complete the following: Prompt the user for the name of an input file. Open that file for input. (reading) Read the file using a "for line in a file" loop For each line, o print the line and compute and print the average word length for that line. Close the input file Sample output: MY CODE IS WRONG AND NEED HELP CORRECTING IT!!! ------------------------------------------------------------------------------------------------------------------------ DESIRED OUTPUT: Enter input file name: Seasons.txt Thirty days hath September...
Questions 1. How to create a comment in python? 2. The way to obtain user input from command line 3. List standard mathematical operators in python and explain them 4. List comparison operators in python 5. Explain while loop. Give example 6. Explain for loop. Give example 7. How to create infinite loop? And how to stop it? 8. Explain a built-in function ‘range’ for ‘for’ loop 9. Explain break statement 10. Explain continue statement 11. Explain pass statement 12....