make a program choose number 1 until 100 - python-2.7

How to make the program choose a value from 1 to 100? The program cannot print the correct value
while True:
regage = raw_input('Enter your age:')
if regage not in range(1,100):
print 'Please put an apropriate number for your age'
else:
print 'you are', regage,'years old'

This should work. The problem was that raw_input returns a string, so the value should be converted to an integer before you can check if it's in the array of integers that range returns.
while True:
regage = raw_input('Enter your age:')
if int(regage) not in range(1,101):
print 'Please put an apropriate number for your age'
else:
print 'you are', regage,'years old'
Also, I changed the range to include 100.

Related

Why following code doesn't run an exception for negative inputs?

I want to write a simple code when user enters his age, it will give in how many years user will be 100 years. But I have assigned an exception if the user enters a negative number to give a value error. But the code runs regardless even if I enter a negative number without raising an exception. Why is that? Thanks! I'm using python 2.7
try:
age = raw_input("Please enter your age: ")
if age < 0:
raise ValueError ('%d is not a positive number' )
except ValueError as err:
print ("You've entered an incorrect age input %s" %err)
else:
print("You will be 100 in %d" % (100 - int(age)))
raw_input returns a string, so age is a string containing whatever you put - "-3" for example. Not an integer.
When comparing an integer to a string, "-3" < 0, the integer always "comes first" (is smaller than the string), just as an implementation detail, so your if will always be False. Cast to an int, the ValueError will already catch an invalid cast:
age = int(raw_input("Please enter your age: "))

Python readability

