I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
Related
I found this Python 3 code template in a coding website. The site claims that t will be a string of n integers.
n = int(input())
for i in input().split():
t = int(i)
I understand input.split() is for taking multiple inputs, like in a, b = input.split() will raise a ValueError until I give two inputs like 1 2.
What I don't understand is how it is implemented in a for-loop. Like, what value does i take on? And how Python is supposed to know that t will have n integers?
NOTE: I tried printing t. The result is as same as t = int(input()). I am not getting this. Please help.
I found this Python 3 code template in a coding website. The site claims that t will be a string of n integers.
If this is really the case, I recommend you to contact the owner of the website, because this statement is wrong, already by definition : A string is the contrary of an integer in Python. For an explanation of the code see below.
n = int(input())
for i in input().split():
t = int(i)
This code lets you first input a number n, which is never used.
Then, it lets you input a string containing numbers separated by spaces, splits the string at spaces and loops over the resulting list. Each item is converted to int, and assigned to a variable t, which, in the end, get's garbage collected because it is never used.
I"m trying to store 2 multi line inputs in 2 variables. However, std input methods keep getting hung up. I cannot change input format, but I can always expect 2 strings will be provided together. There is a new line character at the end of the first block and a new line character at the end of the second block.
I have tried several solutions from previous posts on how to accept multi line input, but none work for this case:
Store multi-line input into a String (Python)
When I try to use this code:
y input is accepted but x input is never accepted. I think the compiler is misinterpreting a line break somehow.
Any suggestions would be really appreciated.
y = input().strip()
x = input().strip()
TGGGAGGAGCAGTGATAATGCTACCTTGCTCGTGCCCCTTTAATGCCGGTGTCATCGCCTTAATGGGGTTCACAAGCAGTTACGGGGGGTCAAGTAATCATCGCGTTCGTCTTAGACGTGTCAGAGAACTAGTTTTGGAATCATTAACGACCTGCAATACTAGGTGCCAGCATAGGGTCTTTCGGAAGCACAACGTTGGAAGGCATCGCTTAGTGTAACCTAGTTACGGGAAGGCTACAGGTGCGGATGGTGGGGCCCAGCTGGGACTCAATCCAGGGACATCGGACTTTCGTTGGGGTTGAGCGGTCGCGAGGATTCGCAAGAGGGCGCCTTACAATGTTACCGTTTAGATTTACGGCCATTCCGACTTTGCAATTATTACCTTGAGCGATGCCGGCCATGCCGCGACATTATCAGTGATGTGTTCTCTCTCGGCTTGGTCGTTCAAACACGGGGCGTCATAGCTGAGTAGCCAAGGCAAACCAATTACCTACGTTCTGACCTGGCTGAATCTTGTGGAGCACCGGATCCAAGCAGTCGTGCCGGAGATTGTAGGCCAGCTTGTCATTCTGGATTGCGTTCCGCCCGATGTGAGCTTGTTCATACACCGAGTACGGGCTGCATTGGATCGTTCTATACGACAACGCTTCAGATCTCGAGTGCGTGGATCGAAGAAAGCGGAAGTCCGTTCGCGGACGCTCACAGCTGGTTGCTGCCGGCACCAACATGAACCGATCACCTAGCGCTTATAGTAAGCGGATATATCTTAGTATTAACCTTTCATTCCGGGCGGCACCTGAATGGGCAGTCTCGATTGATTAAGATCCCTTACTCTTCGAACTCGCGCGGACACGTCGTGCGCATCAATGGCAGTTATCTCGTATTAATACATACGCGTGATCAGCGCTATAGGGTATTTTTAGTTTTGGTCAACTCCGCAGTCACTGTGGATTGAATTGAGCATGCGGGCGAAGATCTGCTTTTCATCGCCTCTAACCAA
TATGGAGGACCAATGGTAGATGATACCGTTGCTCGGGGCGCTTTAAAGCCGGAGTAATGCGCCTATGAATGTGGGTTCACAGAGGAGTTCCCGGGGGGTCAACATCATCATGCGAGTGTCGTCTTAAAAGTGGCAGAATAACTGGTTTCTATGTATATCATTGAGCACCATCAATACGAGGTGTCAGCATGAGGCTCGTTCGGATGCCCGGCCTTGGAAGGCATCTGAGTTAGTATAACACTAGTTACGCGAAGGCTACAGGTGCGTGATCGTGCGGCCCAGTTGGGACTCAATTGAGGGACACGCGGACTTTCGTCGGGCTGTCAGAGGCCGGTCGGGGGAATGCGCAGGTTGTGCGGCACATACAATGTTATCGTTTCAGAATTTTATCGGCCATATCCGACTTTGCAATTATATTCCTTGCAGCGATGCCGGGGGAGCCGCGTACATGCATCAGTGTATGTATGCTCACTCGGCTATGTCGGTTCATAACCTGGCGCATATTAGCTGAGTAGACAAGGACTAAACCAATTAAACTACGTTCTGACCTCGCTATAGTATGTGAGTGAGTCACCGGATCCGAGCAGTTCGGGCCGCAGATTGGAGGCCAGCTTGTCATACTGGGTTGACCGTTTCGCCCGATGGGAGCTTGGTATCATACATCGAGTTACGTGGCTGCATTGTGTATCGTTCTGTTACGTACAACGCCTTCAAGGTCCCGAGTGCGAGGGTTCCCAGAAAAGCTGGAAGCGCAGTTCGTGAACTGCTCACAGCTGGTGGCTGCCGGCACCAACATGCACTTCGACTCACCTACCCAGCTAAATGTAAGCGCATATCTCTTAGTATATAACCTTTACATATCCGGGCGACGTACAGTAAAGAAGCAGGCTCGATGTCGTAGAGTTACCCTTACTACACTCGCAAATCGCGCGGACACGGTATGTACGCATTGAATCGACAGTTCTCTCGTATTTAGTACATACGCGTGATCAGCTGCTATAGAGTAATTCTAGCTTTGAGTGAACACCTCAGTGATGGCTGGATTGTAACTGAGCAACGCGGTCTGAGCGAACGGTTTTTGCATCGCGCTCTAACCAGG
I figured out that the problem was IDE specific. VS Code cannot accept large string input from console. No problems when using PyCharm.
When I run the following code :
import math
x=float(input('enter : '))
print(x)
and then I input : math.sin or cos or pi or log .... of a number like : sin(2) ,I get this error :
Traceback (most recent call last):
File "C:\Users\user\Desktop\hh.py", line 10, in <module>
x=float(input('enter : '))
ValueError: could not convert string to float: 'sin(x)'
You can get an answer by combining comments from #Walter Tross and #wwii. How to fix the problem if you want users to be able to enter code that will be evaluated with the result stored in x, you should use:
from ast import literal_eval
x = literal_eval(input('enter:'))
P.S. You will need to put quotation marks around the user input.
P.P.S. Your user can put in basically any code to be executed using this input.
To get to the why, you are giving python commands and expecting it to evaluate what you said and store it in x. You are giving words to python and not giving it a way to convert them to numbers. It'd be the same as typing into your terminal 2 plus 2. The words don't mean anything unless you have some kind of compiler.
It is difficult for you to write a program to understand and evaluate expressions, especially ones that include functions like sin or sqrt. However, if you are sure that the user of your program is safe (and that is usually a bad assumption), you can get Python to do the evaluation using the built-in eval function. You could try this:
import math
strexpr = input('enter: ')
print(eval(strexpr))
Then, if you run this program and the user types math.sin(2), the program prints
0.9092974268256817
which is the correct value of the sine of two radians.
NOTE: This little program will allow the user to type any valid Python expression then evaluate it. If the user knows how, he could use this to format the hard drive and wipe out all your data or do all kinds of mischief. Use this only if you are totally sure of the user. But how can you ever be sure about anyone else?
In Learn Python The Hard Way (Exercise 13) the 3rd Study Drill says to "Combine raw_input with argv to make a script that gets more input from a user."
I wrote this script below, intending to have the terminal prompt the user for answers to three questions, then it would print back phrases with those answers integrated into them. However, I get an error about not having enough values to unpack when I try to run it with the following command:
python ex13.py
I understand that I need more variables to unpack in order for the script to work, so when I type this then the script works but never outputs the variables "first", "second" or "third" (which I don't want it to anyway):
python ex13.py first second third
I know how to write a script without importing argument variables, but how else can I interpret the study drill? I know I am not understanding the prompt of the study drill correctly but I'm not sure how to write the script differently or even if I am going in the right direction.
Can anyone offer some tips or advice? You don't have to give me the answer outright (I like figuring things out) but I am at a loss for the moment.
MY SCRIPT:
from sys import argv
script, color, number, shape = argv
color = raw_input("What is your favorite color? ")
number = raw_input("What is your favorite number? ")
shape = raw_input("What is your favorite shape? ")
print """
This program is called %r and it will determine your
favorite color, number and shape.
""" % script
print "Based on your answers, your favorite color is:", color
print "Your favorite number is:", number
print "And your favorite shape is a:", shape
What exactly do you want your code to do? If you want to have
$ python ex13.py
$ What is your favorite color? <yourColor>
..........
$ Your favorite color is <yourColor>
Then you need to get rid of the part where you set all those values from argv. argv is a list of the arguments passed to python when you invoke it in the command line. The fix you have in your comments sets script = ['ex13.py'] instead of 'ex13.py' for precisely this reason, you're setting script to be a list as opposed to a string.
If you want your code to run so that you pass the script arguments when you run it, you could get rid of your sections calling for raw_input (or you could leave them in, but that would overwrite their values from what you passed in the command line) Try running the code you've posted with
$ python ex13.py <yourColor> <yourNumber> <yourShape>
It should work much more closely to what you want.
As you have already solved one problem by removing the variables before the =, now the only problem is you are getting square brackets around ex13.py.
You see you have to add another variable after script before = that is without input() and the problem is solved.
I'm new to Python and have been working through some tutorials to try to get to grips with different aspects of programming.
I'm stuck on an exercise that is most likely very simple however I am unable to find the solution.
How do I create a program that reads one line of input and prints out the same line two times?
For example if the input was Echo it would print:
Echo
Echo
Any help with this would be hugely appreciated. I think I'm making a simple logic error but don't yet have the skills in place to recognise what it is.
The other answers seem logical enough, but what if you wanted to print it let's say a 1000 times or a million times? Are you really going to be typing print(variable) a million types? Here is a faster way:
j=input("Enter anything.")
for i in range(2):
print(j)
Here, I can change the value of range to whatever I want, and J will be printed that many times.
What happens here, is that the variable i loops upwards (an increment) to the number 2, so to explain it to a beginner, i travels t=from number to number. Where I put print(j) for every number i loops through until it gets to 2, J will be printed.
It sounds like you've been doing the input and output in one go:
print(input())
That works for doing a single echo of the input, but makes it a bit harder to repeat the same thing twice. An easy workaround would be to save the inputted text to a variable, which you can print twice:
text = input()
print(text)
print(text)
If you needed to do the input and doubled output with a single statement, you could use string formatting to duplicate the text with a newline in the middle:
print("{0}\n{0}".format(input()))
way complex right?(:D)
inp = input("Input something would ya? ")
print(inp)
print(inp)