Why is the input() function returning None? - python

So I am using Jupyter notebook and when I run the code
name = input(print('What is your name?'))
The code will produce the output:
What is your name?
None []
Since I cant copy and paste the rectangle that comes when using the function input(), lets asume the brackets represent that rectangle. Then say you write John Doe in the box, it will then show NoneJohn Doe Why is the word None shown next to the name and the box? How do you remove it? Thanks

I believe you want to prompt the user to type his/her name and then print out the name?
if so, try this:
name = input('What is your name?')
print('Your name is '+ name)
Also with this in mind.
Input takes a prompt string as its argument, which it will print automatically, but print returns None; it is this that gets printed by input. Your code is equivalent to:
name = print(...) # prompt == None
ans = str(input(name))
Instead, use str.format to build the prompt and pass it straight to input

Related

Python: How to require an input to correspond with a previous input?

all. Python newbie here.
Simply-put here is my basic idea:
I want to create a "Login" feature where people must input a valid username from a preset tuple.
Next, once a valid name is entered, they will be asked to enter the corresponding code name, which is saved to a dictionary. (I have a feeling that I am over-complicating this, or maybe the dictionary is the wrong idea entirely, so any advice on how to simplify would be great).
real_names = ("JD", "JM" "JC")
player_ids = {"JD":"Arrow","JM":"Bullet","JC":"Blade"}
while True:
# user must input a name from the real_names tuple
name = input("User unidentified. Please input your name: ")
# if username is not in tuple, rerun script
if not name in real_names:
print("Invalid username detected")
continue
print(f"Positive ID! Welcome, {name}")
break
The above code works just fine. But next, I want to make a new input that requires the player ID to match the previously input name. In Pseudo-code, something like this:
# While True Loop:
id = input("Please confirm user Code Name: ")
#ID must correspond to keyword in dictionary
if ID value does not match username Keyword:
print("Invalid ID")
continue
print("Identity confirmed!")
break
Am I on the right path? If so, how would I syntax the second part? If the dictionary is the wrong idea entirely, please provide a good alternative. Many thanks!
player_ids[name] is the value you're looking for. So, you want something like this:
if id != player_ids[name]:
print("invalid ID")
Also, the dictionary already keeps track of player names, so you don't need the real_names tuple.
This previous answer works perfect, because you are looking up the value based on the key from a dictionary. Finally, one little tip, it's always good practice to avoid naming variables after reserved variables and keywords, that is to say, use another variable name just in case you are going to use to use the id() function again in the program.

why am i unable to use list object syntax and am met with AttributeError: when running my program

i apologise for the longevity of this question
I want to write a piece of code which essentially checks if the str name of an input has already been added within a txt file, let me tell you this scenario:
I am using Classes and Listing in order to structure my data (stored in a txt file) for comparisons later, I am using the code that follows:
import csv
class Volunteer:
def __init__(self,name,coin_type,weight_of_bag,true_count):
self.name = name
self.coin_type = coin_type #a function allowing me to class the data
self.weight_of_bag = weight_of_bag
self.TrueCount = true_count
with open("CoinCount.txt","r+") as csvfile: #opens file as CSV *IMPORTANT*
volunteers = []
for line in csvfile:
volunteers.append(Volunteer(*line.strip().split(',')))
I have also created some more simple code such as a menu etc, within this menu though I want to include the ability to input new volunteers, for now i havent actually gotten to the stage of appending new data to the txt file however, i am at the moment trying to create an inspection which checks if the inputted volunteers name has already been used before, just for more information, i will send the data within the txt file:
Abena,5p,325.00,Y
Malcolm,1p,3356.00,Y
Jane,£2,120.00,Y
Andy,£1,166.25,N
Sandip,50p,160.00,Y
Liz,20p,250.00,Y
Andy,20p,250.00,Y
Andy,50p,160.00,Y
Jane,£1,183.75,N
Liz,£,179.0,N
Liz,50p,170.0,N
Jane,50p,160.0,Y
Sandip,£1,183.0,N
Jane,£2,132.0,N
Abena,1p,3356.0,N
Andy,2p,250.0,N
Abena,£1,175.0,Y
Malcolm,50p,160.0,Y
Malcolm,£2,175.0,N
Malcolm,£1,175.0,Y
Malcolm,1p,356.0,Y
Liz,20p,250.0,Y
Jane,£2,120.0,Y
Jane,50p,160.0,Y
Andy,£1,175.0,Y
Abena,1p,359.56,N
Andy,5p,328.5,N
Andy,£2,108.0,N
Malcolm,£2,12.0,N
I will also give you the code for this part of the menu so that if you wish to explain to me how to fix it you will be able to use the same variable names
def open_menu_1():
inputvolunteername = input("Enter the volunteers name you wish to add: ")
if hasNumbers(inputvolunteername):
yes_or_no = input("volunteer name contains numbers, would you like to try again? ")
if yes_or_no == "yes" or "Yes":
print("")
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
open_menu()
elif any(not c.isalnum() for c in inputvolunteername):
yes_or_no = input("volunteer name contains special characters, would you like try again? ")
if yes_or_no == ("yes" or "Yes"):
open_menu_1()
else:
print("")
print("you have been sent back to the main menu")
print("")
elif inputvolunteername == volunteers[0].name:
print("oi")
I designed a tiny grain of the code i would need to test out if it would work,that is displayed at the bottom of the code above
i essentially ran the program and typed in as the input the first name on the txt file (Abena) and by doing so, the console printed "oi". I thought this would be as difficult as this part of the code got as i thought all i would have to do now is replace
elif inputvolunteername == volunteers[0].name:
print("oi")
with
elif inputvolunteername == volunteers[0:].name:
print("oi")
i thought this would work because in lists this usually would go through all from 0 to infinity until there was nothing else to search from that name class category, however in actuality once i ran the program i was greeted with the following message:
elif inputvolunteername == volunteers[0:].name:
AttributeError: 'list' object has no attribute 'name'
this confused me as I do have an attribute 'name' and that is made evident by the fact that that the other line of code which i tested out did work however by simply adding a colon it says that there is no attribute,
please let me know what i need to change to the bottom line of code in order to make the program detect whether the inputvolunteername is equal to any of the names already written on the txt file.
There are duplicates in CSV... so to test for name in volunteer list of names I recommend using set()
inputvolunteername in set([v.name for v in volunteers])
The following return True
'Abena' in set([v.name for v in volunteers])

