How to check for white space input in python - python

I'm very new to programming and python. I'm writing a script and I want to exit the script if the customer type a white space.
questions is how do I do it right?
This is my attempt but I think is wrong
For example
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
line = inf.readline()
while (userType == raw_input)
print "userType\n"
if (userType == "")
print "invalid entry, the program will terminate"
# some code to close the app

I know this is old, but this may help someone in the future. I figured out how to do this with regex. Here is my code:
import re
command = raw_input("Enter command :")
if re.search(r'[\s]', command):
print "No spaces please."
else:
print "Do your thing!"

The program you provided is not a valid python program. Because you are a beginner some small changes to you program. This should run and does what I understood what it should be.
This is only a starting point: the structure is not clear and you have to change things as you need them.
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
#line = inf.readline() <-- never used??
while True:
userType = raw_input()
print("userType [%s]" % userType)
if userType.isspace():
print "invalid entry, the program will terminate"
# some code to close the app
break

You could strip all whitespaces in your input and check if anything is left.
import string
userType = raw_input('Please enter the phrase to look: ')
if not userType.translate(string.maketrans('',''),string.whitespace).strip():
# proceed with your program
# Your userType is unchanged.
else:
# just whitespace, you could exit.

After applying strip to remove whitespace, use this instead:
if not len(userType):
# do something with userType
else:
# nothing was entered

Related

How can I see if my password variable is within a line so that my code can proceed?

I am creating a password re-setter for school, and i want to check that if the password is within the first line of the text file, then it can say "Okay, choose a new password")
Newpass=""
Network=""
setpass=""
Newpass=""
password=""
def newpass():
Network=open("Userandpass.txt")
lines=Network.readlines()
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password in line:
newpass=input("Okay, choose a new password ")
Network.close()
Network=open("Userandpass.txt","a")
if len(newpass)>= 8 and newpass[0].isalnum()==True and newpass[0].isupper()==True:
print('password change successful')
Network.write("New Password : " + newpass )
Network.close()
break
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
Network=open("Userandpass.txt","w")
Network.write(input("What is your Username")+",")
Network.write(input("Password:")+ ",")
question=input("Do you want to change your password?")
if question=="yes":
Network.close()
newpass()
else:
Network.close()
print("Okay thank you.")
Please help! I have been looking all over here and i can't find a solution
You can try by two things :
lines=Network.read() # change here
password=input("just to confirm it is you, re-enter your old password:")
for i in range (3):
if password == lines.split(",")[1]: # change here also
Explanation :
The problem with readlines is o/p as list where read return as string which is better one to use here .
The second thing it returns as a single string ie, combined form of name and password just with ,. So if you split it you will get an list of separated values. Then you can take only password from it and check with input.
In your code you are just checking the input element is just present in that whole string, not checking whether it is same password or not
You said you needed this for school, so i assume it's somewhat urgent:
All the changes i did are minor and i commented what i did and why.
# no need to intialize these variables
#Newpass=""
#Network=""
#setpass=""
#Newpass=""
#password=""
def newpass():
# the with open() construct takes care of closing the file for you and gives you a nice handle for working with the file object.
with open("Userandpass.txt") as Network:
# this reads all filecontents into a list and while doing so strips away any kind of whitespace.
username,current_password=[x.strip() for x in Network.readlines()]
for i in range (3):
password=input("just to confirm it is you, re-enter your old password: ")
if password == current_password:
# communicate the requirements instead of letting potential users run into errors
newpass=input("Okay, choose a new password (must be 8 chars or more, alphanumeric and have it's first letter capitalized.) ")
if len(newpass)>= 8 and newpass.isalnum() and newpass[0].isupper():
with open("Userandpass.txt","a") as Network:
print('password change successful')
Network.write("New Password : " + newpass )
return
else:
print("password did not match requirements, try again ")
else:
print("error")
break
print("3 tries up or else password updated")
with open("Userandpass.txt","w") as pwfile:
# separate by newline instead of punctuation => personal preference
pwfile.write(input("What is your Username? ")+"\n")
pwfile.write(input("Password: ")+ "\n")
question=input("Do you want to change your password? (yes/no): ")
if question[0].lower() == 'y':
newpass()
else:
print("Okay thank you.")
# properly terminate
exit(0)
You are missing an 's' in the line
if password in line**s**:
maybe the problem comes from there.

How to take any input from the users in capital letters even if the user is entering it in small letters?

I am trying to generate a story using python. For this I'm trying to take the input from the users for some questions. The scenario I'm trying to get is that whenever the user enters the input, then it is displayed on the output screen in capital letters.
But what happens is that the text is diplayed in small letters.
Here is the sample of the code
message1 = input(" my name is: ")
message2 = input(" i am from: ")
message3 = input(" i love to eat: ")
print( " My name is " + message1.upper() + " I am from " + message2.upper() + " I love to eat " + message3.upper())
I expect My name is SANDEEP when the user enters sandeep, but I get sandeep.
You can use this following code for console app. I am converting the input after reading it whole. But you can do the job quiet easily and get your desired result(Converting every character as you enter to uppercase) when you'll implement it in web applications( by using html and javascript there).
import os
message1 = input(" MY NAME IS: ")
os.system('cls')
message1="MY NAME IS : "+message1.upper()
res=message1+"\n"
message2 = input(res+"I AM FROM: ")
os.system('cls')
res+="I AM FROM : "+message2.upper()+"\n"
message2="I AM FROM : "+message2.upper()
message3 = input(res+"I LOVE TO EAT: ")
os.system('cls')
res+="I LOVE TO EAT : "+message3.upper()+"\n"
message3="I LOVE TO EAT: "+message3.upper()
print(res+"\n\n\n"+ message1 +"\t"+message2+"\t"+message3)
So, this will only work on Linux systems and only with ASCII characters:
import termios
import sys
def uppercase_input(prompt):
sys.stdout.write(prompt)
sys.stdout.flush()
old = termios.tcgetattr(sys.stdout.fileno())
new = old[:]
new[1] |= termios.OLCUC
termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, new)
try:
return input().upper()
finally:
termios.tcsetattr(sys.stdout.fileno(), termios.TCSANOW, old)
result = uppercase_input("all uppercase? ")
print("yes: {}".format(result))
This uses some interesting ancient settings to convert I/O to/from uppercase from the old times when there were terminals only supporting upper-case ASCII.
From man tcsetattr:
OLCUC (not in POSIX) Map lowercase characters to uppercase on output.
So this solution is not really portable.
For a fully portable solution, you would need to implement echoing yourself.

