OK so I have this task at school, I'm a complete beginner but I have most of it down, I need to ask for the number and have it output the corresponding name (it's part "d") I managed to get part C to work but when I try to do the same thing to D it refuses to work. I know I'm probably doing something wrong but as I said I'm a complete beginner.
Also, can I tried changing my c+d to "if" so that I could add another "else" so that if the name/number that was input wasn't in any of the lists that it would return saying "invalid" but I cant seem to be able to change them to if statements.
Anyway here's the code I'm trying to make work, like I said, C works but D refuses to:
flag="F"
choice=""
#Looping-----------------------------------------------------------------------
while choice != "F" and choice !="f":
print( " A. Setup Name, Number and CallsPerDay \n"
" B. Display all names and numbers \n"
" C. Insert name to find out number \n"
" D. Insert number and find out name \n"
" E. Display Min, Max and Average CallsPerDay \n"
" F. Finish the Program")
choice=input("Select an option: \n\n")
#Selection---------------------------------------------------------------------
if choice=="A" or choice =="a":
if flag=="F":
names=["gordon", "david", "graeme", "joyce", "douglas", "brian", "suzanne", "karen"]
numb=[273429, 273666, 273512, 273999, 273123, 273224, 273324, 273424]
CPD=[30, 10, 15, 2, 5, 1, 3, 6]
length=len(numb)
print("Names, Numbers and CallsPerDay have now been set up \n")
flag="T"
elif flag=="T":
print("Lists already set up \n")
#---------------------------------------------------------------------------------
elif choice=="B" or choice=="b":
if flag=="F":
print('Run option A first!')
else:
for i in range(0,length,1):
print(names[i],numb[i], CPD[i], "\n")
#-------------------------------------------------------------------------------
elif choice=="C" or choice=="c":
if flag=="F":
print('Run option A first!')
else:
wanted=input('Name please ').lower()
i=0
while names[i] != wanted:
i=i+1
print('Number',numb[i])
#----------Part that refuses to work------------------------
elif choice=="D" or choice=="d":
if flag=="F":
print('Run option A first!')
else:
wanted=input('Number Please: ')
i=0
while numb[i] != wanted:
i=i+1
print('Number',names[i])
Here is the error I get in the shell when trying to do this:
A. Setup Name, Number and CallsPerDay
B. Display all names and numbers
C. Insert name to find out number
D. Insert number and find out name
E. Display Min, Max and Average CallsPerDay
F. Finish the Program
Select an option:
a
Names, Numbers and CallsPerDay have now been set up
A. Setup Name, Number and CallsPerDay
B. Display all names and numbers
C. Insert name to find out number
D. Insert number and find out name
E. Display Min, Max and Average CallsPerDay
F. Finish the Program
Select an option:
d
Number Please: 223666
Traceback (most recent call last):
File "G:\Lvl 5\sofware\menuNEWex - Copy.py", line 62, in <module>
while numb[i] != wanted:
IndexError: list index out of range
>>>
It should be outputting David, because they are both #2 on their lists
There's a few problems here. First, you need to convert wanted from a string to an integer so your comparison will work:
# Not this, because the return of input is a string
wanted=input('Number Please: ')
# But this. Note this will throw a ValueError if converting to an int fails!
wanted = int(input('Number please: '))
# This one has error handling!
try:
wanted = int(input('Number please: '))
except ValueError:
print("That's not a number")
Also, if your entered number is not in your list numb, your loop will still break when i becomes larger than the last index. Try using the index method instead, as it will either return the index of the number or throw a ValueError. Be careful though - that index is the first index of the element in the list. If the same number is repeated, you'll need another approach that handles conflicts:
try:
i = numb.index(wanted)
print('Number', names[i])
except ValueError:
print("No such number")
You should also consider wrapping your input requests in while loops that look for valid values. For example, you need a number for the above section:
i = None
while i is not None:
try:
i = int(input("Number: "))
except ValueError:
# i is still None
print("Must enter a number!")
An example running would give you this:
Number: a
Must enter a number!
Number: b
Must enter a number!
Number: 33
If you put checking your index in that loop, you get checking for integers and valid values at the same time.
Related
You want to know your grade in Computer Science, so write a program
that continuously takes grades between 0 and 100 to standard input
until you input "stop", at which point it should print your average to
standard output.
NOTE: When reading the input, do not display a prompt for the user.
Use the input() function with no prompt string. Here is an example:
grade = input()
grade = input()
count = 0
sum = 0
while grade != "stop":
grade = input()
sum += int(grade)
count += 1
print(sum / count)
Please dont solve it for me, but if you can point out why setting grade as "input()" doesnt work
You input a line as the first operation and then correctly enter the loop only if it isn't "stop".
However, that should then be the value you use for summing rather than immediately asking the user for another value. In your current code, if the user enters "stop", there is no check before attempting to treat it as a number.
So, if you don't want a solution, I'd suggest you stop reading at this point :-)
Couldn't resist, could you? :-)
The solution is to simply move the second input call to the bottom of the loop, not the top. This will do the check on the last thing entered, be that before the loop starts or after the value has been checked and accumulated.
In addition, your print statement is inside the loop where it will print after every entry. It would be better
There's other things you may want to consider as well, such as:
moving your print outside the loop since currently you print a line for every input value. You'll also have to catch the possibility that you may divide by zero (if the first thing entered was "stop").
handling non-numeric input that isn't "stop";
handling numeric input outside the 0..100 range.
Don't use this since you're trying to educate yourself (kudos on you "please don't solve it for me" comment by the way) and educators will check sites like SO for plagiarism, but a more robust solution could start with something like:
# Init stuff needed for calculating mean.
(count, total) = (0, 0)
#Get first grade, start processing unless stop.
grade = input()
while grade != "stop":
# Convert to number and accumulate, invalid number (or
# out of range one) will cause exception and not accumulate.
try:
current = int(grade)
if current < 0 or current > 100:
throw("range")
# Only reaches here if number valid.
total += int(grade)
count += 1
except:
print(f'Invalid input: {grade}, try again')
# Get next grade and check again at loop start.
grade = input()
# If we entered at least one valid number, report mean.
if count > 0:
print(total / count)
the first input does not work, covered by the second input;
when input is "stop", int("stop") is wrong;
When reading the input, do not display a prompt for the user. you should print the ans after the while loop
you can use endless loop and break to solve this problem.
...
while True:
grade = input()
if grade == 'stop':
break
...
print(ans)
pseudocode
numtodouble=int
result=int
print("")
print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
result=numtodouble*2
print("2 X", numtodouble, "=", result)
print("")
print("Enter a number you would like to double and press Enter.")
input(numtodouble)
break
print("OK, you entered a value <=0, ending execution.")
Does anyone know where I went wrong with my code? I've been struggling with this for hours.
try:
# input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
num_to_double = int(input("Enter a number you would like to double and press Enter."))
while num_to_double>0:
result=num_to_double*2
# Format puts the arguments into the curly braces in the order given
print("2 X {} = {}\n".format(num_to_double, result))
# input is cast to int and stored in num_to_double. The text in the input command is the prompt
num_to_double =int(input("Enter a number you would like to double and press Enter."))
# This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making
# the code act not as intended
print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try:
# Except block.
except ValueError as _:
print("A not-a-number was supplied")
This code is far simplier and does what you're trying to do. I assume you're learning python, so some of these things are not the simplest way to do things, like the format function, but are super useful to learn.
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
This code is the closest I could do to the pseudocode provided. Declaring variables before they're used here isn't necessary and is messy. It's like the pseudocode wasn't meant to become python. Same with printing blank lines, those should be wrapped into the previous or next print lines.
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions
I'm very new to Python and programming in general, so excuse me if the code is terrible and the problem rather easy to solve.
I have written code to allow a user to have employee data printed based on 3 different inputs, which they are allowed to choose from.
The options the user has available to them are to pick employees based on their payroll number; a minimum and maximum salary range; their job title.
I made two functions for the formatting. The first one turns the lines of the text file into lists, then the second function grabs those individual lists and formats them.
Then the code requests the user to input the file name. If the file cannot be found, they get to try again. If it is correct, the file is loaded and then runs through the functions to print out a neat table.
Then the user is asked what method they want to choose from to select specific employees. They are given 4 options, 3 are mentioned at the start and the fourth is to just end the program.
I managed to successfully get the first option to print out the employees without hassle, as is the same for the fourth option to end the program. I almost have the third one completed, I just need to find a way to print the name without a comma. My problem resides within the second option: how do I print the employees and their details if they fall between the minimum and maximum salary ranges entered by the user if the range isn't an integer since it has to include a '£' sign?
Here's the code. It's the biggest chunk in the program because I just have no clue how to make it work properly -
def detailsPrint(field) : #takes tuple and prints
print("{:30}" "{:6}" "{:15}" "{:7}".format(field[3] + ", " + field[4], field[0], field[2], "£" + field[1]))
if display == 2 :
maxSalary = "£1000000"
minpay = input("Enter the minimum pay : ")
maxpay = input("Enter the maximum pay : ")
if len(minpay) and len(maxpay) < maxSalary :
for s in employeeList :
if s[1] >= minpay :
detailsPrint(s)
The outcome should be something like (example) Simpson, Bart 12345 Consultant £55000 if the minpay were to be £50000 and maxpay £60000
edit: Managed to get it working. Here's the code
if display == 2 :
x = False
maxSalary = 1000000
minpay = int(input("Enter the minimum pay: "))
maxpay = int(input("Enter the maximum pay: "))
if int(minpay) > int(maxSalary) or int(maxpay) > int(maxSalary) :
x = False
print("No employees earn over £1000000. Try again.")
if int(minpay) or int(maxpay) < int(maxSalary) :
for s in employeeList :
if int(s[1]) >= minpay and int(s[1]) <= maxpay :
detailsPrint(s)
x = True
if x == False :
print("No employees could be found within that range. Try again")
print("\n")
Simplest solution: don't ask for the £ char ;-)
A solution that work with your requirement is to change the line
if len(minpay) or len(maxpay) > maxSalary :
with something like
if int(minpay[1:]) > int(maxSalary[1:]) or int(maxpay[1:]) > int(maxSalary[1:]) :
which check the numeric value of the strings (your condition seems wrong anyway to me)
You could replace all "£" signs to "" in a string.
YourString.replace("£", "")
I'm trying to create a python football manager program that asks users a players name and the asks how many goals the player has scored. The goals scored cannot be a negative number or more than 6. I'm also trying to get the code to validate that goals scored is an integer and not a string. Here's the best I could do:
goals = ""
while goals == "":
try:
goals = int(input("Enter goals scored"))
except ValueError:
print("Please enter an integer")
How can I get the code to also check the range? Doing:
while goals == "" and goals not in range(0,6):
#Try catch loop
Doesn't work.
You need to use an or, not an and.
If the input isn't an int, you'll get a ValueError, and goals will remain "". If you don't get a ValueError a valid int is assigned to goals, so you need to check the range:
while goals == "" or goals not in range(0,6):
The first problem lies with you assigning a string as the default to a variable that is truly integer-based. You say that goals cannot be negative or greater than 6, then use an invalid integer as your original value for goals.
goals = -1
while not 0 <= goals <= 6:
text = input('Enter goals scored (between 0 and 6 inclusive): ')
try:
goals = int(text)
except ValueError:
print('Please enter an actual integer.')