Python try except problems - python

So im having a little trouble with a project im working on. I'm not an expert with Python nor am I an idiot when it comes to coding. This problem may have a very simple answer but I cant seem to get it right. My entire code asks a user to answer questions using a random choice from a list.
import turtle
import random
turtle.speed("fastest")
pi = 3
minNumber = 5
maxNumber = 10
score = 0
listNmbers = []
a = [1,3,5,7,9]
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
def drawSquare():
for i in range(4):
turtle.begin_fill()
turtle.pendown()
turtle.forward(50)
turtle.left(90)
turtle.end_fill()
turtle.right(360/userAnswer)
turtle.penup()
turtle.setpos(-700,-200)
turtle.fillcolor("green")
print("Welcome! What is your name??")
name = str(input())
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
badInput = False
while not (badInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
badInput = (numbers >= 4) or (numbers >= maxNumber)
if badInput == False:
print ("Please input an integer between 5 and 10 please")
badInput = False
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(int(num)):
red = random.random()
green = random.random()
blue = random.random()
num1 = random.choice(a)
turtle.color(red,green,blue)
correct = num1 * 3
print("What is the cirumference of the circle if", num1,"is the diameter and Pi is 3?")
userAnswer = int(input())
if userAnswer == correct:
print("That's Correct! Well Done")
score = score + 1
for k in range(correct):
turtle.color(red,green,blue)
drawSquare()
turtle.penup()
turtle.forward(150)
else:
print("sorry thats is incorrect")
in this bit of code, it asks the user how many questions they want to ask (as an integer). My code works well when a number within the parameters are given, but as soon as a number such as 19 is given, it continues when it should not. Also if a string is given, it works well and asks again for an integer, but if an integer is given after being asked, it crashes. The error read:
for i in range(int(num)):`ValueError: invalid literal for int() with base 10: 'test'`
All help would appreciated so much. thank you all

And you're hidding too much code within a generic try..except (try to Ctrl+C while input is required... nope!). I would write that function in that way:
def getNumbers():
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
try:
number = int(num)
except:
print("Not a number!")
return getNumbers()
goodInput = minNumber < number < maxNumber
if not goodInput:
print ("Please input an integer between 5 and 10 please")
return getNumbers()
else:
return number
number = getNumbers()

getNumbers() doesn't return any value. Thus, it implicitly returns None, which you assign to numbers, here:
numbers = getNumbers(numbers)
Make sure that wherever you exit the getNumbers() function, you return numbers (probably at the end:
def getNumbers(numbers):
....
return numbers

EDIT: #see xbello answer to have a working answer. My "poisoned" code isn't working as expected ;)
First of all I must say that your code isn't really nice to read... But here are some fixes that should do the trick
maxNumber = 10
print("Hello", name,"you need to calculate the circumference of a circle when given a diameter. To calculate the circumference, use the equasion; Pi x Diameter (Pi = 3")
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
def getNumbers(numbers):
try:
goodInput = False
while not (goodInput):
num = input("how many questions would you like to answer? (Pick between 5 and 10)")
numbers = int(num)
# Here was a bad condition having a look at your comments
goodInput = (numbers > 4) and (numbers <= maxNumber)
if goodInput == False:
print ("Please input an integer between 5 and 10 please")
# goodInput is already False, no need to set it again
# Here is the missing return
return numbers
except:
print("Please input an integer between 5 and 10")
numbers= 0;
numbers = getNumbers(numbers)
numbers= 0;
numbers = getNumbers(numbers)
for i in range(numbers):
#Do stuff
You can see that I added a return value to your function (that returned None by default) and that I take this return value to push it into "numbers" afterwards. That "numbers" value can then be pushed into a range() function to make a nice for loop.

Related

Factorial using two functions Python 3.x

Hello everyone I have a homework assignment that I am supposed to do in python 3.x
I am struggling to figure out how to do this so I'm hoping you can explain to me how to about this.
Problem
The factorial of a positive integer n (written n!) is the product 1 x 2 x 3 x ... x n. Write a program that asks the user to input a positive integer and then calculates and displays the factorial of the number. The program should include two functions: getN to which the input is sent, and which guarantees that the input is a positive integer. The function fact should calculate the factorial value. The program (main) should then display the factorial value.
So far I have a rough sketch of how I want to go about this
#This program will show the answer to a factorial after the user inputs a value.
def getN(n):
try:
n = int(input("Please enter a non-negative integer: "))
except n < 1:
print("You did not enter a value of 1 or greater.")
def fact(n):
count = 1
while n > 0:
count *= n
n -= 1
if n == 0:
break
def main(n):
n = int(input("Please enter a non-negative integer: "))
getN(n)
main(n)
I believe its supposed to look something like this. If you can give me some feedback about what I should do that what be greatly appreciated. Thanks!
Please see inline comments
def getN():
try:
n = int(input("Please enter a non-negative integer: "))
if n < 1:
raise ValueError # it will be thrown also if input is not a valid int
except ValueError: # n < 1 is not an Exception type
print("You did not enter a value of 1 or greater.")
else:
return n
def fact(n):
count = 1
for i in range(1, n+1): # you see how simple it is with for loop?
count *= i
return count
def main():
n = getN() # before you were just asking n twice, never using fact()
print(fact(n))
main()
Seems reasonable to me. It looks like you never return or print the actual factorial calculation. Maybe your function 'fact' should "return count"? In addition, you don't need to check "if n==0" in your fact function, since if it is 0 it will end the while loop due to the condition of the while loop.

Python help (computer guess number)

I'm learning how to program in Python and I found 2 tasks that should be pretty simple, but the second one is very hard for me.
Basically, I need to make a program where computer guesses my number. So I enter a number and then the computer tries to guess it. Everytime it picks a number I need to enter Lower or Higher. I don't know how to do this. Could anyone advise me on how to do it?
For example (number is 5):
computer asks 10?
I write Lower
computer asks 4?
I write Higher
Program:
I already made a program which automatically says Higher or Lower but I want to input Lower or Higher as a user.
from random import randit
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.
from random import randint
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
guess = randint(min,max)
print(guess,"?")
answer = str(input("Higher/Lower? "))
if answer == 'Higher':
min = guess
elif answer == 'Lower':
max = guess
attempts += 1
print("I needed", attempts, "attempts")
from random import randit
attempts = 0
guess = 0
min = 0
max = 100
while guess != number:
number = int(input("Number? "))
guess = randint(min,max)
print(guess,"?")
if guess < number:
print("Higher")
min = guess
elif guess > number:
print("Lower")
max = guess
attemps += 1
print("I needed", attempts, "attemps")
problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help
from random import randint
print('choos a number in your brain and if guess is true enter y else any key choose time of guess: ')
print("define the range (A,B) :")
A = int(input("A: "))
B = int(input("B: "))
time = int(input("time:"))
while time != 0:
ran = randint(A, B)
inp = input(f"is this {ran} ?")
time -= 1
if inp == "y":
print("bla bla bla computer wins!")
break
print("NOPE!")
if time == 0:
print("computer game over!")
break
from random import *
number = int(input("Number? "))
attempts = 0
guess = 0
min = 0
max = 100
attemps =0
guess = randint(min,max)
while guess != number:
userInput=input(str(guess)+"?")
if userInput.lower()=="lower":
max=guess
elif userInput.lower()=="higher":
min=guess
attemps += 1
guess = randint(min,max)
print("I needed", attemps, "attempts to guess ur number ="+str(guess))
output:
Number? 5
66?lower
63?lower
24?lower
19?lower
18?lower
10?lower
4?higher
9?lower
6?lower
4?higher
I needed 10 attempts to guess ur number =5

How to Separate a Range of Odd and Even Numbers Through Searching the Array While Skipping Numbers

I'd like to challenge myself and develop my programming skills. I would like to create a program that asks for the user to enter a range of numbers where odd and even numbers should be separated (preferably through search) and also separated by a specified jump factor.
Also the user should be allowed to choose whether or not they would like to continue. And if so they can repeat the process of entering a new range.
for example when the program is run a sample input would be:
"Please enter the first number in the range": 11
"Please enter the last number in the range": 20
"Please enter the amount you want to jump by": 3
and the program would output:
"Your odd Numbers are": 11,17
"Your even Numbers are": 14,20
"Would you like to enter more numbers(Y/N)":
So far what I have for code is this but am having trouble putting it together and would appreciate some help.
import sys
print("Hello. Please Proceed to Enter a Range of Numbers")
first = int(input("please enter the first number in the range: "))
last = int(input("please enter the last number in the range: "))
jump = int(input("please enter the amount you want to jump by: "))
def mylist(first,last):
print("your first number is: ",first,"your last number is: ",last,"your jump factor is: ",jump)
def binarySearch (target, mylist):
startIndex = 0
endIndex = len(mylist) – 1
found = False
targetIndex = -1
while (not found and startIndex <= endIndex):
midpoint = (startIndex + endIndex) // 2
if (mylist[midpoint] == target):
found = True
targetIndex = midpoint
else:
if(target<mylist[midpoint]):
endIndex=midpoint-1
else:
startIndex=midpoint+1
return targetIndex
print("your odd Numbers are: ")
print("your even Numbers are: ")
input("Would you like to enter more numbers (Y/N)?")
N = sys.exit()
Y = first = int(input("please enter the first number in the range"))
last = int(input("please enter the last number in the range"))
jump = int(input("please enter the amount you want to jump by: "))
question - "So far what I have for code is this but am having trouble putting it together and would appreciate some help."
answer -
As a start, it seems like a good idea to group your inputs and outputs into functions! Then putting it together is a snap!
def get_inputs():
bar = input('foo')
def process_inputs():
bar = bar + 1
def print_outputs():
print(bar)
if '__name__' == '__main__':
get_inputs()
process_inputs()
print_outputs()
You could even toss in something like if input('more? (Y/N):') == 'Y': in a while loop.
Maybe I'm missing something but couldn't you replace your binary search with the following?
>>> list(filter(lambda x: x%2 == 1, range(11, 20 + 1, 3)))
[11, 17]
>>> list(filter(lambda x: x%2 == 0, range(11, 20 + 1, 3)))
[14, 20]

Passing Variables/lists through Functions

Im having trouble with sorting Variables/lists and then being able to transfer them across functions. Im still quite new to python and am probably missing something very basic. but ive been going over this for hours.
I need to create a program which generates 20 random integers and indicates whether each number is odd or even. I need to sort the two original integers into ascending order and transfer them to random.randint function but am having trouble, any help would be appreciated.
This is what i have so far.
import random
def userinput():
global number1
global number2
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
userinput()
def numbersorting():
global both
both = [(number1),(number2)]
sorted(both)
numbersorting()
def random_gen():
global num
i = 0
for i in range(20):
num = random.randint(number1,number2)
def get_num():
return values.pop
def odd_even():
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
odd_even()
random_gen()
Well it doesn't seems so clear on the question what actually you want to do but the use of global is a really bad practice in general.
However you can use the methods that returns the values you need for instace:
If you need a user input that returns 2 numbers it is better to use this approach:
def get_numeric_input(label):
try:
return int(input(label))
except NameError:
print "Please enter a number"
return get_numeric_input(label)
With this function you can get a numeric value from a user.
Using it you can the 2 next values like
def get_user_input():
n = get_numeric_input("Enter First Integer: ")
m = get_numeric_input("Enter First Integer: ")
return [n, m]
Now you have a function that returns the 2 values from the user and using the sort method for list you have those values sorted
def get_sorted_values(l):
return l.sort()
Check this information about sorting in python https://wiki.python.org/moin/HowTo/Sorting
Using the random numbers as you have described is ok, but also try to use the is_odd and is_even function outside of any other function and you will be able to reuse them more times.
Are you looking for something like this?
I edited your code to work with what I understand your problem to be...
You want the user to input 2 numbers to set the upper and lower bound of each random number. Then you want to generate 20 random numbers within that range and find out whether each number of even or odd?
import random
def random_gen(number1, number2):
for i in range(20):
num = random.randint(number1,number2)
if num % 2 == 0:
print("Random Number", num, "is even")
else:
print("Random Number", num, "is odd")
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
random_gen(number1, number2)
You have a few problems with your current code:
Indentation (fixed in the edit)
Unnecessary use of global variables. If you need that type of functionality you should consider passing the variables into each function as you need it instead
A number of functions are unnecessary too. For example, you dont need the get_num() and odd_even() functions as you can just perform those actions within the loop that you have. Even in the case I just posted you dont even really need the random_gen() function - you can just move all of that code to after user input. I just left it there to show what I mean with point #2 above
from random import randint
def user_input():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
if number1 > number2:
number1, number2 = number2, number1
return number1, number2
def odd_even(num):
if num % 2 == 0:
print("Random Number " + str(num) + " is even")
else:
print("Random Number " + str(num) + " is odd")
def random_gen():
number1, number2 = user_input()
for i in range(20):
num = randint(number1, number2)
odd_even(num)
random_gen()
You generally want to try to avoid using global variables when possible. It's just good programming practice, as they can get rather messy and cause problems if you don't keep careful track of them. As far as sorting your two integers, I think that that one if statement is a much more pythonic way of doing things. Well, I think it's easier at least. Also, in Python, you don't need to declare your for loop variables, so the line i=0 is unnecessary. Also, I'm sure this is an assignment, but in real life you're going to want to run an exception clause, in which you would say something like
while True:
try:
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
break
except ValueError:
print("Oops! Try entering an integer!")
Hope that helps!
Avoid globals by passing the variables to functions and returning the new values from functions.
import random
def userinput():
number1 = int(input("Enter First Integer: "))
number2 = int(input("Enter Second Integer: "))
return number1, number2
def numbersorting(nums):
return sorted(nums)
def random_gen(hi, lo):
return random.sample(range(hi, lo), 20)
def odd_even(num):
if num % 2 == 0:
print("Random Number %d is even" % num)
else:
print("Random Number %d is odd" % num)
nums = userinput()
sortnum = numbersorting(nums)
randoms = random_gen(*sortnum)
[odd_even(n) for n in randoms]
In keeping with your original function names.
You should be aware of the difference between list.sort and sorted. If you have a list li then li.sort() sorts in place, that is it alters the original list and returns None. So return li.sort() is always wrong. on the other hand return sorted(li) is ok, but just sorted(li) is a wasted sort since the result is thrown away.
Try both.sort()
sorted returns a new list.
sort() is done in place.

Hotter/Colder Number Game in Python

I'm working my way through the Code Academy Python course and have been trying to build small side projects to help reinforce the lessons.
I'm currently working on a number game. I want the program to select a random number between 1 and 10 and the user to input a guess.
Then the program will return a message saying you win or a prompt to pick another higher/lower number.
My code is listed below. I can't get it to reiterate the process with the second user input.
I don't really want an answer, just a hint.
import random
random.seed()
print "Play the Number Game!"
x = raw_input("Enter a whole number between 1 and 10:")
y = random.randrange(1, 10, 1)
#Add for loop in here to make the game repeat until correct guess?
if x == y:
print "You win."
print "Your number was ", x, " and my number was ", y
elif x > y:
x = raw_input("Your number was too high, pick a lower one: ")
elif x < y:
x = raw_input("Your number was too low, pick a higher one: ")
You need use a while loop like while x != y:. Here is more info about the while loop.
And you can only use
import random
y = random.randint(1, 10)
instead other random function.
And I think you should learn about int() function at here.
These are my hints :)
import random
n = random.randint(1, 10)
g = int(raw_input("Enter a whole number between 1 and 10: "))
while g != n:
if g > n:
g = int(raw_input("Your number was too high, pick a lower one: "))
elif g < n:
g = int(raw_input("Your number was too low, pick a higher one: "))
else:
print "You win."
print "Your number was ", g, " and my number was ", n

Categories