I am doing problem set 7; my code output True or False as per instruction but it didn't pass check50.
check50 returned:
Traceback (most recent call last):
File "/tmp/tmp2vk2c_gh/test_correct_ipv4_localhost/testing.py", line 3, in \<module\>
print(validate(input("IPv4 Address: ")))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/tmp/tmp2vk2c_gh/test_correct_ipv4\_...
Kindly assist.
Here is my code
import re
def main():
# prompting use for IPV4
ip = input("IPv4 Address: ")
numbers = get_num(ip)
print(validate(numbers))
def get_num(ip):
# search for a valid IPV4 sequence in a string
m = re.search(r"^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$", ip)
if m:
# convert each group in a sequence to an int
number1 = int(m.group(1))
number2 = int(m.group(2))
number3 = int(m.group(3))
number4 = int(m.group(4))
# return a list of numbers
return [number1, number2, number3, number4]
# if no match found return None
else:
return None
# validate ip address
def validate(numbers):
# if there was a match
if numbers:
for number in numbers:
# check if each number in
if 0 <= number <= 255:
number = number
else:
return False
return True
else:
return False
if __name__ == "__main__":
main()
Now that I look at the traceback more closely and compare to the code above, I see why the error occurs. I will explain.
The last line of the traceback displays the line with the error. It is:
Traceback (most recent call last):
...
print(validate(input("IPv4 Address: ")))
This is what the Python interpreter was trying to execute when the error occurs. It also tells you this is line 3 in file testing.py. So, the error isn't in your code (per se), but when testing.py calls your code.
Now, look at your main() function (code snippet below):
ip = input("IPv4 Address: ")
numbers = get_num(ip)
print(validate(numbers))
Notice how input() returns ip. You then call get_num(ip) which returns numbers, and THEN it calls print(validate(numbers)). You have an extra step between input() and validate() that is not in the testing code. That's not how your program is supposed to work. You should get the input and call validate() directly -- no intermediate functions. That's why it doesn't work when called from testing.py.
I assume you fixed the error by migrating get_num() into the validate() function?
Related
I have a script that will accept a random number from a server and then it will tell me if its even or odd, however when I run it I get an error
TypeError not all arguments converted during string formation
Here is the full error message:
Traceback (most recent call last):
File "client.py", line 18, in
if (RNUM % 2) == 0:
TypeError: not all arguments converted during string formatting
Here is the code:
from socket import *
s=socket(AF_INET, SOCK_STREAM)
s.connect(("localhost",6000))
r=s.recv(1024)
clientname = "Edward"
print("This is " + clientname + "\'s client")
while(True):
a=int(input(r))
if(a >= 1) and (a <=20):
s.send(bytes(str(a), 'utf8'))
rnum=s.recv(1024)
#mat=s.recv(1024)
RNUM=rnum.decode('utf8')
#MAT=mat.decode('utf8')
print("Random Number From Server:",RNUM)
if (RNUM % 2) == 0:
print("{0} is Even number".format(RNUM))
else:
print("{0} is Odd number".format(RNUM))
#print("Random Number + Number given = ", MAT)
else:
print("Invalid Integer, try again")
The variable RNUM is a string. To convert it to an integer, call int(RNUM).
After you get to the part when the program prints 6 it gives me the error that is mentioned below. Even though the value if properly attributed. I want it to print a 6 when the Mario.x_location value is equal to the LifeShroom.x value. Then after that, I want it to increase the value of the Mario.x_location by one whenever w is pressed. Type yes than press enter, and type w to see what I mean. What am I doing wrong?
start = input('say yes: ')
class Mario:
x_location = 4 #location of you
class LifeShroom:
x = 4 #location of the object.
if start == 'yes':
while start == 'yes':
command = input('') #press enter here, after you input yes.
if command == 'w':
Mario.x_location += 1 #change Mario.x_location
print(Mario.x_location,)
rules = [Mario.x_location == LifeShroom.x,]
if all(rules):
LifeShroom = True
if LifeShroom:
print(6) #type w again after it prints 6 and you will get the error below.
Exact error that I got:
Traceback (most recent call last):
File "main.py", line 25, in <module>
rules_8 = [Mario.x_location == LifeShroom.x,
AttributeError: 'bool' object has no attribute 'x'
I can say that you are doing a infinite loop. There is no scape for the while loop.
In the first if-statement isn't runned the first if (if command == 'w':), but runs the other two. In the first one, it destroies your class (LifeShroom = True). But it is True, so it will run the third. Your variable LifeShroom is not more a class but a boolean (True).
Next loop there is no more LifeShroom class, so no LifeShroom.x class atribute.
In the Below code i am trying to get the user input until it matches the value in the 'type_details' dictionaries.
But the function is returning the invalid input but not the correct value entered finally
Enter the preferred Type:fsafs
Please Choose the Type available in the Menu
Enter the preferred Type:Cup
Traceback (most recent call last):
File "C:\Users\Workspace-Python\MyFirstPythonProject\Main.py", line 186, in <module>
typeprice = type_details[typeValue]
KeyError: 'fsafs'
Below is the code
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
type = input("Enter the preferred Type:")
if not ValidateString(type):
print("Type is not valid")
getType()
else:
check = None
for ct in type_details:
if ct.lower() == type.lower():
check = True
type=ct
break
else:
check = False
if not check:
print("Please Choose the Type available in the Menu")
getType()
return type
typeValue = getType()
typeprice = type_details[typeValue]
How about something simple as this?
Get user input, check if it's in dictionary, return if so else continue in the infinite loop.
type_details = {'Plain':1.5,
'Waffle':2,
'Cup':1}
def getType():
while True:
user_in = input("Enter the preferred Type: ")
if user_in in type_details:
return user_in
user_in = getType()
print(f'You entered: {user_in}')
print(f'Type Price: {type_details[user_in]}')
Each time getType() is called (even inside itself) a new local variable type is created whose content is lost if it isn't returned to the calling function.
The content of type in the calling getType() isn't modified.
This is my code block
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
elif len(get_close_matches(words, definitions.keys())) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus[get_close_matches(words, definitions.keys())]
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
I expected to receive the meaning of the word "Grief". However, I kept receiving the error : function object is not subscriptable.
Here is the terminal log, just in case it might help:
My-MacBook-Pro:Python Adwok$ python3 dictionary.py
Look Up: GRERFAG
Did you mean grief instead? Enter 'Y' if yes or 'N' if no: Y
Traceback (most recent call last):
File "dictionary.py", line 22, in <module>
print(thesaurus(words))
File "dictionary.py", line 13, in thesaurus
return thesaurus[get_close_matches(words, definitions.keys())]
TypeError: 'function' object is not subscriptable
Please point out even the smallest details, I would appreciate that very much.
As stated by the error stack, in line 13 you are accessing thesaurus as if it was a list/dictionary (or any subscriptable object). Since thesaurus is a function (which is not subscriptable), you get an error. Thus, you need to invoke the function (instead of accessing it):
thesaurus(get_close_matches(words, definitions.keys()))
Also, you should notice:
At the end of your code you are correctly invoking the thesaurus function by calling print(thesaurus(words))
Consider reusing the result of get_close_matches to avoid multiple calls to the same function (which can lead to performance degradation if the call is resource consuming).
I suggest you the following solution:
import json
import difflib
from difflib import get_close_matches
definitions = json.load(open("data.json"))
def thesaurus(words):
if words in definitions:
return definitions[words]
else:
close_matches = get_close_matches(words, definitions.keys())
if len(close_matches) > 0:
yn = input("Did you mean %s instead? Enter 'Y' if yes or 'N' if no: " % get_close_matches(words,definitions.keys()) [0])
if yn == "Y":
return thesaurus(close_matches)
elif yn == "N":
return "None found"
else:
return "Please check word again"
words = input("Look Up: ").lower()
print(thesaurus(words))
How can I return the commented out line below the print statement at the end of this function? Also, when I run the function with the return un-commented, I get one result, but when I run the function with the return commented, I get 7 results and I'm not sure why this is happening.
What I would like to do is call track['name'] after I call the function. When I do, I get this error Traceback (most recent call last):
File "spot.py", line 25, in
track['name']
NameError: name 'track' is not defined
import requests
import json
message = "if i can\'t let it go out of my mind".split()
size = len(message)
def decrementList(words):
for w in [words] + [words[:-x] for x in range(1,len(words))]:
url = 'http://ws.spotify.com/search/1/track.json?q='
request = requests.get(url + "%20".join(w))
json_dict = json.loads(request.content)
track_title = ' '.join(w)
num_words_removed = len(words) - len(w)
new_message_length = size - num_words_removed
new_message = message[new_message_length:size]
for track in json_dict["tracks"]:
if track["name"].lower() == track_title.lower():
print track["name"], " | ", track["href"], " | ", track_title, " | ", num_words_removed
#return track["name"], track["href"], track_title, num_words_removed
decrementList(message)
A return statement causes the function to stop executing and return the value you have specified, whereas with a print statement it just causes something to be output to the terminal, and the function continues to execute.
In order to use the value that is returned from the function, you must do something with it, like assign it to a variable. For example:
track = decrementList(message)
but in that case, you would want to return the track:
for track in json_dict["tracks"]:
if track["name"].lower() == track_title.lower():
return track