I am currently testing my knowledge of python programming as a student and can't get Len() to work on a simple program that asks a user for a user name that is maximum 12 letters long
Name = input("What Is Your Player Name\t")
# Check That The User Has Got A Maximun Of 12 Characters
if Name.len(0-13):
else:
print("Your Name Can Only Contain 12 Characters")
In extension of the other answers using len() you might want to look into using a while-loop to ask the user to enter the name again if it is more than 12 characters like so:
while(True):
name = input("What is your Player Name: ")
if len(name) > 12:
print("Your Player Name can only contain a maximum of 12 characters")
else:
break;
print("\nYou entered the Player Name: %s" % name)
Try it here!
In Python you pass the String into the len function to return the length of the String.
len(Name)
Related
So I am writing a python program for creating a cricket scoreboard. Now I am having problems while comparing strings. This may be a dumb question I know, but here is my code
print("\nWelcome to our Cricket Score Board program")
team1 = input("Enter team 1 name: ")
team2 = input("Enter team 2 name: ")
print("Do the toss")
whoWonTheToss = input("Who won the toss: ")
print(whoWonTheToss)
if (whoWonTheToss != team1) or (whoWonTheToss != team2):
print("Enter a valid choice")
I did print(whoWonTheToss) just to check if my program is working. I am not the best at explaining but here is the output that I am getting
Welcome to our Cricket Score Board program
Enter team 1 name: RCB
Enter team 2 name: CSK
Do the toss
Who won the toss: RCB
RCB
Enter a valid choice
Now I am thinking why the program is giving me Enter a valid choice in the end after winning the toss. This should end the program, but instead it is just prinint Enter a valid choice. How can I fix this problem?
Use and instead of or to check this -
if (whoWonTheToss != team1) and (whoWonTheToss != team2):
print("Enter a valid choice")
You don't get correct output, because or checks only one of the conditions, you need to check if both of them are equal
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Is there is a way to make sure that the user enters the input data as I want them to,
For example,
I wrote this code so the user can enter some birthdays and the script will choose one in random:
import random, re
print("keep in mind that you need to enter the date in this format dd/mm/yyyy")
cont_1 = input("please enter the informations of the 1st contestant : \n")
cont_2 = input("please enter the informations of the 2nd contestant : \n")
cont_3 = input("please enter the informations of the 3rd contestant : \n")
cont_4 = input("please enter the informations of the 4th contestant : \n")
cont_5 = input("please enter the informations of the 5th contestant : \n")
print("Thank you,")
win = cont_1 + " " + cont_2 + " " + cont_3 + " " + cont_4 + " " + cont_5
contDates = re.compile(r'\d\d/\d\d/\d\d\d\d')
ir = contDates.findall(win)
print(" And the Winner is: ", random.choice(ir))
I want to know if there is a way to force the user to write in the input in this format ../../... when he enters the first two digits a slash shows and the next two
There is not easy way to do this. The easiest solution is to just check that what the user input is correct before asking for the next input:
date_re = re.compile(r'\d\d/\d\d/\d\d\d\d')
def ask_date(prompt):
while True: # Ask forever till the user inputs something correct.
text = input(prompt)
if date_re.fullmatch(text): # Does the input match the regex completly (e.g. no trailing input)?
return text # Just return the text. This will break out of the loop
else:
print("Invalid date format. please use dd/mm/yyyy")
cont_1 = ask_date("please enter the informations of the 1st contestant : \n")
cont_2 = ask_date("please enter the informations of the 2nd contestant : \n")
cont_3 = ask_date("please enter the informations of the 3rd contestant : \n")
cont_4 = ask_date("please enter the informations of the 4th contestant : \n")
cont_5 = ask_date("please enter the informations of the 5th contestant : \n")
This also simplifies the selection process, since all dates are valid:
print(" And the Winner is: ", random.choice((cont_1, cont_2, cont_3, cont_4, cont_5))
You can check if it is correct date format like this without using regex.
import datetime
user_input = input()
try:
datetime.datetime.strptime(user_input,"%d/%m/%Y")
except ValueError as err:
print('Wrong date format')
If you want it custom:
i = input("date (dd/mm/yyyy):")
split = i.split("/")
for item in split:
try:
int(item)
except:
print("error")
exit()
if len(split) != 3 or len(split[0]) not in [1, 2] or len(split[1]) not in [1, 2] or len(split[2]) != 4:
print("error!")
else:
print("accepted!")
This makes sure that all of the items are numbers, and that there are 3 slashes, the first and second ones are two digits, and the last one is 4 digits. If you want to accept any correct date:
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I'm attempting to accept user input and check the string for non-alphabet values. My problem is if they enter a bad value, how do I query them again and start the loop over? See below
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
name = str(input("Enter name:")
**line to start iterating from the beginning with new entry.**
Just trying to verify users only enter letters. If the check fails they enter the name again and it starts over. Thanks in advance!
You can do something like this:
correct = False
while correct == False:
name = str(input("Enter name:"))
for i in name:
if not i.isalpha():
correct = False
break
else:
correct = True
You can see below an example code:
while True:
number_found = False
name = str(input("Enter name:"))
for i in name:
print("Check {} character".format(i))
if i.isdigit():
print("{} is number. Try again.".format(i))
number_found = True
break # Break the for loop when you find the first non-alpha. You can reduce the run-time with this solution.
if not number_found:
break
print("Correct input {}".format(name))
Output:
>>> python3 test.py # Success case
Enter name:test
Check t character
Check e character
Check s character
Check t character
Correct input test
>>> python3 test.py # Failed case
Enter name:test555
Check t character
Check e character
Check s character
Check t character
Check 5 character
5 is number. Try again.
Enter name:
I'm brand new to both Python and StackOverflow, and I have a problem that has been stumping me for the past couple of hours.
I am making a peer-evaluation script for my high-school class. When you run the script, you input your classmate's name, then you rate them 1-10 on effort, accountability, and participation. These 3 values are then averaged. This average is assigned to the variable "grade". Since each classmate is going to get multiple grades, I need to have the "grade" variable export to another Python document where I can average every grade for each respective classmate.
So far, I have the script create a .txt file with the same name as the evaluated classmate, and the grade integer is stored there. Does anyone know of a way that I can export that integer to a Python file where I can append each successive grade so they can then be averaged?
Thanks
Python peer evaluation script
def script():
classmate = input('Please enter your classmate\'s name: ')
classmateString = str(classmate)
effortString = input('Please enter an integer from 1-10 signifying your classmate\'s overall effort during LLS: ')
effort = int(effortString)
accountabilityString = input('Please enter an integer from 1-10 signifying how accountable your classmate was during LLS: ')
accountability = int(accountabilityString)
participationString = input('Please enter an integer from 1-10 signifying your classmate\'s overall participation: ')
participation = int(participationString)
add = effort + accountability + participation
grade = add / 3
gradeString = str(grade)
print ('Your grade for ', classmate, 'is: ', grade)
print ('Thank you for your participation. Your input will help represent your classmate\'s grade for the LLS event.')
filename = (classmateString)+'.txt'
file = open(filename, 'a+')
file.write(gradeString)
file.close()
print ('Move on to next classmate?')
yes = set(['yes','y','Yes','Y'])
no = set(['no','n','No','n'])
choice = input().lower()
if choice in yes:
script()
elif choice in no:
sys.exit(0)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
script()
script()
put
import name_of_script_file
at the top of your Python file, assuming they are in the same folder.
Then you can access the variable like:
name_of_script_file.variable_name
I am very new to Python programming (15 minutes) I wanted to make a simple program that would take an input and then print it back out. This is how my code looks.
Number = raw_input("Enter a number")
print Number
How can I make it so a new line follows. I read about using \n but when I tried:
Number = raw_input("Enter a number")\n
print Number
It didn't work.
Put it inside of the quotes:
Number = raw_input("Enter a number\n")
\n is a control character, sort of like a key on the keyboard that you cannot press.
You could also use triple quotes and make a multi-line string:
Number = raw_input("""Enter a number
""")
If you want the input to be on its own line then you could also just
print "Enter a number"
Number = raw_input()
I do this:
print("What is your name?")
name = input("")
print("Hello" , name + "!")
So when I run it and type Bob the whole thing would look like:
What is your name?
Bob
Hello Bob!
# use the print function to ask the question:
print("What is your name?")
# assign the variable name to the input function. It will show in a new line.
your_name = input("")
# repeat for any other variables as needed
It will also work with: your_name = input("What is your name?\n")
in python 3:
#!/usr/bin/python3.7
'''
Read list of numbers and print it
'''
def enter_num():
i = input("Enter the numbers \n")
for a in range(len(i)):
print i[a]
if __name__ == "__main__":
enter_num()
In the python3 this is the following way to take input from user:
For the string:
s=input()
For the integer:
x=int(input())
Taking more than one integer value in the same line (like array):
a=list(map(int,input().split()))