How to add a progress bar in python? - python

I've been asked to make a 'Privilege Checker' and so far it is coming along pretty well. Here is my code:
def Privilige():
print("Welcome to Privilege checker V0.011")
print("Would you like to check your privileges?")
answer = input("Type 'Yes' or 'No' and hit enter ('Y', 'y', 'N', or 'n' are also valid choices).")
print("Checking priviliges.")
if answer == "yes" or answer == "Yes" or answer == "Y" or answer == 'y':
print("Privileges: Checked")
elif answer == "no" or answer == "No" or answer == 'N' or answer == 'n':
print("Privileges: Unchecked.")
else:
print("Please enter a valid option.")
Privilige()
Now, in between print("Checking privileges.") and if answer == "yes" I would like to add a progress bar that uses this character, "█" is this possible?
Any help appreciated, thanks!

You could try something like this:
from time import sleep
for i in range(60): # Change this number to make it longer or shorter.
print('█', end='')
sleep(0.1) # Change this number to make it faster or slower.

Related

Can't get string user input working (Python)

I've searched the web and this site and been messing around all day, trying 100 ways to get this simple little program working. I'm practicing endless While loops and string user inputs. Can anyone explain what I'm doing wrong? Thank you!
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.islower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
your code has one thing wrong answer.islower() will return boolean values True or False but you want to convert it into lower values so correct method will be answer.lower()
while True:
print("This is the start.")
answer = input("Would you like to continue? (Y/N) ")
answer = answer.lower() # change from islower() to lower()
if answer == "n":
print("Ok thank you and goodbye.")
break
elif answer == "y":
print("Ok, let's start again.")
else:
print("You need to input a 'y' or an 'n'.")
You just need one amendment to this line:
Instead of
answer = answer.islower()
Change to
answer = answer.lower()

How can I create a function with Yes or No?

How can I go about creating a input and output with Y\N (yes or no) function in a question?
My example; if my question is Would you like some food? (Y \ N):, how can I do this and have the answers show Yes, please. or No, thank you. for either choice and then proceed to the next question with the same function?
I thought about using this: valid=("Y": True, "y": True, "N": False, "n": False) but that only shows up as True or False for me, or is there a way to change from True \ False to Yes \ No? or this one:
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
But I'm really not sure how else to proceed with this one, or if there's any other easier solution to this.
I think what you're looking for is a conditional print statement rather than a true/false return statement on the function.
For example:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
print ("Yes, please" if user_input == 'Y' else "No, thank you")
Or, more readable:
def user_prompt():
while True:
user_input = input("Would you like some food? (Y \ N)")
if (user_input == 'Y'):
print("Yes, please")
elif (user_input == 'N'):
print("No, thank you")
I hope I understood your question correctly, you basically check the first letter (incase user enters yes/no) every time the user enters a value and try to verify that if it's Y/N you break the loop if not you keep asking the same question.
def user_prompt(yes_no):
while True:
user_input=input(yes_no)
if user_input[0].lower() == 'y':
print("Yes, please.")
break
elif user_input[0].lower() == 'n':
please("No, thank you.")
break
else:
print("Invalid, try again...")
Not sure if this is the best way, but I have a class based implementation of same
""" Class Questions """
class Questions:
_input = True
# Can add Multiple Questions
_questions = [
'Question 1', 'Question 2'
]
def ask_question(self):
counter = 0
no_of_question = len(self._questions)
while self._input:
if counter >= no_of_question:
return "You have answred all questions"
user_input = input(self._questions[counter])
self._input = True if user_input.lower() == 'y' else False
counter += 1
return "You have opted to leave"
if __name__ == '__main__':
ques = Questions()
print(ques.ask_question())
Firstly there is many ways you can go around this, but I am guessing you found the solution yourself already but here is one that is the best.
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
continue = get_yes_no_input('Would you like to proceed? [Y/N]: ')
And there we go.

Why my random number game doesn't work right?

guys! I'm new here. Nice to meet you!
I have the following problem. My random number generator always do exactly the same number. I have a guess why it's happening, but I'm not sure. Can you, please, explain what I'm doing wrong and just write some words about my code at all? Thanks!
import random
def begin():
r_num = random.randint(1, 10)
p_num = int(input('Enter your number: '))
ch = (r_num, p_num)
if ch[0] == ch[1]:
print(ch[0])
print("You've won! Excellent!")
play_again = input("Do you want to play again? y/n")
if play_again == 'y' or play_again == 'Y':
begin()
elif play_again == 'n' or play_again == 'N':
print('Goodbye!')
elif ch[1] < ch[0]:
print(ch[0])
print("Your number is lower than it must be!")
begin()
elif ch[1] > ch[0]:
print(ch[0])
print("Your number is higher than it must be!")
begin()
def start():
gen = input('Print generate to begin playing! \n')
if gen == 'generate':
print('Success!')
begin()
else:
print('Fail!')
start()
print('Welcome to my first Python game! Guess random generated number from 1 to 10!')
start()
The code works perfectly fine and so you genuinely must just have had incredibly good/bad luck (depending on which way you think about it). Try running the code in a different IDE - it's the only thing I can think of that may be causing the issue. Try running the script again?

Python: Skip user input and call later on

I'm fairly new to Python and am currently just learning by making some scripts to use at work. Real simple, just takes user input and stores it in a string to be called later on. The questions are yes/no answers but I wish for the user to have the option to skip and for the question to be asked again at the end, how would I do this?
Currently this is what I've got:
import sys
yes = ('yes', 'y')
no = ('no', 'n')
skip = ('skip', 's')
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
elif power.lower() in skip:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
then at the end of the script after all the questions have been asked I have this:
if power.lower() in skip:
power = str(raw_input("Does the site have power? (Yes/No): "))
if power.lower() in yes:
pass
elif power.lower() in no:
pass
else:
print ''
print '%s is an invlaid input! Please answer with Yes or No' % power
print ''
exit()
else:
pass
if power.lower == 'yes':
print 'Site has power'
else:
print 'Site doesnt have power, NFF.'
I understand this is very messy and I'm just looking for guidance/help.
Regards,
Trap.
Since you're rather new to Python I'll give you some tips:
Store all the questions which receive "skip" as a response into a list.
At the end of all your questions, iterate through (hint: "for" loop) all the questions which the user skipped and asked them again.
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
message=("is this correct")
Print=(message)
#store input
answer = input("yes/no:")
if answer == "yes": print("thank you")
if answer == "no": print("hmm, are you sure?")
#store input
answer = input("yes/no:")
if answer == "yes" : print("please call my suppot hotline: +47 476 58 266")
if answer == "no" : print("ok goodbye:)")
if someone had a solution for line 7 when answerd yes skiped to the end desplaing ok `goodbye:) thank you`

New Programmer, How do you use If and Elif and Else statements? Its giving me NameError: name 'No' is not defined

answer = input('Hi! Would you like to say something? (No or Yes)')
if answer == No or no:
print('Okay then, have a good day!')
elif answer == Yes or yes:
answertwo = input('What would you like to say?')
print(answertwo, 'Hmmmmmm, Intresting.')
**if answer == No or no:
NameError: name 'No' is not defined**
I would suggest you using .lower() for every input. This ensures that if some types "nO" or "YeS" it takes the lowercase equivalent. Example:
ui = input("Type \"Hi\"").lower()
Next, you should really add an else option to your code. This is for answers you don't want them to type. This should be held in a while loop Example:
while(True):
ui = input("Type \"Hi\"").title()
if(ui == "Hi"):
print("Hello")
break
else:
print("That isn't a choice!")

Categories