I'm just beginning with programming(python3), using the information available on Internet. Right now I'm learning how to use try/except. My problem is that the code I wrote runs fine in the command prompt of windows 10, but not in the shell(Atom/Hydrogen) where it throws an error(line 6, NameError) because I didn't defined the variable "fish", I know that usually happened the other way around but I just want to understand if I'm making a mistake. The code is as follows:
>try:
>> fish = int (input("please enter your age "))
>except:
>> print("That's not a number ")
>> exit(0)
>if fish <= 15:
>> parentLicense = input ("have one of your parents have a license? (yes/no) ")
>> if parentLicense == "yes":
>>> print ("You can fish")
>> else:
>>> print("So sad, you or one of your parents need a license")
Hi Chiron and welcome to the community. The reason you are getting an undefined error is because fish can be undifined under certain circumstances in the try statement.
You should use
try:
# try stuff
except ValueError:
# do stuff when theres an error
else:
# stuff if try stuff works
else is only called if no exception is raised. I would avoid using bare except too as it can cause issues and its not good practice.
Related
[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.
enter image description hereI am a begineer in Python development and learning python on python 3.6
When I executed below code ,I expected it to terminate when first return statement is executed and I was expecting Output 4.
But It is iterating 3 times and giving output as 8.
As per my understanding as soon as return statement is executed it should come out of the function. Why this is not happening.
#!/bin/python3
def stockmax(prices):
# Write your code here
# Write your code here
count=0
profit=0
maximum=max(prices)
#print(maximum)
index_max=prices.index(maximum)
#print(index_max)
if len(prices)<=1:
return(profit)
else:
for i in range(len(prices)):
if i<index_max:
profit=profit-prices[i]
#print("profit if",profit)
count=count+1
#print("count is",count)
elif i==index_max:
#print(profit)
profit=profit+(prices[i]*count)
#print("profit elif",profit)
count=0
else:
profit=profit+stockmax(prices[i:])
return(profit) # should terminate on executing first return
x=(stockmax([5,4,3,4,5]))
print(x)
By calling stockmax inside of itself, you are opening up a new 'scope'. We can treat these as levels on a building. When you call it, you are essentially moving up a floor, or gaining a level. To get back to the ground floor, or the main 'scope' you need to go back through all of the lower floors. We can do this easily by using return a little bit sooner. In your code it would look a little like this:
def stockmax(prices):
count=0
profit=0
maximum=max(prices)
index_max=prices.index(maximum)
if len(prices)<=1:
return(profit)
else:
for i in range(len(prices)):
if i<index_max:
profit=profit-prices[i]
count=count+1
elif i==index_max:
profit=profit+(prices[i]*count)
count=0
else:
profit=profit+stockmax(prices[i:])
return(profit) # Use return here instead!
This would give us the desired output of 4.
Im writing the code in text editor and execute it by double clicking the code. The code is fairly simple:
n_inp = int(input("N: "))
num = []
for i in range(n_inp):
num.append(int(input("Number: " )))
print(num)
but for some reason the program just stopped after the loop is finished. It never prints the num, the program just closed. I tried using sleep command after the print(num) to see if it changes anything but it doesnt. Is there a problem with the code? Or should i just use some IDE to execute it? Thanks in advance.
edit: the code runs fine when executed from command prompt, i just wont run a code by double clicking again.
but i tried the same code in python3 it's working correctly...
num prints the output like....
N: 3
Number: 12
Number: 13
Number: 14
[12, 13, 14]
You are not able to see the output because it will close the terminal immediately after printing the output. You can just add sleep after the print(num) statement. Try the following code.
import time
n_inp = int(input("N: "))
num = []
for i in range(n_inp):
num.append(int(input("Number: " )))
print(num)
time.sleep(10)
or add one more input() after the print statement so that it will wait until you press any other button.
n_inp = int(input("N: "))
num = []
for i in range(n_inp):
num.append(int(input("Number: " )))
print(num)
input()
what I want is something like this:
The first file just prints as soon as the 2nd has read
# a.py
print('pepe')
# wait till the other had read
print(23)
The second program uses data from the later
# b.py
name = input()
age = int(input())
print('Hi ' + name + ', you are ' str(age))
So I can see in the console:
Hi pepe, you are 23
I want to do this because, I waste a lot of time typing in the console. And I want to do it automatically.
Just in case, I browsed for this thing a long time, but no idea, that is why I decided to ask here.
A couple of different ways.
1) while True:
an infinite loop that requires you to use some sort of
while True:
cmd = input("type something")
if cmd == 'e':
do something
elif cmd == 'f':
do something else
else:
do that last thing
2) input("press enter to continue")
input('press enter to continue')
Hopefully that gets you what you need...
You can also learn more here: How do I make python to wait for a pressed key
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.