How do I define the number variable in this function? - python

I don't really know anything about user defined functions and I am wondering how do I define the number variable in this function?
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)

Why do you even need parameters for your function. Try the below code.
You are clearly defining number in the function.
You are getting the input from the user.
I think that's all you are actually looking for.
Also your function has 3 parameters and you were passing only one as a number and that was not even defined, that's why you got the error. Even if you had defined the variable number, you still would have got the error as you had two more parameters in there which didn't make sense as you don't need them!
def getNumber():
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber()

In Python, this
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)
is very different to this
def getNumber(str,input,number):
number= str(input("Give me a number!:"))
if (number.isdigit())==True:
print("Thats a great number I love "+str(number))
while (number.isdigit())==False:
number=str(input("You lied to me thats not a number! Give me a number!"))
getNumber(number)
When you run the first version, the third line containing if (number.isdigit() is not part of your function - it's not indented, so is actually outside the function and at the root of your module.
This means that when you run your module you are working on a variable (the number variable) which hasn't been declared and doesn't exist.

You can define any value to a variable by var_name = value, i.e. num = 4 or string = 'A string.
You want to scan the user input and verify there aren't any non-digit characters in the string (\D):
import re
def getNumber():
number= str(input("Give me a number!:"))
# re (regex module), check for characters in the alphabet
if re.search('\D',number) != None:
return False # or use re module to remove unwanted characters by using re.replace().
else:
if '.' in number:
return float(number)
else:
return int(number)
Note The way this is written, when the function is called it will ask the user for input. If you want to check whether an input is a number, without calling user input inside the function, give the function a parameter that it will check. i.e.
import re
def getNumber(input):
# re (regex module), check for characters in the alphabet
if re.search('\D',number) != None:
return False # or use re module to remove unwanted characters by using re.replace().
else:
if '.' in input:
return float(input)
else:
return int(input)
>>> getNumber('a3')
False
>>> getNumber('3')
3
Hope this helps. Be sure to check out the re module docs for more info.
Cheers!

Related

Python Nested List: How to print specific elements and append to each sublist

quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for i in range(len(quizes)):
grade = eval(input("Enter", quizes[i][0],"grade:"))
quizes[i].append(grade)
print(quizes[i])
Hey guys so I been working on this for the past week and can't solve this. I am trying to get my program to ask "Enter [person1] grade: " and so on and append a second element to each sublist which will be their grade and then print the contents of the entire list. Any help is appreciated
The problem is input takes 1 string as a parameter, you are passing 3 instead. So:
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
grade = eval(input(f"Enter {l[0]} grade:"))
l.append(grade)
print(l)
However, I respectfully don't understand the point of using eval here. Eval turns data into code. Using eval on user input creates a great security hole. In the above code, what if the user input quizes.clear()? The whole array will be emptied. What if he inputs something eviler?
Consider (assumes valid grades only contain numbers):
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
while True:
try:
grade = float(input(f"Enter {l[0]} grade:"))
except ValueError:
print("Please input a number.")
else:
l.append(grade)
break
print(quizes)
The main problem is that input() accepts only one argument as the input prompt, unlike print which can take any number of arguments - you're giving 3 parameters to the input function - "Enter", quizes[i][0], and "grade:".
You can try concatenating them - like input("Enter "+str(quizes[i][0])+" grade:") (the str() conversion is not needed if you know that all the quizes[i][0] will be strings already),
or even use string formatting - "Enter {} grade".format(quizes[i][0]) or f"Enter {quizes[i][0]} grade:"
This should be enough, but there are 2 more changes you can make to your code if you like -
Iterate over the nested lists directly (for sub_list in quizes:)
Using int() or float() to convert a returned input string containing a number will also work in place of eval
For example
for quiz in quizes:
grade = eval(input("Enter {} grade:".format(quiz[0])))
quiz.append(grade)
print(quiz)
EDIT: Python docs on string formatting The f"..." syntax works only for Python 3.6+
You need to change:
grade = eval(input("Enter", quizes[i][0],"grade:"))
to
grade = eval(input("Enter " + quizes[i][0] + " grade:"))
input does not behave as print does. You can't use commas to join text in any other function (except for a very small number of custom functions and modules), and you should stay away from them at if that's confusing for you to only use them sometimes.
With that change, does your code work now? You didn't tell us why it wasn't working the way you expected.
Now that I'm looking at it, what did yours do wrong?
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for quiz in quizes:
grade = eval(input("Enter " + quiz[0] + " grade:"))
quiz.append(grade)
print(quiz)
print(quizes)

Handling input data quality with checks & default value

I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))

