Problem with "while not loop" in Python code - python

I create a simple code in Phyton, it demands two numbers and until are given you´re in a loop (because the code checks if an int number is given). After that, you have to choose a certain operation. But my code can´t break the loop. I don´t know what´s wrong, if it is the indentation? If I shouldn't use a loop in this, the syntax?
dataRight = False
#Check if the data are int numbers
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
#After the data given is right, choose the operation to make.
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = dataParsec / lightYear
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = dataParsec * lightYear
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
Can someone help me? It's been days and I can´t see what´s wrong.

Code:
As far as I understood, your problem is non-terminating while loop. It's just because of indentation.
while not dataRight:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
try:
dataParsec = int(dataParsec)
except:
dataParsec = "Error1"
dataLight = input("LightYear Númber: ")
try:
dataLight = int(dataLight)
except:
dataLight = "Error2"
# This must be outside the except that's all
if dataParsec != "Error1" and dataLight != "Error2":
dataRight = True
Output:
Convert LightYears and Parsecs, enter the data:
Parsecs Number: l
LightYear Númber: 5
Convert LightYears and Parsecs, enter the data:
Parsecs Number: 2
LightYear Númber: 5
Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: A
Convert to Parsecs: 0.613203497712751

If you want it to stay in the loop until the user enters a number, try something along these lines
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")

This do the work:
print("Convert LightYears and Parsecs, enter the data:")
dataParsec = input("Parsecs Number: ")
while dataParsec.isdigit() == False:
dataParsec = input("Parsecs Number: ")
dataLightYear = input("LightYears Number: ")
while dataLightYear.isdigit() == False:
dataLightYear = input("LightYears Number: ")
question = input("Choose, A)-LightYear to Parsecs, B)-Parsecs to LightYear: ")
question = question.upper()
lightYear = 3.26156
if question == "A":
convertlightYear = int(dataParsec) / int(dataLightYear)
print("Convert to Parsecs: ", str(convertlightYear))
elif question == "B":
convertParsec = int(dataParsec) * int(dataLightYear)
print("Convert to LightYear: ", str(convertParsec))
else:
print("Data entered is wrong")
Thanks Blckknght, Bibhav and Victor_G. All of you were of great Help! :D

Related

Can't find a way to incorporate addition, division, subtraction and multiplication inside of my small game

I am trying to use the variables user_ans_a, user_ans_s, user_ans_m and user_ans_d inside of my game as questions randomly chosen by python. My dilemma is coming from matching the randomly chosen variable to an answer coresponding to that variable. I want the user to be able to enter an anser to those questions.
import random
import re
while True:
score = 0
top = "--- Mathematics Game ---"
print(len(top) * "━")
print(top)
print(len(top) * "━")
print(" Type 'Play' to play")
start_condition = "Play" or "play"
def checkint(input_value):
while True:
try:
x = int(input(input_value))
except ValueError:
print("That was a bad input")
else:
return x
while True:
inp = input()
if inp == "Play":
break
else:
print("Try again")
if inp == "Play":
print("What's your name?")
name = input()
print(f"Hello {name}")
while True:
try:
no_of_rounds = int(input("how many rounds do you want to play? "))
break
except ValueError:
print('Please enter a number.')
for i in range(no_of_rounds):
ran_int1 = (random.randint(1,10))
ran_int2 = (random.randint(1,10))
answer_a = (ran_int1 + ran_int2)
answer_s = (ran_int1 - ran_int2)
answer_m = (ran_int1 * ran_int2)
answer_d = (ran_int1 / ran_int2)
user_ans_a = (f"What does {ran_int1} + {ran_int2} = ")
user_ans_s = (f"What does {ran_int1} - {ran_int2} = ")
user_ans_m = (f"What does {ran_int1} * {ran_int2} = ")
user_ans_d = (f"What does {ran_int1} / {ran_int2} = ")
if checkint(user_ans_a) == int(answer_a):
print(f"That was correct {name}.")
score = score+1
else:
print(f"Wrong {name}, the answer was {answer_a}, try again")
print(f"Score was {score}")
while True:
answer = str(input('Run again? (y/n): '))
if answer in ('y', 'n'):
break
print("invalid input.")
if answer == 'y':
continue
else:
print("Goodbye")
break

removes the writing "none" in the python calculator

