Python - Need advice - python

Below I have a script that I have done while trying to complete for a assignment I have.
What the script is suppose to do is ask the user for 2 inputs and then return the greater of the inputs. (This I havent figured out completely yet)
The point of this assignment is too see what happens if I instead of entering 2 numbers, enter two words "Hej" and "Hå".
What I need some advice on is how to enable this script to accept 2 user inputs and return the greater of them two.
def maximum(x, y):
i = 0
maxnra = 0
maxnrb = 0
while i < len(x) :
if x[i] > maxnra:
maxnra = x[i]
i = i + 1
else:
i = i + 1
print "I första ordet är maximum: ", maxnra
i = 0
while i < len(y) :
if y[i] > maxnrb:
maxnrb = y[i]
i = i + 1
else:
i = i + 1
print "I andra ordet är maximum: ", maxnrb
maximum("hej", "hå")
EDIT:
I tried working this out another way, is this a way to solving this?
print "First"
x = input()
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif a == b:
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
right now im missing something cause it's not returning anything when I enter the 2 values.

Read documention on the command raw_input to see how you can get input from the user.

If you just want a simple way to get user input from the terminal window, have a look at the raw_input function.

Your first code would simply takes two lists and prints the maximum value of each individual list. So, this is not that you want.
In the second code, although the approach is right, you made some minor mistakes.
print "First"
x = input() # use raw_input() for python 2.7
print "Second"
y = input()
def printMax(x, y):
if x > y:
print(x, 'is maximum')
elif x == y:
# not a==b
print(x, 'is equal to', y)
else:
print(y, 'is maximum')
Actually, when you enter input in this code, though you enter numbers they are still considered as strings. So, there would be no big difference if you enter a string.
These strings are compared lexicographically using (ASCII value order). As your input isn't from ASCII, it will show error.
So, you need to replace input() or raw_input() with the following
import sys # do this at the top of program.
x = raw_input().decode(sys.stdin.encoding)
# similarly do it for y
Please read the following stackoverflow question to know more on this link

Related

Add tuples to a list

I have a problem with a simple program; my aim is to add tuples to a list, put in input by the user. The while-loop should break when the user puts 0.
this is my code:
sList=[]
x=tuple(input("insert tuple (0 to stop): "))
while x!=int(0):
sList.append(x)
x=tuple(input("insert tuple (0 to stop): "))
print (sList)
The problem is that the while loop never stops, even if I put 0, where is the mistake?
Please read the following lines in order to understand how to fix the error in your code:
sList=[]
x=tuple(input("insert tuple (0 to stop): "))
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
while int(x[0])!=int(0):
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
sList.append(x)
x=tuple(input("insert tuple (0 to stop): "))
print (sList)
You are comparing the string (0,) to the int value 0.
This is why your version doesn't work as expected.
I've also added two more prints to better understand what the code is doing.
Once we understood the nature of the error and how to fix it I would like to ask you why using a tuple in this case.
Could using an int directly be a good idea?
We could also reduce the number of lines and remove duplicated code, here's another iteration:
sList=[]
x = None
while x != 0:
print("x contains: " + str(x))
print("x type is: " + str(type(x)))
x = input("Insert 0 to stop: ")
if (x != None) and x.isdigit():
x = int(x)
if x != 0:
sList.append(x)
print (sList)
There are two problems in your code (as far as I have understand your issues):
a. You need to first convert the input from user (which will be string) to tuple. You can use:
t = tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(','))
b. You need to modify your while loop test expression to:
while len(t):
Assumptions that I have made:
You want the user to type comma separated values (Because having a single value tuple in your list doesn't make sense to me. Correct me if I have missed something)
You want to end your while loop if user hasn't entered any value (,i.e., has pressed the Enter key).
If my assumptions are correct, try this:
def check_int(s):
if len(s) == 0:
return False
if s[0] in ('-', '+'):
return len(s) > 0 and s[1:].isdigit()
return s.isdigit()
sList=[]
x=tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(',') if check_int(x.strip()))
while len(x):
sList.append(x)
x=tuple(int(x.strip()) for x in input("insert tuple (0 to stop): ").split(',') if check_int(x.strip()))
print(sList)

