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
Related
It's my 4th day learning programming so I'm very new to it. and I'm trying to get the user's info(hobbies) in one question and save them into a list then give back the user one of the hobbies they chose.
this what I've came up with
import random
fav_hobbies = []
hobbies = input("what are your favourite hobbies?(cooking, writing,ect) ").lower()
fav_hobbies.append(hobbies)
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
The problem is that instead of choosing a word among the words that user has chosen it just prints all of the things they said.
How do I fix this?
You are just accepting a string from the User and storing it as it is without splitting.
Assuming that you are accepting a space separated input, You can do this in:
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
import random
fav_hobbies = list(input("what are your favourite hobbies?(cooking, writing,ect) ").lower().split())
situation = input("so are you bored now?(answer with yes or no): ").lower()
if situation == "yes":
print("you should try " + random.choice(fav_hobbies))
elif boredom_situation == "no":
print("awesome! have a nice day!")
If you use some other separator like , you can just add it to split(',')
I have to write a program that takes user input for a website and keyword, and then reads the source code of the website for that word. I have to code it so it detects many variations of the word (ex. hello vs. hello, vs. hello!) and am not sure how to do this. I have it coded like this so far to detect the exact input, but I'm not sure how to get multiple variations. Any help would be greatly appreciated, thank you!
def main():
[n,l]=user()
print("Okay", n, "from", l, ", let's get started.")
webname=input("What is the name of the website you wish to browse? ")
website=requests.get(input("Please enter the URL: "))
txt = website.text
list=txt.split(",")
print(type(txt))
print(type(list))
print(list[0:10])
while True:
numkey=input("Would you like to enter a keyword? Please enter yes or no: ")
if numkey=="yes":
key=input("Please enter the keyword to find: ")
else:
newurl()
break
find(webname,txt,key)
def find(web,txt,key):
findtext=txt
list=findtext.split(sep=" ")
count = 0
for item in list:
if item==key:
count=count+1
print("The word", key, "appears", count, "times on", web)
def newurl():
while True:
new=input("Would you like to browse another website? Please enter yes or no: ")
if new=="yes":
main()
else:
[w,r]=experience()
return new
break
def user():
name=input("Hello, what is your name? ")
loc=input("Where are you from? ")
return [name,loc]
def experience():
wordeval=input("Please enter 3 words to describe the experience, separated by spaces (ex. fun cool interesting): ")
list=wordeval.split(sep=" ")
rate=eval(input("Please rate your experience from 1-10: "))
if rate < 6:
print("We're sorry you had a negative", list[0], "and", list[2], "experience!")
else:
print("Okay, thanks for participating. We're glad your experience was", list[1], "!")
return[wordeval,rate]
main()
What you're looking for is the re module. You can get indices of the matches, individual match instances, etc. There are some good tutorials here that you can look at for how to use the module, but looping through the html source code line by line and looking for matches is easy enough, or you can find the indices within the string itself (if you've split it by newline, or just left it as one long text string).
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)
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'm in a beginning programming class and our program is to create a program to gather information on four different zip codes and five different types of coffee drinks to see if our friend should open up a coffee shop in that area.
My program will not accept my variables
My other problem with my program is it won't loop back around to get more input. I tried to reset the user answer to allow it to go back to the beginning but it doesn't read it.
I set up an accumulater for my if statement
Example
while UserAnswer == "yes":
ZipCode = input("Enter Zip Code: ")
print("Here are your menu choices: \n m = Cafe Mocha\n l = Cafe Latte ")
print(" r = Cafe Regular \n d = Cafe Regular Decafe \n c = Cafe Carmel")
CoffeeType = input("Enter your order: ")
Quantity = input("Enter quantity: ")
#Start inner loop with if statements to determine the quantity of the coffee
while UserAnswer == "no"
if ZipCode == 48026:
if CoffeeType == "m":
CM48026 = Quanity + CM48026'
My accumulater CM48026 doesn't save and at the end it prints out 0.
You need to provide an initial value for the accumulator. And that should be done outside the inner loop. Because you are using the same variable in the expression which provides the value for the accumulator.
So, doing a = b + a will not really work, as the value of a at the right is not really defined.
Moreover, there's a typo for the variable quantity, and that might actually be the reason why your code is not working!