With using String instead of Try/Except prevent crashing- How to? - string

I am writing a code for the wind chill index for an assignment for college.
The prof wants us to prevent the code from crashing upon user input of blank or letters, without using Try/Except Blocks. (He refers to string methods only).
Instead of crashing it should out put an error message eg. ("invalid input, digits only")
I tried utilizing the string.isdigit and string.isnumeric, but it won't accept the negative degrees as integers.
Any suggestions? (code below)
Would another "if" statement work?

Replace the punctuation:
if temperature.replace('-','').replace('.','').isnumeric():

Use an infinite loop and check that everything seems right.
Whenever there's an error, use the continue statement. And when all checks and conversions are done, use the break statement.
import re
import sys
while True:
print("Temperature")
s = sys.stdin.readline().rstrip('\n')
if re.match("^-?[0-9]+(\\.[0-9]+)?$", s) is None:
print("Doesn't look like a number")
continue
if '.' in s:
print("Number will be truncated to integer.")
temp = int(float(s))
if not (-50 <= temp <= 5):
print("Out of range")
continue
break

Related

Pycharm not prompting for input

[code that i have written , it is working fine but not prompting to enter a input and not processing the code when i run this , i have tries to check for file configuration but it is also fine][1]
[1]: https://i.stack.imgur.com/r4abs.pngcode that i have written , it is working fine but not prompting to enter a input and not processing the code when i run this , i have tries to check for file configuration but it is also fine
In python you have to be careful with indentation, since the guess() you call at the end is defined inside the function so it will not run as you wish. First, you must call the function from outside it.
In addition, you have indicated in the definition of the function def guess(x) that you must pass an argument, which you should also do. For example, this code is functional:
import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = int(input(f'Guess a number between 1 and {x}: '))
if guess < random_number:
print('Sorry, guess again. Too low.')
elif guess > random_number:
print('Sorry, guess again. Too high.')
print(f'Yay, congrats. You have guessed the number {random_number} correctly!!')
guess(10)
As you can see, the function is called after being declared (at the same indentation level, i.e. outside of it) and, in addition, an argument is passed to it.

What is an in-script code to terminate a script with an if function (when the value is not true)?

I am intending to end a script right after an "if" logic, when the logic returns a "true" result. Here it is:
age=int(input("Enter your age: "))
if age<=18:
print("You are not an adult. Please exit.")
exit() **#here is where I need the code to terminate and exit.**
else:
print("Your age is: ", age)
from datetime import date
print("This is the year ",date.today().year)
yr = date.today().year
yob=yr-age
print("You were born in the year: ",yob)
What would be the most appropriate command to terminate the sequence if the first "if" logic returns "true" i.e. if the age is below 18, the script should terminate. Many thanks in advance.
There can be many ways to end the script. It's tough to say what you want to achieve, without sharing any code here. But still in general you can try this-
1- Use pass keywords
2- if you are using loop, you can use break keyword
3- if you are using a function, just return nothing if the condition is not true.
4- you can also use 'try and except' block
5- You can use while loop

How to check if a var stored '#' or any special char

A simple code like this:
for input in sys.stdin:
if input=='#': break . #this is considered false even if I type # and wont break
print(input) #it prints #
I want the user to type # to stop the loop, but even if I type #, the statement is still considered false.
It's not just '#' but also '!' or '#' etc.
Does anyone know why? thanks.
Since you asked for the reason, I think its actually the break line you add at the end of your input. if you use this code it actually works:
import sys
for input in sys.stdin:
input = input.strip()
if input=='#':
break
print(input)
Here you can see that the breakline is in the string:
import sys
for user_input in sys.stdin.detach():
print(user_input)
The usual way to get input from a user is with the input function:
inp = input('Type something')
if inp!='#':
print(inp)
Running with input that is anything other than # will echo the input back to you, otherwise it will do nothing (break as you put, however this will not work as it is outside of a loop)
for something in sys.stdin:
...
The code above does not work as you expect because sys.stdin is a file handle and it will not reach the some '...'.
But you can use the code below and it will break as you would expect:
inp = input('Write here:')
if inp!='#':
print(inp)

Defining function difficulties ["NameError: name 'number' is not defined"]