Can't figure out how to make my funtion not return None in Python

I have a program I am trying to make which will either show all the factors of a number or say it is prime. It's a simple program but I have one main issue. Once it prints all of the factors of an inputted number, it always returns none. I have tried multiple ways to get rid of it but nothing works without screwing something else up. The code is below.
def mys(x):
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
print(mys(x))
That code is just for printing the factors but that is where the problem lies. The results I get after entering a number, in this case 20, are as follows:
2
4
5
10
None
No matter what I do, I can't get the None to not print.
So if you don't want the return value of mys (None) not printed, then don't print it:
mys(x)
In python, a function that has no return statement always returns None.
I guess what you are trying to do is calling the mys function, and not printing it.
Note that you should remove x parameter, because it is asked inside of the function.
def mys():
x = input("Enter a number: ")
for i in range(2,x):
r = x % i
if r == 0:
print(i)
mys()
It would be better not to include user input and printing in your function. It would make it easier to test and to reuse:
def mys(x):
result = []
for i in range(2,x):
r = x % i
if r == 0:
result.append(i)
return result
x = input("Enter a number: ")
print(mys(x))

Alternative to Goto, Label in Python?

I know I can't use Goto and I know Goto is not the answer. I've read similar questions, but I just can't figure out a way to solve my problem.
So, I'm writing a program, in which you have to guess a number. This is an extract of the part I have problems:
x = random.randint(0,100)
#I want to put a label here
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
#And Here I want to put a kind of "goto label"`
What would you do?
There are lots of ways to do this, but generally you'll want to use loops, and you may want to explore break and continue. Here's one possible solution:
import random
x = random.randint(1, 100)
prompt = "Guess the number between 1 and 100: "
while True:
try:
y = int(raw_input(prompt))
except ValueError:
print "Please enter an integer."
continue
if y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number: "
else:
print "Correct!"
break
continue jumps to the next iteration of the loop, and break terminates the loop altogether.
(Also note that I wrapped int(raw_input(...)) in a try/except to handle the case where the user didn't enter an integer. In your code, not entering an integer would just result in an exception. I changed the 0 to a 1 in the randint call too, since based on the text you're printing, you intended to pick between 1 and 100, not 0 and 100.)
Python does not support goto or anything equivalent.
You should think about how you can structure your program using the tools python does offer you. It seems like you need to use a loop to accomplish your desired logic. You should check out the control flow page for more information.
x = random.randint(0,100)
correct = False
prompt = "Guess the number between 1 and 100: "
while not correct:
y = int(raw_input(prompt))
if isinstance(y, int):
if y == x:
correct = True
elif y > x:
prompt = "Wrong! Try a LOWER number: "
elif y < x:
prompt = "Wrong! Try a HIGHER number "
else:
print "Try using a integer number"
In many other cases, you'll want to use a function to handle the logic you want to use a goto statement for.
You can use infinite loop, and also explicit break if necessary.
x = random.randint(0,100)
#I want to put a label here
while(True):
y = int(raw_input("Guess the number between 1 and 100: "))
if isinstance( y, int ):
while y != x:
if y > x:
y = int(raw_input("Wrong! Try a LOWER number: "))
else:
y = int(raw_input("Wrong! Try a HIGHER number "))
else:
print "Try using a integer number"
# can put a max_try limit and break

Is there any way to make this Python function run for more intervals?

