I am attempting to limit the character length of my input and then verify whether it is one of the three white characters. Struggling with the final part:
while True:
try:
letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
assert len(letter) !=1
except AssertionError:
print("Please type only ONE character")
else:
whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
if whitespace not in letter:
print("Your character in lower case is: "+str(letter).lower())
else:
print("You typed a white space character!")
Welcome to Stackoverflow!
It looks like the error is on the if whitespace not in letter: line. This should actually be the other way around: if item not in list:. You have if list not in item:.
Also, it might help you if I reformat your code a little.
while True:
letter = input('Please enter a character: ')
if len(letter) != 1:
print('Please type only ONE character')
continue
if letter in ['\n', ' ', '\t']:
print("You typed a white space character!")
continue
lowercase_letter = letter.lower()
print(f'Your character in lower case is: {lowercase_letter}')
If you haven't already seen pylint, I'd recommend you take a look at it. It helps you format your code to PEP8 standard. It is also quite good at pointing out some simple errors in your code.
Raising Exceptions are for reporting errors to calling functions - i.e. you can't perform the job the function is supposed to be doing because the input or system state is not as required by the function.
Catching Exceptions is for handling specific errors you know how to handle in a higher level function. So for example, if your trying to read a file and it doesn't exist. In your program that mean the user hasn't set a specific flag in the config file... so you can catch that exception and let the user know how to fix the issue.
Raising an Exception and catching it in the same function (at least in this case) is just a very complicated way of writing an if statement.
When writing an if-else statement, it's a good idea to try and make the if branch positive. Which means avoid if not ...: else: if you can.
In your code, letter is already a string object - so there is no need to create a new string object with str(letter). In python everything is an object, even literals.
The continue statement jumps to the next iteration of the loop. Nothing after the continue is executed in the current iteration of the loop. You could also look at break statement that finishes executing the loop. As an exercise, you could look at adding an extra check to your code to see if the user typed 'quit', and then break. What do you think will happen?
if letter.lower() == 'quit':
break
This would have to be added before the check for single letters otherwise you would never get to this check.
Finally, rather than using string concatenation in your print statement (using str + str). You can use f-strings, format strings as in the example f'Hi my name is {name} and I am from {home}', where name and home are string variables.
Hope this helped!
I'd advise you not to use exceptions because they're very unstable. Instead, I'd use if/else conditions, like this one:
letter = input('Please enter a character: ')
if len(letter) == 1:
if letter in '\n\t ':
print('You typed a white space character!')
else:
print('Your character in lowercase is {}'.format(letter.lower()))
else:
print('Please type only ONE character')```
Related
Beginner with Python but I wanted to use a list to contain multiple potential string responses that the user may give in the input.
def Front_Door():
print("Welcome to the Party Friend!")
Emotional_state = input("How are You Today? ")
Positive_Emotion = ["good", "fine", "happy"]
I tried to use an if statement to get python to check through my list to see if the input contained any of the strings listed in the e.g. I gave.
if Positive_Emotion in Emotional_state:
print("That's Great! Happy to have you here!")
The code still manages to prompt me for Emotional_state but it just repeats the question one more time, if I respond with one of then strings I've listed again it gives me this error:
if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list
I'm guessing there is a method to make Python search through my list of strings and cross reference it with my inputs and give me the response I want?
Any help is appreciated :).
You are checking if the whole list is in the string!
What you probably want to do is check if any of the items in the list are in the string.
Something like:
if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
print("That's Great! Happy to have you here!")
This will check each emotion in the list, and if any of them are in the string it will return True.
Hope this helps.
I'm all too late to the party, but here are my two cents.
You only need Positive_Emotion and Emotional_state to switch places in your if statement, so that it becomes:
if Emotional_state in Positive_Emotion:
print("That's Great! Happy to have you here!")
I made a text file with names in and my codes works but has a big flaw i want to know if they is any way i could fix this issue.Lets say the names are 'bob' 'jim' 'mark'.If entered 'ar', it would allow you to enter since ar is in the text file. Thank you for any time.
import sys
namefile=open("names.txt","r")
filenames=namefile.read()
namefile.close
if name1 in filenames:
print("Welcome",name1)
else:
print("ACCESS DEINED")
sys.exit(0)
name2=str(input("What is the name of player2? "))
if name2 in filenames:
while name2==name1:
if name2==name1:
print("This name is already taken, please choose another.")
name2=str(input("What is the name of player2? "))
if name2 in filenames:
print("Welcome",name2)
else:
print("ACCESS DENIED")
sys.exit(0)
Before I answer the question, I would like to point out that the if statement you use in the while loop is unnecessary. If the while loop executes, the if is guaranteed to be true.
Now, to solve your problem, simply do this: When adding a name to the file, add a space before and after it. Then, when checking if a name is present in the file, add a space before an after the input from the user. The spaces will function as a start and end character, meaning that no "partial matches" will happen. You could also use any character's you want, rather than just a space.
I hope that this helps you moving forward!
hello all I am python programmer
I made a program with spyder IDE with python 3.7.0
when I ran this program the program didn't execute the desired action
that is they don't shutdown this pc or lock it and doesn't open cmd
can you show me the mistake and if possible correct the code by typing below
import os
import ctypes
command = "cmd"
print ("select from any commands")
print ('1.open CMD')
print ('2.shutdown pc')
print ('3.restart pc')
print ('4.lock pc')
choice = input()
if choice == 1: #starts command prompt
os.system(command);
if choice == 2: #trigger shutdown
os.system("shutdown -p");
if choice == 3: #trigger restart
os.system("shutdown -r");
if choice == 4: #trigger lockscreem
ctypes.windll.user32.LockWorkStation()
[Python 3]: input([prompt]) returns a string. When comparing a string with an integer (e.g. "1" == 1), the result will always be False.
To fix your problem, either:
Convert each of the 4 values (used in comparisons) to a string, by placing its value between quotes e.g:
if choice == "1":
Convert input's result to an integer e.g.:
choice = int(input())
but you'll have to enclose that in a try / except block (to avoid program crash if user doesn't input an integer)
Notes (to improve your code):
When calling functions, always check their return value (which may be an error indicator)
Since the 4 are choices, then they are mutually exclusive, meaning that only one (or none) will be executed. As a consequence, you could replace each of the last 3 if clauses by an elif, so if the program entered one branch, it won't test for the ones that follow it
You could also add a final else clause, where you could let the user know that none of the choices executed (the value entered was different than all of them)
Instead of the 5 print statements (for the menu), you could just pass one string (you'll have to format it) to input:
choice = input("select from any commands:\n 1.open CMD\n 2.shutdown pc\n 3.restart pc\n 4.lock pc\n")
For better flexibility, you could use the subprocess module (instead of os.system) to execute external commands
ctypes is a tricky topic, and although if for this case things are fine, for more complex ones (e.g. calling a function with parameters) it might not work as expected. There are many examples (on this site and on others) showing how to deal with such cases
When program doesn't work as expected, you could always debug it, or at least print the variables involved, and thus increase the chances of figuring the problem yourself
I'm coding this telegram bot for my clan. The bot should send a reply based on a few words in the text msg. Suppose I type a text in the group containing the words "Thalia" and "love" and I want the bot to respond. The following works.
elif "thalia" in text.lower():
if "love" in text.lower():
reply("I love u too babe <3." "\nBut I love my maker even more ;).")
else:
reply("Say my name!")
msg containing thalia and love
I coded it like this because when I use the "and" or "or" keywords the statement doesn't work and the bot goes crazy. In the above, if I code: elif "thalia" and "love"..... it doesn't work.
If there is another way to code this I would appreciate the tip!
Now I am trying the same technique on more words with "and" and "or" but it doesn't work. If I leave "and" and "or" out it works fine. But of course then I can't use the combinations of words I want with this particular response.
elif "what" or "when" in text.lower():
if "time" or "do" in text.lower():
if "match" in text.lower():
reply ("If you need assistence with matches, type or press /matches")
it triggered the command without the 3 words in one sentence
How can I rewrite this code in a more "professional" way and what do I need to change to get it to work? The bot responds only when the combination of the words are used like in the thalia love code. Instead of when "matches" is used.*
Python is much like natural language but the interpreter cannot fill in what human listeners can. 'a and b in c' must be written out as 'a in c and b in c'.
Before writing the if statements, you should lower case text once, not repeatedly. Then turn it into a set of words, after removing punctuation and symbols, to avoid repeated linear searches of the lower-cased string. Here is an incomplete example for ascii-only input.
d = str.maketrans('', '', '.,!') # 3rd arg is chars to delete
text = set(text.lower().translate(d).split())
Your 'matches' snippet can then be written as follows.
elif (("what" in text or "when" in text) and
("time" in text or "do" in text) and
"match" in text)
reply ("If you need assistence with matches, type or press /matches")
You could also use regular expression matching to do the same thing, but logic statements like the above are probably easier to start with.
I need help with an ATM python program that I am creating. I am new to Python and I am worried that my coding is so off that I must start from the beginning. I am trying to separate the sections by def (): and I keep getting an error.
Traceback (most recent call last):
File "/Users/tonystrobach/Desktop/untitled3.py", line 44, in <module>
deposit()
File "/Users/tonystrobach/Desktop/untitled3.py", line 35, in deposit
if (answer == "D") or (answer == "d"):
NameError: global name 'answer' is not defined
I have been searching a long time and trying to grasp the concepts of Python the best I can. Any suggestions would be helpful.
Here is my code:
The purpose of this program is to create a simple ATM environment
Written by K. Strobach 11/22/13
def account():
print ("Hello, welcome to Bank of Python!")
print ("Please enter your account pin number")
account = raw_input("Account pin number is 1234: ")
account = (1234)
account()
def balance():
print ("would you like to see your account balance?")
see = raw_input("Enter Y or N: ")
if (see == "Y") or (see == "y"):
balance = int(0)
print ("Current balance: $" + str(balance))
balance()
def transaction():
print ("Would you like to make a transaction?")
more = raw_input("Enter Y or N: ")
if (more == "Y") or (more == "y"):
print ("Would you like to make a deposit or withdraw? Or would you like to end this transaction?")
answer = raw_input("Enter D for deposit; W for withdraw; E for end: ")
transaction()
def deposit():
if (answer == "D") or (answer == "d"):
print ("How much would you like to deposit?")
deposit = input("Enter amount to deposit: ")
deposit = int(deposit)
currentbalance = deposit + balance
print ("Deposited: $" + str(deposit))
print ("Current Balance: $" + str(currentbalance))
deposit()
def withdraw():
if (answer == "W") or (answer == "w"):
print ("How much would you like to withdrawl?")
withdraw = input("Enter amount to withdraw: ")
withdraw = int(withdraw)
currentbalance = withdraw - balance
print ("Withdrew: $" + str(withdraw))
print ("Current Balance: $" + str(currentbalance))
withdraw()
def end():
if (answer == "E") or (answer == "e"):
exit ("Thank you for Banking with Bank of Python, goodbye!")
else:
exit ("Thank you for Banking with Bank of Python, goodbye!")
end()
This is for a class, but I am not worried about that, I just want to get a better understanding of how to make this work.
Thanks in advance.
You mentioned that this was about learning, and I really respect that, so I'm going to offer a totally unsolicited review of the code you wrote as a whole, trying to point out stylistic and substantive improvements where I saw some. I'm sure you could get more competent help, but I wanted feedback like this from someone who was a little further along than me. The short answer has already been pointed out, that you're not assigning answer before referencing it within that function, but there are other things worth noting as well.
In the interest of keeping the short answer relevant, I also point to this good answer on how scoping works for Python. If you just want to know why answer wasn't working right, that should clear things up. If you want a really tedious breakdown of the code, read on :)
account
Let's look at account first. I'll only say this once, but you can (although are by no means obligated to) print multi-line strings. You can do this a number of ways:
print("This line\nwill print on\nthree lines!")
prints...
This line
will print on
three lines!
The key here being the newline character \n. Notice that I said it was a character, not characters. That will come up someday.
An alternative way to print multi-line strings is by making the string multi-line using triple quotation marks:
print('''This line
will print on
three lines!''')
prints... well, the same thing as above. People are not as keen on this approach since triple quotes are often used for block comments and docstrings, but there's no law against it.
While we're in account I want you to consider the logic of this pair of statements:
account = raw_input("Account pin number is 1234: ")
account = (1234)
What this is doing is prompting the user to enter a pin number, and then setting it to (1234) regardless. This might be intentional - like for testing purposes - but it seems weird to me. I'm also not sure if you're trying to create a tuple (which would just require a trailing comma), but if not, and you're just making a simple integer, you can say
account = 1234
which will disambiguate the intent a little bit.
I'll also bring up that raw_input is a python 2.x function, and in python 3k you just use input. you should be cautious, however, to convert the value the user gives into the appropriate type: input returns a string type regardless of what the user enters. You can quickly convert it into an integer by calling int(input("some prompt")), but you might want to catch errors, like if someone responds to that prompt with "I'm lost and not good with computers."
balance
When you ask if the user wants to see their balance, you set it to 0!
balance = int(0)
Not necessary, and in fact somewhat frustrating for anyone doing business at the Bank of Python.
This is also potentially a little too advanced for you, but consider using string formatting to print the balance. It's a nice way of taking care of the little odds and ends in a simple function. In this case, you'd use something like
print("Current balance: ${b:.2f}".format(b=balance))
transaction
So I accidentally skipped ahead and saw that you planned on using answer in a later function. You're thinking ahead, which is good, but you're thinking ahead of the computer, which is bad. Within the scope of deposit, answer doesn't exist yet, so it has no idea what you're talking about when you ask whether it =="D". It should throw an error, which you can solve a number of ways:
You could put everything into the transaction function (please don't do this)
You could pass answer to both deposit and withdraw, separately, and let them figure out what they each want to do with it (again, nope)
You could, keeping things at about this level of complexity, run your if statements from deposit and withdraw in the transaction function instead, and call whichever of the two matches up (this sounds good, let's do this).
To take option 3, you would actually pull the if statements from each function and then tell each one to run their corresponding functions... and that's it. Like
if answer[0].lower()=="d":
deposit()
elif answer[0].lower()=="w":
withdraw()
else:
print("I'm confused, this is not fun anymore.")
deposit
Your deposit function isn't retaining the new balance when people deposit money. You mentioned this is a simple ATM program so I'm trying to limit the scope of functionality I would expect in grading something like this, and ultimately you probably know better than anyone on StackOverflow what your assignment demands, but do think about how you would keep the new balance :)
withdraw
Same as all of the stuff from before
end
I'm pretty sure exit doesn't take arguments (in other words, you can't leave a parting message on your way out). Just print your goodbye and then exit quietly so to speak.
I haven't brought up things like function parameters or classes (let alone class attributes or methods), any of which could really broaden the scope and complexity of your assignment, but at the same time would make it much more interesting and rewarding to code. You seem to be thinking procedurally, which (in my opinion) is good for getting your arms around how a computer works through things. Keep at it; someday you'll look back at this code and think about how you could have optimized and abstracted certain things so much :P
You have declared answer only inside functions. Add
answer = 0
above the account() function and wherever you use answer, add
global answer
in that function. This is becasus, the scope of answer is limited to particular function and not outside the function. If you use a global variable, it can be used in any function.
Simple as this, you can either make answer a global variable. Not recommended, but an option or you can pass it to the function deposit by typing and to call it use deposit(answer)
def deposit(answer):
If you decide to use calling functions instead of just having every function called no matter what it makes your program more computer friendly.
Also one last thing is you might run into some problems because you have balance as the name of a function along with an int variable.