I just created a simple calculator program using python language, but there is a little problem here, when I end the program by inputting number 1, there is always the text none.
The question is how do I get rid of the text none in the program that I created? Because to be honest it is very annoying and will damage the image of the program that I created.
def pilihan():
i = 0
while i == 0:
print('\n\tWelcome to the Simple Calculator Program')
print("\nPlease Select Existing Operations", "\n1. subtraction", "\n2. increase", "\n3. division", "\n4. multiplication")
pilihan2 = int(input('Enter your choice (1/2/3/4): '))
if pilihan2 == 1:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "-", angka2, "=", angka1 - angka2)
elif pilihan2 == 2:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "+", angka2, "=", angka1 + angka2)
elif pilihan2 == 3:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, ":", angka2, "=", angka1 / angka2)
elif pilihan2 == 4:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "x", angka2, "=", angka1 * angka2)
else:
print('Error option, please try again')
continue
print('Program finished, want to restart?')
y = 0
while y == 0:
ulang = int(input('Type 0 for YES and 1 for NO = '))
if ulang == 0:
y += 1
break
elif ulang == 1:
y += 2
break
else:
print('\nThe command you entered is an error, please try again')
continue
if y == 1:
continue
else:
break
print(pilihan())
Change the print(pilihan()) to pilihan(), the return value of pilihan() is None :)

How do I make python react to strings? [duplicate]

This question already has answers here:
In Python, how do I check that the user has entered a name instead of a number?
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
Let's get straight to the problem: when i run the code, and type letters instead of numbers to the first input my python gets an error. How do i make my python know that if someone types in letters instead of numbers should get warned and repeat the code? Im trying to fix it from about two hours.
Thank you for help
Also sorry for my really bad english
import time
import random
def repeatt():
od = int(input("Wpisz do ktorej liczby liczba ma byc losowana: "))
doo = int(input("Do ktorej: "))
if od >= doo:
print("Jeszcze raz :")
repeatt()
elif od <= doo:
wylosowana = random.randint(od, doo)
print("Wylosowana liczba: ", wylosowana)
print("Witaj! Od czego chcialbys zaczac?:")
print(
"""
1. forin slowo
2. oblicz ile ja zyje
3. oblicz, ile mam zaplacic
4. tekst
5. losowanie liczby
"""
)
choice = int(input("Wpisz liczbe: "))
if choice == 1:
slowo = input("Wprowadz slowo: ")
for letter in slowo:
print(letter)
elif choice == 2:
obliczanie = int(input("Wprowadz, ile masz lat: "))
oblicz = obliczanie * 60 * 60
print("Zyjesz juz ponad ", obliczanie * 60 * 60, "sekund")
elif choice == 3:
pieniadze = int(input("Ile podczas miesiacu zarabiasz?: "))
print("Na jedzenie: ", pieniadze / 5)
elif choice == 4:
wiadomosc = input("Wpisz jakąs wiadomosc: ")
def repeat():
wybor = input("upper, lower, title?: ")
if wybor == "upper":
print(wiadomosc.upper())
elif wybor == "lower":
print(wiadomosc.lower())
elif wybor == "title":
print(wiadomosc.title())
else:
print("Wpisz upper, lower lub title")
wybor = input("upper, lower, title?: ")
if wybor == "upper":
print(wiadomosc.upper())
elif wybor == "lower":
print(wiadomosc.lower())
elif wybor == "title":
print(wiadomosc.title())
else:
print("Wpisz proprawnie")
repeat()
elif choice == 5:
od = int(input("Wpisz liczbe od ktorej ma byc losowana: "))
doo = int(input("Do ktorej: "))
if od >= doo:
print("Jeszcze raz :")
repeatt()
elif od <= doo:
wylosowana = random.randint(od, doo)
print("Wylosowana liczba: ", wylosowana)
else:
print("Tylko liczby")
else:
print("Wpisz liczbe od 1 do 3")
choice = int(input("Wpisz liczbe: "))
Replace the above line with below code
While True:
choice = input("Wpisz liczbe: ")
if choice.isdigit():
choice = int(choice)
# your code of if conditions
else:
print("please enter valid input")
continue
while True:
try:
choice = int(input("Wpisz liczbe: "))
break
except ValueError:
print("No letters allowed, please try again")
def repeatt():
def redo(): #Repeating function
try:
od = int(input("Wpisz do ktorej liczby liczba ma byc losowana: "))
except: #If the user enters a string instead of int it will go back to redo() which will repeat until user enters a int.
print("Enter A Number!")
redo()
redo() #Leads to the input
repeatt()

How could I use the except function with a for loop