Python repeating wrong username loop

I'm trying to make a system that checks for a user name in a separate text file, and if it doesn't exist tell them this and prompt them to re enter the password. This works the first time they get the username incorrect, however subsequent times it repeats the message multiple times.
Here is the code I have so far:
def existingUser():
annoyingProblem = 0
print("Welcome back")
while True:
existingUsername = input("What is your user name?")
for i in range(100):
with open("logins.txt", "r") as logins2:
for num, line in enumerate(logins2, 1):
if existingUsername in line:
correctPassword()
else:
if annoyingProblem == 99:
print("That doesn't seem to match. Please try again")
else:
annoyingProblem = annoyingProblem + 1
If I understood correctly you want to check whether the given username is valid , and if its wrong you want give 99 chances to user
input.txt
sandeep
lade
venkat
Code(here max chances are 3)
def existingUser():
annoyingProblem = 0
print("Welcome back")
while True:
existingUsername = str(raw_input("What is your user name?"))
with open("infile.txt", "r") as logins2:
for num, line in enumerate(logins2, 1):
if existingUsername in line:
correctPassword()
print("That doesn't seem to match. Please try again")
annoyingProblem = annoyingProblem + 1
if annoyingProblem == 3:
print("exceeded number of attempts")
break
Output
>>> existingUser()
Welcome back
What is your user name?nope
That doesn't seem to match. Please try again
What is your user name?nope
That doesn't seem to match. Please try again
What is your user name?nope
That doesn't seem to match. Please try again
exceeded number of attempts
I don't even know how that compiles, as long as you have an "else" in a different tab column than the "if". Maybe that can be your problem, as you are testing things in a way you don't want. Also, existing username is read once and is not changed. So the "if" will be true a hundred times!
I think you dont have to use all the looping stuff. As each username is a line.. we can use the below as the file probably will not be huge.. like 100mb..
def existingUser():
existingUsername = input("What is your user name?")
if existingUsername in open('logins.txt').read():
correctPassword()
else:
print("That doesn't seem to match. Please try again")

Struggling with Python

I must answer this question in python but I'm not sure what i must do, this is the question:
Your program should read in multiple lines of input from the user, stopping when the user enters a blank line. Each line will be a command from the user to the phone. Each command consists of a space-separated sequence of words.
If the first word is Add, there will be two words following it: the name of the person and their phone number. If an Add command is encountered, your program should store this name to phone number mapping. Alternatively, if the first word is Call, there will be one word following it: the name of the person to call. In this case, if the phone knows the number for this person, your program should print out that it is calling that number, otherwise it should print out that it does not have a number for this person.
The program I have written is this:
contact = {}
**line = input('Command: ')
while line:
parts = line.split()
name = parts[0]
number = parts[1]
contact[name] = int(number)
line = input('Command: ')**
What more should I add or do to make this program work?
You need to distinguish the different commands.
contact = {}
line = input('Command: ')
while line:
parts = line.split()
command = parts[0]
if command == 'Add':
contact[parts[1]] = parts[2]
elif command == 'Call':
pass
# add the code to find the number and print it
line = input('Command: ')**
To start with you need to add a loop to keep asking the user for a command until they enter a blank line.
When writing an script which interacts with a user, it is also wise to think in terms of what the user could do wrong. The problem states a number of requirements, for example, if Add is entered, there should be two words following. If the user only entered one, what should you do?
Also what happens if the user enters a name that has not yet been entered? Python dictionaries provide a get() method which handles this. It allows you to specify what needs to be returned when the requested key is not present. In this case, you can return "Unknown name".
The following shows what I mean:
line = ' '
contacts = {}
while line:
line = input('Command: ')
if line:
words = line.split()
if words[0] == 'Add':
if len(words) == 3:
contacts[words[1].lower()] = words[2]
else:
print("Badly formatted Add")
if words[0] == 'Call':
if len(words) == 2:
print(contacts.get(words[1].lower(), "Unknown name"))
else:
print("Badly formatted Call")
By using the .lower() command on the entered name, it would then mean the user could do "Add Fred 1234 / Call fred" and it would still find a match.

Force a raw_input

How would I implement the following:
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if not title:
# repeat raw_input
title_selection = ''
while not title_selection:
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
It is necessary to define title_selection as '' before hand, which means empty (also False).
The not will make False to True (negation).
This is often done with a "loop-and-a-half" construct with a break in the middle:
while True:
title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
if title_selection:
break
print "Sorry, you have to enter something."
This method gives you an easy opportunity to print a message telling the user what the program expects.

Categories

Resources