Python Programming Loop

2024/11/20 8:45:14

I'm doing an assignment where I have to conduct a quiz for different topics. This is my code so far.

print("Hello and welcome to Shahaad's quiz!") #Introduction
name = input("What is your name? ")
print("Alright", name,", these will be today's topics:")
print("a) Video Games")
print("b) Soccer")
print("c) Geography") 
choice = input("Which topic would you like to begin with?")
if choice == 'video games' or choice == 'Video Games' or choice == 'Video games' or choice == 'a)':print("You picked Video Games.")
print("Question number one:")
print("What is the most popular FPS (First Person Shooter) game?")
print("a) Call of Duty")
print("b) Battlefield")
print("c) Grand Theft Auto 5")
print("d) Counter Strike")
answer = input("Your answer:")
guessesTaken = 0
if answer == 'Call Of Duty' or answer == 'Call of duty' or answer == 'Call of duty' or answer == 'a)' or answer == 'call of duty':print("You are correct!")
else: guessesTaken = guessesTaken + 1print("Incorrect!")print("You have", guessesTaken, "guess left!")

I am trying to make it so that if they get the answer wrong, they get another chance at answering the question. Right now once they get it wrong, they can't type again. Thanks!

Answer

You should do as @BartoszKP says, use a while loop to check that the user has entered a valid input.

That being said, I have a few recommendations that might improve the readability of your code. Instead of this

if choice == 'video games' or choice == 'Video Games' or choice == 'Video games' or choice == 'a)':print("You picked Video Games.")

You could take advantage of the str().lower() method:

if choice.lower() == 'video games' or choice == 'a':print('You picked Video Games.")

The lower() method converts all letters to lower-case.

Regarding the while loop, I don't like to use a flag variables - it adds an extra variable to the code that isn't really needed. Instead, you could make use of break

while True:choice = input('Which topic would you like to begin with?')if choice.lower() == 'video games' or 'a':print('You picked Video Games.')break #This breaks out of the while loop, and continues executing the code that follows the loop

Another solution is to define the choice variable before the while loop, and run it until the input is like you want:

choice = input('Which topic would you like to begin with?')
while choice.lower() != 'video games' and choice != 'a':print('Please pick a valid option')choice = input('Which topic would you like to begin with?')
print('You picked "{}".'.format(choice))

If you want to be able to choose between different options, the code could be further improved by checking if the input string is one of the items in a list:

valid_options = ['video games', 'a', 'software', 'b', 'cartoons', 'c']
choice = input('Which topic would you like to begin with?')
while choice.lower() not in valid_options:print('Please pick a valid option')choice = input('Which topic would you like to begin with?')
print('You picked "{}".'.format(choice))

Output:

Which topic would you like to begin with?Movies
Please pick a valid option
Which topic would you like to begin with?vIdeO gaMes
You picked "vIdeO gaMes".Which topic would you like to begin with?software
You picked "software".

If you use Python 2.x, you should also consider using raw_input() instead of input(). Please see this related SO question to understand why.

https://en.xdnf.cn/q/118437.html

Related Q&A

How to fix stale element error without refreshing the page

Trying to get details of Tyres on this page. https://eurawheels.com/fr/catalogue/INFINY-INDIVIDUAL . Each tyre has different FINITIONS. The price and other details are different for each FINITIONS. I w…

Fastest way in numpy to get distance of product of n pairs in array

I have N number of points, for example: A = [2, 3] B = [3, 4] C = [3, 3] . . .And theyre in an array like so: arr = np.array([[2, 3], [3, 4], [3, 3]])I need as output all pairwise distances in BFS (Bre…

How to get argument to ignore part of message

I just wondering how to get the if statement(if 0 < int(message.content)< 153:) to only test part of the message, not the full message.content. Eg: if I put in 1s 100, I want it to test if ONLY t…

how can I limit the access in Flask

I create a project to simulate login my companys website.And put it in my server to let others to use.But the company website has a limit with single ip can only open 2 sessions.So when more than 2 my …

Multiple images numpy array into blocks

I have a numpy array with 1000 RGB images with shape (1000, 90, 90, 3) and I need to work on each image, but sliced in 9 blocks. Ive found many solution for slicing a single image, but how can I obtai…

Python - Transpose columns to rows within data operation and before writing to file

I have developed a public and open source App for Splunk (Nmon performance monitor for Unix and Linux Systems, see https://apps.splunk.com/app/1753/)A master piece of the App is an old perl (recycled, …

Unexpected output while sorting the list of IP address [duplicate]

This question already has answers here:Python .sort() not working as expected(8 answers)Closed last year.I am trying to sort the list of ipaddress from the following list. IPlist= [209.85.238.4, 216.23…

Google Cloud Run returning Server Unavailable Occasionally

I am running a Flask app at https://recycler-mvdcj7favq-uc.a.run.app/ on Google Cloud Run and occasionally I get 503 server unavailable while refreshing a few times seems to load the page. Also, someti…

Connecting to Internet?

Im having issues with connecting to the Internet using python.I am on a corporate network that uses a PAC file to set proxies. Now this would be fine if I could find and parse the PAC to get what I nee…

Angular App Not Working When Moving to Python Flask

Not sure what information to give so will do as much as I can. Currently have an Angular app sitting on IIS and using Classic ASP. All works fine. There is a dropdown which fetches some JSON that then …