Greetings stackoverflow,
I am pretty new to both this website and python.
I wrote a simple program to create a list of devisors based on a user inputted number, the program works (as far as I know)
But I am pretty sure my syntax is extremely amateurish, so I ask the fluent among you, what can I do to make this:
divisors = []
def devisors(x):
while True:
try:
for i in range(1,x+1):
if x%i==0:
divisors.append(i)
if x==i:
break
except ValueError, TypeError:
return "Invalid input."
continue
print "The list of divisors of",x,"Are: ", divisors
choice1= raw_input("Would you like to use devisors program?(Y/N): ")
while True:
try:
if choice1 in yes:
x = int(raw_input("Please enter a number: "))
devisors(x)
elif choice1 in no:
print "Alright, bye bye."
break
else:
print "invalid input"
choice1= raw_input("Would you like to use devisors program(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
try:
choice2= raw_input("Would you like to try again?(Y/N): ")
if choice2 in yes:
divisors = []
continue
devisors(x)
elif choice2 in no:
print "Alright, bye bye. "
break
else:
print "invalid input"
choice2= raw_input("Would you like to try again?(Y/N): ")
continue
except ValueError, TypeError:
print "Invalid input, try again."
Better written?
I want you to go berserk on this code, tell me (If you feel like it) what could be done to improve it, to write less lines, and mistakes I made.
Also I am not sure if this is something allowed on stackoverflow, if not, please let me know and I'll delete this.
Thank you.
Looking forward to the feedback.
First of all, we do have a dedicated Stack Exchange Code Review site, but you're not the only one asking for a code review here.
The first thing I noticed is that you are trying to hard to put everything in a single method.
Whenever you are faced with a problem or task you should try to divide it into the smallest possible problems. Afterwards we can implement the solution to these small problems as functions.
In your example your tasks are the following:
Get user input of a number
Get the divisors of that number
Print the divisors
Ask if the user wants to give it another try
Let's start with the 2nd point of our list:
def divisors_of(x):
if x < 0:
raise ValueError("Value cannot be smaller than 0")
divisors = []
for i in range(1, x + 1):
if x % i == 0:
divisors.append(i)
return divisors
That doesn't look too bad, does it?
After implementing the user input for a number and printing the result, we already get something like this:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
Looking at our task list we still don't ask the user for another try. Again, IMHO it's more readable if we put the logic for that in a function. This has two additional benefits, we can convert the yes/no choice to a boolean and the written code is reuseable:
def yes_no_choice(text):
while True:
choice = raw_input(text)
if choice in "yes":
return True
# Returning like this is called early return
# As we jump out of the function, the code after
# the if is automatically the else statement
# The code is shorter and more readable
if choice in "no":
return False
print "Invalid answer"
Our final result looks like this:
while True:
try:
num = int(raw_input("Please enter a number: "))
divisors = divisors_of(num)
print "The divisors of ", num, " are: ", divisors
except (ValueError, TypeError) as ex:
print ex.message
if not yes_no_choice("Would you like to try again?(Y/N): "):
print "Bye!"
break
# else we will loop
Oh, and try not to use global variables if you don't have to. I'm looking at your divisors = []

Exception Handling with Boolean Expressions

Is it possible to include a boolean expression like I've done below while exception handling using try/except?
For example:
while True:
try:
grade = float(input('Please enter your your score:'))
break
except ValueError:
print('Please enter a numeric value, you dingus!')
except (grade > 1):
print('Not a valid number, please re-enter:')
except NameError:
print('Please enter a numeric value, you dingus!')
I'd like for string inputs to be handled by 'except NameError.' I'd like for numerics greater than 1 to be handled by printing 'Not a valid number, please re-enter:'
As is, the program handles strings and valid numeric inputs as intended. However, when I input numbers greater than 1, the program accepts my input and does nothing else. No except commands are executed and nothing is passed on to the function found below this exception handling piece of code. The program just stops and no error is given to help with debugging.
Give this a shot:
while True:
try:
grade = float(input('Please enter your your score:'))
if grade > 1:
raise ValueError
except ValueError:
print('Not a valid number, please re-enter.')
except NameError:
print('Please enter a numeric value, you dingus!')
except SyntaxError:
print('Please enter something, anything!?')

comparing a list to a tuple, python 3.x - having problems getting the correct position to print

I'm a new programmer and I'm having a difficult time finishing up my 4th program. The premise was to create a program that would take input from the user, creating a list then compares this list to a tuple. After it prints a statement letting the user know which items they chose correspond to the items in the tuple and also in which position they are in the tuple.
The problem I'm having is the last part, I can't get the correct position to print right and I fail to understand why. For example, if someone chose GPS correctly during their guesses, it should print position 0, but it doesn't. If water is chosen, it says it's in position 13...but it should be 5.
#here is the code I have so far:
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = () #this is the tuple that will be compared against
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in case of a survival situation, think Bear Grylls. Once chosen, your list will be compared to the top 10 survival items list.")
while number_items_input < 10:
print("Please choose.")
guessed_items = input()
guessed_inventory_list.append(guessed_items)
number_items_input = number_items_input + 1
print ("You have chosen the following:", guessed_inventory_list)
#block of code below here compares the input to the tuple
t = 1
while t < 1:
t = t + 1
for individual_items in guessed_inventory_list:
for top_items in survival_gear:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The reason you are getting a wrong index is because of the wrong nesting of loops , your outer loop should be the tuple you wish to compare and the inner loop should be the list generated from the input where as in this case it is reverse, see the below corrected code snippet
Code snippet:
for top_items in survival_gear:
for individual_items in guessed_inventory_list:
if individual_items == top_items:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print ("You have chosen wisely", top_items)
print ("It's in position", t, "on the survival list")
t = t + 1
The above code snippet should solve your problem , but your code contains
while loop which can be avoided using the range built in function
Incrementing the variable t manually can be avoided by using enumerate built in function
The nested forloop and if loop can be replaced by using the "in" membership test operator
Find the below updated code:
#!/usr/bin/python
number_items_input = 0
guessed_inventory_list = [] #this is the variable list that will be input by user
survival_gear = ("GPS","map","compass","firstaid","water","flashlight","lighter","blanket","rope","cell phone","signal mirror")
#block bellow takes input from the user
print("Please choose one by one, which top 10 items do you want with you in caseof a survival situation, think Bear Grylls.Once chosen, your list will be compared to the top 10 survival items list.")
# One can use range functions to loop n times in this case 10 times
for i in range(0,10):
guessed_items = raw_input("Please choose:")
guessed_inventory_list.append(guessed_items)
print ("You have chosen the following:", guessed_inventory_list)
# Enumerate is one of the built-in Python functions.
# It returns an enumerate object.
# In this case that object is a list of tuples (immutable lists),
# each containing a pair of count/index and value.
# like [(1, 'GPS'), (2, 'map'), (3, 'compass'),...,(6, 'signal mirror')]
# in the below for loop the list of tuple will be
#unpacked in to t and individual_items for each iteration
for t,individual_items in enumerate(survival_gear,start=1):
#the "in" is a membership test operator which will test whether
#individual_items is in list guessed_inventory_list
if individual_items in guessed_inventory_list:
#finally the print statements below advise the user if they guessed an item and which position it's in.
print("You have chosen wisely", individual_items)
print("It's in position", t, "on the survival list")

Is there a way to go back and edit the information the user entered?

I have a simple code written in Python 2.7 that will ask users for certain information, and it exports the information to a .csv file. Once the user inputs the data, is there a way for them to go back and edit what they entered after pressing enter? Here is what i have so far:
def writer():
import csv
with open('Work_Order_Log.csv', 'a') as f:
w=csv. writer(f, quoting=csv.QUOTE_ALL)
while (1):
Correct=True
Employee=True
WorkOrder=True
Item=True
Qty=True
Process=True
Date=True
Time=True
while Correct:
Correct=False
Employee=False
WorkOrder=False
Item=False
Qty=False
Process=False
Date=False
Time=False
Employee=raw_input("1. Enter Your Name:")
WorkOrder=raw_input("2. Enter The Work Order Number:")
PartNumber=raw_input("3. Enter The Item Number:")
Qty=raw_input("4. Enter Quantity:")
Process=raw_input("5. Enter Process:")
Date=raw_input("6. Enter Date(mm/dd):")
Time=raw_input("7. Total Time(hh:mm):")
needToCorrect=raw_input("Is the last Entry Correct? (If so, type 'y') If not enter the Number of the Field that is incorrect:")
if needToCorrect=="1":
Employee=True
elif needToCorrect=="2":
WorkOrder=True
elif needToCorrect=="3":
Item=True
elif needToCorrect=="4":
Qty=True
elif needToCorrect=="5":
Process=True
elif needToCorrect=="6":
Date=True
elif needToCorrect=="7":
Time=True
w.writerow([Employee,WorkOrder,Item,Process,Qty,Date,Time,Correct])
writer()
After testing the code, I have found that when I enter the number of the incorrect field for correction, it shows in the .csv file that it was incorrect, but still makes me go through the entire loop to fix the errors. Why is this?
You can put all of your input into a while block:
while (1):
Correct = True
while Correct:
Correct = False
Employee=raw_input("Enter Your Name:")
...
needToCorrect=raw_input("Is the last Entry Correct?(y/n):")
if needToCorrect == "n":
Correct = True
w.writerow([Employee,WorkOrder,PartNumber,Process,Qty,Date,Time,Correct])
Then if a user notices something is incorrect, an "n" will prompt the user to return and retype the fields. If you want only to correct certain fields, a similar, more complicated, method would work fine.