I am extremely new to python and just wrote up this really simple code. In the end this is something I made just to get my feet wet and my head wrapped around coding. Python is my first language, I started learning it a couple days ago.
And yes, I am aware that this was a very roundabout choice for a coding method, it's also the first thing I ever produced myself that is more than a couple lines long. So, in the end, is there any way I could make the function Question run more times without running into an issue with variables being returned? I am unsure as to whether that would actually be an issue or I am just too tired to see reason right now. I know I would need to create more if statements for the results section. That much is obvious.
name = raw_input("Please enter you preferred name: ")
print "Welcome, %r, to the general stupidity quiz." % name
raw_input("\n\tPlease press any button to continue")
question1 = "\n\nWhat is the equivilent of 2pi in mathmatics? "
answer1 = "tao"
answer1_5 = "Tao"
question2 = "\nWhat is 2 + 2? "
answer2 = "4"
w = 0
def Question(question, answerq, answere, inputs):
user_answer = raw_input(question)
if user_answer in [str(answerq), str(answere)]:
print "Correct!"
x = inputs + 1
return x
else:
print "False!"
x = inputs
return x
x = Question(question1, answer1, answer1_5, w)
x = Question(question2, answer2, answer2, x)
print "\nYou got " + str(x) + " questions correct..."
if x == 2:
print "You're not stupid!"
elif x == 1:
print "You're not smart!"
else:
print "I hate to tell you this...but..."
raw_input()
I added a raw_input() at the end so my cmd window wouldn't close. I know I could use ubuntu (recently uninstalled it) and I could also just run the code using the cmd window, but it's just a thing I tagged onto the end.
You should aim to have your functions be self contained and do one thing. Your function checks the correctness of a user input to an question and increments a counter. That is clearly two things. I will move the incrementing of the counter out of the function:
def question(question, answerq, answere):
user_answer = raw_input(question)
if user_answer in [str(answerq), str(answere)]:
print "Correct!"
return True
else:
print "False!"
return False
x = 0
if question(question1, answer1, answer1_5):
x += 1
if question(question2, answer2, answer2):
x += 1
Now I am going to clean it up a little by changing some names to be more meaningful and not assuming that every question will always have exactly two answers:
def question(question, correct_answers):
user_answer = raw_input(question)
if user_answer in correct_answers:
print "Correct!"
return True
else:
print "False!"
return False
correct_count = 0
if question(question1, [answer1, answer1_5]):
correct_count += 1
if question(question2, [answer2, answer2]):
correct_count += 1
To learn more, look into coding best practices and coding style. I recommend reading PEP8 for Python.
Welcome to programming! It's hard to tell what you are exactly after here but it seems to me like you want to be able to ask a bunch of different questions without writing more code each time.
One thing you can do is put your list of questions/answers into a list:
quiz = [("what is one + one? ", "2"), ("what is 2 + 2? ", "4")]
Here we are only allowing one correct answer so we need to change the Question() function (we can still accept "Tao" and "tao" by calling answer.lower() to remove capitalisation problems):
def Question(question, answer):
user_answer = raw_input(question)
if user_answer.lower() == answer:
print "Correct!"
x = inputs + 1
return x
else:
print "False!"
x = inputs
return x
Now all we have to do is call the Question function for each question in the quiz list:
for q in quiz:
Question(q[0], q[1])

Python while statement error

I am a beginner in python. My program is to set a number (I am not using random.randint for the moment) and I try to guess it. So here is the code:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
y = raw_input("Guess!")
while x > y:
y = raw_input("Too low. Guess again!")
while x < y:
y = raw_input("Too high. Guess again!")
if x == y:
return "You got it! The number was" + x + " !"
but when I run this, the program states that x < y, no matter WHAT number I put in.
Please, can someone help me? Thank you.
You need to convert y to an integer before comparing it to x:
y = int(raw_input("Guess!"))
Otherwise, you are comparing variables of different types, and the result is not always intuitive (such as x always being less than y). You can apply the same approach for the other times you ask the user to input y.
You may want this:
def game():
print "I am thinking of a number between 1 and 10!"
global x
x = 7
while True:
y = int(raw_input("Guess! ")) # Casting the string input to int
if x > y:
y = raw_input("Too low. Guess again!")
elif x < y:
y = raw_input("Too high. Guess again!")
elif x == y:
print "You got it! The number was " + str(x) + " !"
break # To exit while loop
game()
Y has to be an integer like x. A simple way to do this is:
y=int(raw_input("etc."))
You cannot compare two different variable types in python! Hope this helps!

Categories