When there is a wrong answer, I would like a preset message for all the operators to be displayed.
Maybe something like this:
while True:
try:
user_ans = int(input())
except ValueError:
print ("That is not a valid answer")
continue
else:
break
but in a for loop.
My aim is to ask numerical questions then save to a file.
First, I need to ask the user what maths class they are in, then ask 10 randomly generated questions.
#Imports
import random
from time import sleep
#List & Definitions#
operators = ("-","+","X")
score = 0
QA = 0
#Intro#
print ("Hello and Welcome")
print ("What is your name?")
name = input ()
print ("Do you want to Play (Yes/No)?")
choice = input()
if choice =="Yes":
print ("Excellent")
if choice == "No":
print ("Okey, bye...")
end()
quit()
print ("Please input your class")
cn = input ()
print ("Let's start the quiz!")
sleep(2)
#Asking Questions
for QA in range (0, 10):
numb1 = random.randint(1,10)
numb2 = random.randint(1,10)
randOp = random.choice(operators)
#Addition
if randOp == "+" :
print (str(numb1) + "+" + str(numb2))
answer = numb1 + numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("well done that was correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
else:
print ("Oops! That was no valid number. Try again...")
#Subtracting
if randOp == "-" :
if numb2 > numb1 :
print (str(numb2) + "-" + str(numb1))
answer = numb2 - numb1
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("woah again Correct")
if UserAns != answer:
print("that's wrong")
score = score + 1
elif numb1 > numb2 :
print(str(numb1) + "-" + str(numb2))
answer = numb1 - numb2
print ("Please input your answer")
UserAns = int(input ())
if UserAns == answer :
print ("Correct :) ")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Multiplication
if randOp == "*" :
print (str(numb1) + "X" + str(numb2))
ans = numb1 * numb2
sleep(1)
print ("Please input your answer")
UserAns = int(input ())
if ans == UserAns :
print ("Correct")
score = score + 1
if UserAns != answer:
print("that's wrong")
#Displaying Score
QA = QA + 1
if QA == 10 :
print ("Your score is " + str(score) + " out of ten")
#Saving & Writing to File
savePath = "Results\Class " + str(cn) + "\\" + name.lower() +".txt"
file = open(savePath, "a")
file.close()
file = open(savePath, "r")
if file.read() == "":
file.close()
file = open(savePath, "a")
file.write(name + "\n\n")
file.close()
file.close()
file = open(savePath, "a")
file.write(str(score))
file.write("\n")
file.close()
Just make better input functions..
def input_with_choices(prompt, choices):
while True:
choice = input('{} (choices are: {}) '.format(prompt, ','.join(choices)))
if choice in choices:
return choice
else:
print("That's not a valid choice.")
and
def input_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("That's not an integer.")
etc.
Then you can use those to validate your input in the for loop.
Your question isn't very understandable, however, what I think you are looking for is this:
accepted = False
while not accepted:
try:
UserAns = int(input())
accepted = True
except:
pass

How to prevent any input except for numbers [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to coding. I've managed to produce this code which is a little test for children. It works fine I just need to prevent kids from entering letters or other characters when math questions are asked. Something like "please only enter numbers" should come up. I've tried a variety of functions like ValueError but with no luck. Any help will be appreciated!
import time
import random
import math
import operator as op
def test():
number1 = random.randint(1, 10)
number2 = random.randint(1, num1)
ops = {
'+': op.add,
'-': op.sub,
'*': op.mul,
}
keys = list(ops.keys())
rand_key = random.choice(keys)
operation = ops[rand_key]
correctResult = operation(number1, number2)
print ("What is {} {} {}?".format(number1, rand_key, number2))
userAnswer= int(input("Your answer: "))
if userAnswer != correctResult:
print ("Incorrect. The right answer is {}".format(correctResult))
return False
else:
print("Correct!")
return True
username=input("What is your name?")
print ("Hi {}! Wellcome to the Arithmetic quiz...".format(username))
while True:
try:
# try to convert the user's input to an integer
usersClass = int(input("Which class are you in? (1,2 or 3)"))
except ValueError:
# oh no!, the user didn't give us something that could be converted
# to an int!
print("Please enter a number!")
else:
# Ok, we have an integer... is it 1, 2, or 3?
if usersClass not in {1,2,3}:
print("Please enter a number in {1,2,3}!")
else:
# the input was 1,2, or 3! break out of the infinite while...
break
input("Press Enter to Start...")
start = time.time()
correctAnswers = 0
numQuestions = 10
for i in range(numQuestions):
if test():
correctAnswers +=1
print("{}: You got {}/{} {} correct.".format(username, correctAnswers, numQuestions,
'question' if (correctAnswers==1) else 'questions'))
end = time.time()
etime = end - start
timeTaken = round(etime)
print ("You completed the quiz in {} seconds.".format(timeTaken))
if usersClass == 1:
with open("class1.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 2:
with open("class2.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
elif usersClass == 3:
with open("class3.txt","a+") as f:
f.write(" {}:Scored {} in {} seconds.".format(username,correctAnswers,timeTaken))
else:
print("Sorry, we can not save your data as the class you entered is not valid.")
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter an integer value!")
Look, in your code:
import operator as op
# DEFINE THE `get_int` FUNCTION HERE
# (in global scope so other functions can call it)
def test():
then use it below:
userAnswer = get_int("Your answer: ") # call the function
# No ValueErrors!

Categories

Resources