An Element From a List Won't Properly Convert to a String

I've been working on a login and signup code that is not connected to the cloud. To login, you must enter a username and password, and it will return you with a simple; "Hello, "
I've tried converting the element to a string, but I couldn't find anything else online to help me. It could possibly be that the program I'm using doesn't display an output properly.
inorup=""
newuser=""
users=["jdoe,tractor5","carrey1,1997","admin,56f67dk2997m"]
firstnuser=["John","Carrey","Frederick"]
while inorup != "login" or inorup != "signup":
inorup=raw_input("Would you like to login or signup? ")
if inorup=="login":
userpass=raw_input("Enter <username,password>: ")
if userpass in users:
userpassfnamepos=int(users.index(userpass))-3
print("Hello",str(firstnuser[userpassfnamepos])+".")
#Returning:
Would you like to login or signup? login
Enter <username,password>: jdoe,tractor5
('Hello', 'John')
#Expected Return:
Would you like to login or signup? login
Enter <username,password>: jdoe,tractor5
Hello John.
You should split your string on the ',' and check username password against a dictionary like {username:password}, or use a database or something. Checking string as you do now is kind of limiting and unwieldy.
But to just fix your output, you can change your print to this
print("Hello {}.".format(firstnuser[userpassfnamepos]))
using string.format() also does all the casting and such so you could pass in numbers or whatever you want, not just name. More info Here
and you will get the expected output.
output =
Would you like to login or signup? login
Enter :
jdoe,tractor5
Hello John.
You are already using normal string concatenation to add the period. Why not just do that with the name as well? You also don't need the str in front, since the list is already a list of strings, and so the element in question is already a string.
print("Hello" + " " + firstnuser[userpassfnamepos] + ".")
>>>Would you like to login or signup? login
>>>Enter <username,password>: jdoe,tractor5
>>>Hello John.
Looks like you are mixing python 2 and 3. raw_input id python 2 and in Python 3 it's only input. also, you should use brake to break out of the loop at appropriate places. You have an infinite loop. Lately, the code is printing "Hello John" for me as it's supposed to. However, you don't have to convert the list element to string, it is already a string (therefore returns the same value with or without converting.
I think the reason it's giving you ('Hello', 'John') as output is because it's printing the parenthesis themselves (but that does not make logical sense because they are not included in the string. Anyways note that python 2 print statement is as follows: print "this is to be printed" . there is no parenthesis. Make use of the vertion of python you are using and that your code matches the version.
One additional note, if you are not using a database, maybe use a python dictionary instead of a python list. Not only it's faster and memory efficient, it also makes it easier to work with. it can be something like {username : ("name" , "password")} a combination of a dictionart and a tuple or more explicit {username : {name: "name" , password: "password"}}, which saves a sigle's user data in a dictionary inside a dectionary containing all the users.

How to ask user's name with the use of def function more efficiently

I've basically made a def function to ask user's name with the input
but when I tried to make an input to get the user's name accordingly, I came to realise that each input has to be assigned individually so as to later print that input linked according to what the user inserted their name.
## Ask user's name with the use of def function.
def asking_username():
print("What's your name? ")
username = input()
return username
print("Hello, " + asking_username().title() + "!")
The code above that I made has no problem, but I'd like to make the input to get an user insert in the same line as the print("What's your name? ").
How do you individually assign each input so that it does not get confused with the other input in case multiple inputs are inserted?
How about:
username = input("Enter your name\n")
This works, because I'm using the newline character ("\n").

Why does this code that uses .isalnum not work?

name = ""
name = input("Hi there, what is your name? ")
while name.isalnum():
name = input("Hi there, what is your name? ")
while name.isdigit():
name = input("Hi there, what is your name? ")
This is what the code looks like, but I only want it to accept letters only. When I run this code however, there is a problem and the program keeps asking for the user's name for any input provided, the only way the program continues is if a 'space (bar)' is pressed. What is wrong with this?
while name.isalnum():
Means that the loop will keep running as long as name is alphanumeric. You want:
while not name.isalnum():
Your goal can be better achieved through regex:
import re
p=re.compile(r'[a-zA-Z\s]+$')
name="user0000"
while not p.match(name):
name = input("Hi there, what is your name? ")
This will accept names like "George Smith" but not "Smith1980"

Categories

Resources