How do I check if the user has entered a number? [duplicate]

2024/10/11 8:28:10

I making a quiz program using Python 3. I'm trying to implement checks so that if the user enters a string, the console won't spit out errors. The code I've put in doesn't work, and I'm not sure how to go about fixing it.

import random
import operator
operation=[(operator.add, "+"),(operator.mul, "*"),(operator.sub, "-")]
num_of_q=10
score=0
name=input("What is your name? ")
class_num =input("Which class are you in? ")
print(name,", welcome to this maths test!")for _ in range(num_of_q):num1=random.randint(0,10)num2=random.randint(1,10)op,symbol=random.choice(operation)print("What is",num1,symbol,num2,"?")if int(input()) == op(num1, num2):print("Correct")score += 1try:val = int(input())except ValueError:print("That's not a number!")else:print("Incorrect")if num_of_q==10:print(name,"you got",score,"/",num_of_q)
Answer

You need to catch the exception already in the first if clause. For example:

for _ in range(num_of_q):num1=random.randint(0,10)num2=random.randint(1,10)op,symbol=random.choice(operation)print("What is",num1,symbol,num2,"?")try:outcome = int(input())except ValueError:print("That's not a number!")else:if outcome == op(num1, num2):print("Correct")score += 1else:print("Incorrect")

I've also removed the val = int(input()) clause - it seems to serve no purpose.

EDIT

If you want to give the user more than one chance to answer the question, you can embed the entire thing in a while loop:

for _ in range(num_of_q):num1=random.randint(0,10)num2=random.randint(1,10)op,symbol=random.choice(operation)while True:print("What is",num1,symbol,num2,"?")try:outcome = int(input())except ValueError:print("That's not a number!")else:if outcome == op(num1, num2):print("Correct")score += 1breakelse:print("Incorrect, please try again")

This will loop eternally until the right answer is given, but you could easily adapt this to keep a count as well to give the user a fixed number of trials.

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

Related Q&A

high F1 score and low values in confusion matrix

consider I have 2 classes of data and I am using sklearn for classification, def cv_classif_wrapper(classifier, X, y, n_splits=5, random_state=42, verbose=0):cross validation wrappercv = StratifiedKFol…

Replace `\n` in html page with space in python LXML

I have an unclear xml and process it with python lxml module. I want replace all \n in content with space before any processing, how can I do this work for text of all elements.edit my xml example:<…

Basic python. Quick question regarding calling a function [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)Closed 1 year ago.Ive got a basic problem in pyth…

Obtain the duration of a mp4 file [duplicate]

This question already has answers here:How to get the duration of a video in Python?(15 answers)Closed 10 years ago.I need to know the duration of a mp4 file with python 3.3. I search and try to do th…

Matplotlib.pyplot - Deactivate axes in figure. /Axis of figure overlap with axes of subplot

%load_ext autoreload %autoreload 2 %matplotlib inlineimport numpy as np import datetime as dt import pickle import pandas as pd import datetime from datetime import timedelta, date from datetime impor…

How to generate the captcha to train with Python

I would like to use deep learning program for recognizing the captcha using keras with python.But the big challenge is to generate massive captcha to train. I want to solve a captcha like thisHow can …

Convert PNG to a binary (base 2) string in Python

I Basically want to read a png file and convert it into binary(base 2) and store the converted base 2 value in a string. Ive tried so many things, but all of them are showing some error

Turbodbc installation on Windows 10

I tried installing turbodbc and it gives me the following error and not sure whats wrong here.My python version is 3.7My command line output from Windows 10 Pro. C:\Users\marunachalam\Downloads>pip …

how to convert a text into tuples in a list in python

I am a beginner in python and desperately need someones help.I am trying to convert a text into tuples in a list. The original text was already tokenized and each pos was tagged as below:The/DT Fulton/…

Trying to call a function within class but its not working [duplicate]

This question already has answers here:TypeError: attack() missing 1 required positional argument: self(2 answers)Closed 3 years ago.I am trying to call a function but its not working. here is the code…