using loops for input list by user

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

password strength code help python

so i am writing code in python to tell you your password strength but it is not doing as i say and keeps saying invalid password password unless you use only numbers
hy=1
while(y==1):
passwordentered=str(input("plaese enter your proposed password "))
x=len(passwordentered)
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
if(numbers>0 and lowerletters==0 and higherletters==0):
david=9
elif(lowerletters>0 and numbers==0 and higherletters==0):
david=9
elif(higherletters>0 and numbers==0 and lowerletters==0):
david=9
elif(higherletters>0 and numbers>0 and lowerletters==0):
david=8
elif(higherletters>0 and lowerletters>0 and numbers==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters==0):
david=8
elif(numbers>0 and lowerletters>0 and higherletters>0):
david=7
elif(x>12 or x<6):
david=10
elif(lowerletters==0 and numbers==0 and higherletters==0):
david=10
if(david==10):
print("the password you entered was invalid\
why not try again.")
y=1
elif(david==9):
print("the password you entered is very weak,try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==8):
print("your password is good but it could be better try to include numbers, lower case letters and upper case letters. why not have another go.")
y=1
elif(david==7):
print("your password is really good. thank you for using this program")
y=0
any help would be appriciated
First of all, Python is a very forgiving language, you can get away with a lot of stuff that you can't do in other languages, HOWEVER:
numbers=passwordentered.count("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
Will not work. Python will evaluate everything within the brackets as a boolean expression and this line of code essentially boils down to:
numbers=passwordentered.count("9")
The same goes for the other checks as well. To get what you actually wanted from this, you should use a loop of some sort. You can use something like this:
numbers = sum( ch.isdigit() for ch in passwordentered )
This will give you a count of how many digits are found within the password string. You can modify this to count the number of lowercase and uppercase letters too.
Finally, you should try to clean up your if statements, you could break them down a bit more neatly and make this more readable.
Those count functions won't work if written like that.
Try to replace this:
numbers=passwordentered.count ("1"and"2"and"3"and"4"and"5"and"6"and"7"and"8"and"9")
lowerletters=passwordentered.count ("a"and"b"and"c"and"d"and"e"and"f"and"g"and"h"and"i"and"j"and"k"and"l"and"m"and"n"and"o"and"p"and"q"and"r"and"s"and"t"and"u"and"v"and"w"and"x"and"z")
higherletters=passwordentered.count ("A"and"B"and"C"and"D"and"E"and"F"and"G"and"H"and"I"and"J"and"K"and"L"and"M"and"N"and"O"and"P"and"Q"and"R"and"S"and"T"and"U"and"V"and"W"and"X"and"Z")
with the following:
numbers = sum(typ in "0123456789" for typ in passwordentered)
lowerletters = sum(typ in "abcdefghijklmnopqrstuvwxyz" for typ in passwordentered)
higherletters = sum(typ in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for typ in passwordentered)
or the following for a verbose approach:
numberlist = "0123456789"
Lletterlist = "abcdefghijklmnopqrstuvwxyz"
Hletterlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers=0
lowerletters=0
higherletters=0
for f in xrange(0, x):
if numberlist.find(passwordentered[f]) != -1:
numbers = numbers+1
if Lletterlist.find(passwordentered[f]) != -1:
lowerletters = lowerletters+1
if Hletterlist.find(passwordentered[f]) != -1:
higherletters = higherletters+1

Simple python program

Bear with me, i'm extremely new to the world of programming. I'm trying to design a simple data entry/answer program for ICD-9 codes related to medical billing.
Example:
Enter ICD-9: "487.1"
Answer: "Influenza with respiratory manifestations"
Enter ICD-9 Code: "844.2"
Answer: "Cruciate Ligament Tear of Knee"
I sketched this out in a few minutes, but I have no idea how to get the program to read a range of numbers instead of just the one number. I'm also getting ValueErrors: invalid literal for int() with base 10: 844.2, so I used 844 just to test.
Filename: icd9wizard.py
number = 844
running = True
while running:
guess = int(input('Enter ICD-9 Code: '))
if guess == number:
print('Cruciate Ligament Tear of Knee')
elif guess < number:
print('Invalid entry')
else:
print('Invalid entry')
I know it's basic.. I just need an arrow pointing me in the right direction.
Thanks!
If you've got a predefined set of numbers that you'd like to use, you can test for inclusion in a dictionary:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
running = True
while running:
guess = raw_input('Enter ICD-9 Code: ')
if guess in good_numbers:
print good_numbers[guess]
else:
print('Invalid entry')
In Python, the int data type can hold only whole integers, with no fractional part. For your application, since you won't be doing any actual arithmetic with the entered numbers, it's probably best to keep them as a string. So don't call int at all:
number = "844"
guess = input('Enter ICD-9 Code')
Notice how I changed number so that "844" appears in quotes. This means it could contain any character values, such as "844.2" or "fred".
There is another data type called float that holds floating point values (numbers with fractional parts). However, this type is not suitable for your application because you're not going to do calculations with these numbers.
You can fix the ValueError by using float() instead of int(). An int is incapable of storing non-integers, i.e. numbers with values after the decimal point.
As for the rest of your question, you should think about using a dictionary (see the python documentation) with the ICD-9 codes as the keys and the answer/description as the values. This way you can put in a ton of codes and descriptions without having to use a giant block of if and elif. Consider filling this dictionary by reading in a file or something.
For example (once you have filled the dictonary):
number = 844.2
running = True
while running:
guess = float(input('Enter ICD-9 Code: '))
if guess in icd_9_dict.keys():
print(icd_9_dict[guess])
else:
print('Invalid entry')
don't use input() which tries to interpret the value given by the user (and can pose some security problems). Prefer raw_input() which always return a string. Then you can compare strings instead of numbers.
A Python dictionary is also a nice structure for what you are trying to build.
You should cast it to float() instead of int(). After you convert to float, you can get the integer part with int().
s = "100.3"
f = float(s) # 100.3
i = int(f) # 100
To read a range of values, you can do something like this:
s = input("Enter some values separated by space: ")
a = [float(value) for value in s.split(" ")] # array of floats
If you want N values, you can use a loop:
for i in range(N):
s = input("Enter a value: ")
# do something with this value
Your question is not clear, please improve it if you want a better answer.
First of all, 844.2 is float, not int :)
For range of numbers - you mean like this?:
487.1 456.4 654.7
Than use split(' ') on your input. Use raw_input to always get whole line as a string, than you can do with it whatever you can do with strings.
edit as noted in other answers - if this codes has nothing to do with numbers (beside digits in them;] ) - leave them as strings.
I'm just going to put it out there that it's always better to ask for forgiveness than to ask permission. This is a python best practice, which may not be relevant to you as a beginning programmer, but it's good to get started on the right foot.
try just says "try to do the following stuff" and except says "if there was one of the following errors when you tried to do the above stuff, do this stuff instead". You can tell that KeyError is the right error to put here if you try to access your dictionary with an invalid key (try it yourself in the interactive interpreter, it will always list the exception) just like you were getting ValueError exceptions before:
good_numbers = {"487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee",
"133.7": "Being awesome at code"}
while True:
try:
guess = input('Enter ICD-9 Code: ')
print(good_numbers[guess])
break
except KeyError:
print('Invalid entry')
continue
Oh and just to mention also that break says to quit looping out of the inner-most loop and continue says to go back to the beginning of aforementioned loop.
Enter ICD-9 Code: asd
Invalid entry
Enter ICD-9 Code: 487.1
Influenza with respiratory manifestations
>>>
Now just to point you in the right direction, you might be wanting to read input from a file; in this case, you're going to want to investigate the open command. To parse the input you can probably use split or something:
med_codes = open('IDC-9-2011.txt', 'r')
code_list = med_codes.read().split()
Then you can feed your codes into your dicitonary one at a time like:
for code in code_list:
try:
print (good_numbers[guess])
except KeyError:
print ( code, 'is an invalid IDC-9 code')
I think the main advantage here is that you know that you have some finite input, so you don't have to mess around with while loops and running counters or anything.
Oh yeah and remember to close your file when done!
med_codes.close()
Create a dictionary of results indexed by the values you're looking for like:
ICDCODES = { "487.1": "Influenza with respiratory manifestations",
"844.2": "Cruciate Ligament Tear of Knee" }
Then just compare and match:
print ICDCODES[input('Enter ICD-9 Code: ')]

Categories

Resources