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

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()

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 :)

Implementing a timer into Math game in Python

import random
from tkinter import *
import tkinter as tk
import time
scores = []
score = 0
#introduction
def start():
print(" Welcome to Maths Smash \n")
print("Complete the questions the quickest to get a better score\n")
username = True #this makes sure the user can only enter characters a-z
while username:
name = input("What is your name? ")
if not name.isalpha():
print("Please enter letters only")
username = True
else:
print("Ok,", name, "let's begin!")
main()
#menu
def main():
choice = None
while choice !="0":
print(
"""
Maths Smash
0 - Exit
1 - Easy
2 - Medium
3 - Hard
4 - Extreme
5 - Dashboard
"""
)
choice = input("Choice: ")
print()
#exit
if choice == "0":
print("Good-bye!")
quit()
#easy
elif choice == "1":
print("Easy Level")
easy_level()
#medium
elif choice == "2":
print("Medium Level")
medium_level()
#hard
elif choice == "3":
print("Hard Level")
hard_level()
#extreme
elif choice == "4":
print("Extreme Level")
extreme_level()
#teacher login
elif choice == "5":
print("Dashboard")
from GUI import dashboard
dashboard()
else:
print("Sorry but", choice, "isn't a vaild choice.")
def easy_level():
global score
#easy level
for i in range(10):
operator_sign =""
answer = 0
num1 = random.randint(1,5)
num2 = random.randint(1,5)
operator = random.randint(1,4)
#choosing the operator randomly
if operator == 1:
operator_sign = " + "
answer = num1 + num2
elif operator == 2:
operator_sign = " - "
answer = num1 - num2
elif operator == 3:
operator_sign = " * "
answer = num1 * num2
elif operator == 4:
operator_sign = " / "
num1 = random.randint(1,5) * num2
num2 = random.randint(1,5)
answer = num1 // num2
else:
print("That is not a vaild entry!\n")
#outputting the questions along with working out if it's correct
question = str(num1) + operator_sign + str(num2) + "\n"
user_input = int(input(question))
if user_input == answer:
score = score + 1
#total score
print("You scored:", str(score), "out of 10")
Been trying to add a timer in this game for a while but every time I go to the first level it doesn't work with the game at the same time, as in I will load the first level and none of the questions will pop-up until the timer has completed. Was wondering if anyone could help me or know a fix to this, I want to make it so if the user completes the test within a certain amount of time they get an additional 10 points added to the overall score. This is what I had come up with at first:
def timer():
countdown=120
while countdown >0:
time.sleep(1)
score = score + 10

Break or continue a while loop from a function

I'm trying to have a while loop ask a series of question and restart when the last question is asked. The thing is, I want the user to have the ability to quit by typing a specific word at any question. I also want as little code as possible in the loop, so the if/elif statements lays in functions.
My question is: Can I continue or break a loop from a function?
My code:
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
check_age(age)
#And so on with questions
Is this possible?
You can return some(for example bool) value from function check_age(q) and check it.
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
if q == "foo":
return True
else:
return False
while True:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
if check_age(age):
break
The best way probably is to raise a custom Exception from inside the question functions as follows:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
NUMBER_MEN, NUMBER_WOMEN = 0, 0
class ExitLoop(Exception):
pass
def check_gender(reply):
global NUMBER_WOMEN, NUMBER_MEN
while True:
if reply == "f":
NUMBER_WOMEN += 1
return
elif reply == "m":
NUMBER_MEN += 1
return
elif reply == "foo":
raise ExitLoop
else:
print("Please answer M or F: ")
reply = input("Are you a male or female (M/F)? ").lower()
def check_age(reply):
if reply == "foo":
raise ExitLoop
if not 16 <= int(reply) <= 25:
print("You are not in the age range for this survey")
return False
return True
while True:
try:
gender = input("Are you a male or female (M/F)? ").lower()
check_gender(gender)
age = input("Please enter your age: ")
inrange = check_age(age)
if not inrange:
continue
except ExitLoop:
break
I made a few other changes to your code to make it a bit more pythonic. Be careful by the way, the code above fails when the user enters anything but 'foo' or a number in reply to the age question.
By the way, if you want to ask your user a lot of questions, you might want to check out the excellent Click package.
Hope this helps!
You should try this code, is someone put other letter the loop will break
def check_gender(q):
if q == "f":
number_women = number_women + 1
elif q == "m":
number_men = number_men + 1
# elif q == "foo":
#break the loop
else:
print("Please answer M or F: ")
q = input("Are you a male or female (M/F)? ").lower()
check_gender(q)
def check_age(q):
if not(16 <= int(q) <= 25):
print("You are not in the age range for this survey")
#Jump back to first question here
#if q == "foo":
#break the loop
while True:
gender = input("Are you a male or female (M/F)? ").lower()
if gender != "f" and gender != "m":
break
else:
check_gender(gender)
age = input("Please enter your age: ")
try:
ageValue = int(age)
check_age(age)
except ValueError:
print ("You must enter a number")
break

Trying to create a confirmation for my code so that it will allow user to change answer

I wanted to add a confirmation for my code so that the user will be able to change their input. I haven't yet added the loop for the question but for some reason when I run this it fails to run def calc() and therefore the calculations I created cannot continue. Help!!
n=0
x=0
while True:
numbers = input("Please enter a, b,c, or, d to select a equation")
if numbers == "a":
n =3
x = 2
break
elif numbers =="b":
n = 4
x = 5
break
elif numbers == "c":
n=5
x=6
break
elif numbers == "d":
n=6
x=7
break
else:
print("Please enter a,b,c, or d")
w = float(input("Please enter weight"))
choice = input("Is this your answer?")
if choice == "yes":
def calc():
if n > w :
weight = (x - w)
weight2 = weight/n
print(weight)
elif w < x:
weight = (w - x)
weight2 = weight/n
print(weight)
calc()
elif choice =="no":
print ("Lets change it")
else:
print("Please respond with 'yes' or 'no'")

Categories

Resources