Okay, trying to make a simple game of Guessing Numbers but I can't find the mistake in this code. Still pretty new to python so probably the reason why but I can't figure out what is wrong with it.
import random
from time import sleep
def start():
print("Welcome To The Guessing Game \n Try to guess the number I'm thinking of \n Good luck!")
selectRandomNumber()
guessCheck(number, numberInput=1)
def restart():
print("Creating new number ...")
sleep(1)
print("OK")
selectRandomNumber()
guessCheck(number,numberInput=1)
def selectRandomNumber():
number = random.randint(0,1000)
tries = 0
return
def tryAgain():
while True:
try:
again = int(input("Do you want to play again? y/n:"))
except ValueError:
print("Couldn't understand what you tried to say")
continue
if again == "y" or "yes":
print("Awesome! Lets go")
restart()
elif again == 'n' or "no":
print("Goodbye!")
break
else:
print("Not a valid option")
continue
def guessCheck(number,numberInput=1):
while True:
try:
numberInput = int(input("What number do you think it is?: "))
except ValueError:
print("Couldn't understand that. Try again")
continue
if numberInput > number:
print("Too high")
tries += 1
continue
elif numberInput < number:
print("Too low")
tries += 1
continue
elif numberInput == number:
print("Congrats! You got my number")
tryAgain()
number = selectRandomNumber()
print(number)
start()
Every time I try to run the program I keep getting the same mistake.
It tells me:
Traceback (most recent call last):
File "python", line 60, in <module>
start()
File "python", line 8, in start
guessCheck(number, numberInput)
NameError: name 'number' is not defined
Don't quite understand what that means.
Some help would be appreciated. Thanks!
* UPDATE *
Was able to fix the part about defining the variable but now new problem happened where when I try to run
Same code as before but added
guessCheck(number,numberInput=1)
and also added the variable number at the end
number = selectRandomNumber()
print(number)
start()
when I run it I get this
None # this is from `print(number)` so instead of getting a number here I'm getting `None`
Welcome To The Guessing Game
Try to guess the number I'm thinking of
Good luck!
What number do you think it is?:
The Traceback is telling you this:
We got to start().
start() called guessCheck().
We tried to pass two pieces of information to guessCheck(): the variable names number and numberInput.
We don't have those variables defined yet! numberInput doesn't get defined until once we've already started guessCheck(), and number isn't actually defined anywhere.
As Manoj pointed out in the comments, you probably want number to hold the output of selectRandomNumber(). So, instead of just calling selectRandomNumber() in start(), try number = selectRandomNumber() instead.
You can add a print(number) on the line right after that to make sure number has a value assigned to it.
Now number has a value, going into your call to guessCheck(). That still leaves numberInput undefined though. You can set a default value for function arguments like this:
guessCheck(number, numberInput=1)
That way, when guessCheck is called but numberInput hasn't been defined yet, it will automatically give it the value 1 until you set it explicitly.
You may encounter other issues with your code the way it is. My advice would be to start really simply - build up your game from each individual piece, and only put the pieces together when you're sure you have each one working. That may seem slower, but trying to go too fast will cause misunderstandings like this one.

Python Recrusive Statement Error not Defined

I am trying to test each input then return that the number is cleared then do the math. For Example is a user inputs N instead of a number I want it to output that its not a number whereas if the user inputs 1 then I want it to move to the next function asking for a power then do the same thing and if that passes then goes to the final section which output the answer to the problem.
The program passes both the errors for the non number areas yet when it get to very last function it is telling me base nor power are defined.
Code is written in some Python2 and some Python3. All works fine though. I use python3 mostly.
[Test Picture/Error Msg][1]
# Below we are creating the recursive statement to do the math for us. We are calling Base and Power
# from the main function where the user Inputs the numbers.
def pow(base, power):
if power == 0:
return 1
if power == 1:
return base
else :
return base * pow(base, power - 1)
def determineBase():
while True:
try:
base = int(input ('Please Enter A Base: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return base
def determinePower():
while True:
try:
power = int(input ('Please Enter A Power: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return power
def main():
determineBase()
determinePower()
pow(base,power)
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
main()
def main():
determineBase()
determinePower()
pow(base,power)
Here, neither base nor power are defined. What you meant instead was to store the result from those function calls and pass those then:
def main():
base = determineBase()
power = determinePower()
pow(base, power)
The issue isn't inside the recursive function, it's inside your main function.
The problem is arising due to the fact that you are passing base as an argument to the pow() function without defining the variable base first (the same would subsequently be true for power).
In other words you need something along the lines of:
def main():
base = determineBase()
power = determinePower()
pow(base,power) #this line could probably be removed
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
As currently, you're not storing the values of these two functions.

Resources