have a raw input in a variable? - python

For a project I need to have a program ask a contests name, use the name in another question.
The Code below works.
The Main problem is that I need the time entered as a value and saved so I can calculate it later, but print in a line that says time = """"" , doesn't work.
Any suggestions on how to approach this problem?
def main():
print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
archerList = [] #list
name = raw_input ("Enter contestants first name: ")
s = str(name)
archerList.append(name)
print "Enter time (in milliseconds) for " + s , raw_input (": ")
main()

i think you need to do
t = raw_input ("Enter time (in milliseconds) for %s :" % s)

For raw_input returns a string value,
So x = raw_input() will assign the string of what the user has input to x.
See this for docs of raw_input.
For your archerslist, you may want to use a dictionary instead as then you can access the "time" with the name of the archer.
See here for dictionary documentation
You can use dictionaries like this:
def main():
print "~*~*~*~*~*~ Timbuktu Archery Contest ~*~*~*~*~*~"
archers = {}
while True: # get inputs till user inputs empty string.
name = raw_input ("Enter contestants first name: ")
if name == '':
break
while True: # get input till ttime can be converted to an int.
ttime = raw_input ("Enter time (in milliseconds) for %s :" % name)
try:
ttime = int(ttime)
except ValueError: # error handling
print 'Invalid input, Enter a number'
else:
break
archers[name] = ttime # assign values to the dictionary
return archers # return dictionary value

Related

How to make a proper name input program in python [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True

Python pickles not storing data

I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.

How do I say, if variable = any integer, in Python 2x

import random
print ("hello")
user_friend1 = raw_input("Name one of your friends: ")
user_friend2 = raw_input("Name another friend: ")
# inputs for user
friends = [user_friend1,user_friend2]
best_friend = random.sample(friends, 1)
I want to loop it so that if a user types an integer to a question then it will ask the question again, i need it for both questions user_friend 1 and 2
print ("your best friend is %s") % (best_friend)
if type(variable) == int:
This gets the type of the variable and compares it to the class int
Use this
import random
while True:
friend1 = raw_input("Name one of your friends: ")
try:
val = int(friend1)
except ValueError:
break
print("Enter valid name")
while True:
friend2 = raw_input("Name another friend: ")
try:
val = int(friend2)
except ValueError:
break
print("Enter valid name")
friends = [friend1,friend2]
best_friend = random.sample(friends, 1)
print("your bestfriend is %s" %(best_friend))
Output
Name one of your friends: 1
Enter valid name
Name one of your friends: 1
Enter valid name
Name one of your friends: tilak
Name another friend: varma
your bestfriend is ['varma']
You should use isinstance()
if isinstance(variable, int):
do_something()

I need python understand True when 1, yea, y is typed

I would like to learn how could i run below Python code proper way. I guess comments will do the work below.
Now, this only works well just in case I type "True" or "False" with capital initial letters. But I also need to get the same result when typed 1 or true etc.
# Here we ask the user place an input and assign it to name parameter.
name = raw_input ("What is your name human?: ")
# Here we will display the value of name parameter placed by user
print "Got it! Your name is %r" % name
# Here we ask the user if he is owning the device.
# We will assign the answer to computers_owner parameter
computers_owner = input ("Are you the owner of this machine?: ")
# In this question's answer we have an if condition.
# If the answer is True machine will say "Good! I need you" % name
if computers_owner is True:
print "Good! I need you %s" % name
# If the answer is False machine will say "Call me your master!" % name
else:
print "Call me your master! %s" % name
You can use a list for true conditions like this:
name = raw_input ("What is your name human?: ")
print "Got it! Your name is %r" % name
computers_owner = raw_input("Are you the owner of this machine?: ")
if computers_owner in ['1','yea','y','yo','hell yeah','true','True', 'true dat']:
print "Good! I need you %s" % name
else:
print "Call me your master! %s" % name

While-Loop Use in Python

When you come to the 2nd while loop while x == 2: it's still repeating the whole script even though x /= 1 (not if "n"is entered). Let say we enter "y" on the prompt "Is this correct?" shouldn't x become 3 which stops both the first and the 2nd loop?
This is probably obvious but I'm pretty new.
# -*- coding: utf-8 -*-
import time
x = 1
while x == 1:
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
while x == 2:
if correct == "y":
x = 3 # x = 3 skips all whiles, not working
time.sleep(1)
elif correct == "n":
time.sleep(1)
x = 1 # x = 1 --> 1st while still in action
else:
print "Invalid input \n\t Loading..."
x = 2 # x = 2 --> 2nd while takes over
print "Where do you live?"
time.sleep(0.5)
country = raw_input("Country: ")
time.sleep(0.5)
city = raw_input("City: ")
time.sleep(1)
print " \n Data: \n\t Name: %r \n \t Age: %r \n \t Country: %r \n \t
City: %r " % (name, age, country, city )
In the code you never change the value of your x to 2 so your inner loop while x==2: never runs and you loop infinitely. You need to change the value of x just inside the while x==1: loop for you to even enter the second loop.
The while structure is totally unnecessary, use functions instead and chain them
def ask():
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
return decide(name,age) #<-- Goes to decide
def decide(name,age):
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
if correct == "y":
return name,age #<-- process finishes
elif correct == "n":
return ask() #<-- goes back to asking
else:
print "Invalid input"
return decide(name,age) #<--Goes back to wait for a valid input
name, age = ask() #<--Starts the whole process
While I like my other answer better, if you want this code to work with just a slight modification, just bring the definition of correct to the inner loop and as Abdul Fatir say, kick in an x = 2. Anyhow using creating a state machine this way is not recommended.
x = 1
while x == 1:
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
x = 2 #<--Necessary
while x == 2:
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
if correct == "y":
x = 3 # x = 3 skips all whiles, not working
time.sleep(1)
elif correct == "n":
time.sleep(1)
x = 1 # x = 1 --> 1st while still in action
else:
print "Invalid input \n\t Loading..."
x = 2 # x = 2 --> 2nd while takes over
I like the solution involving chaining functions, but I also think that you could use some help with your input validation. I really nice tool for this is not in to validate it ahead of time. For instance
def ask():
print "What's your name?"
name = raw_input("Name: ")
print "How old are you?"
age = raw_input("Age: ")
return decide(name,age) #<-- Goes to decide
def decide(name,age):
print "So you are %r years old and your name is %r. Is this correct?" % (age, name)
correct = raw_input("(y/n): ")
while correct not in ["y", "n"]:
correct = raw_input("(y/n): ")
if correct == "y":
return (name,age) #<--process finishes
else
return ask() #<-- goes back to asking
Just to be clear, I ripped a large portion of that code from another answer, but I think that doing it that way is more efficient, and puts all acceptable answers in once place for easy viewing. It would even allow for more complex input validation, and potentially let you use a constant or config file to define available options.

Categories

Resources