python calling empty list invalid syntax - python

I am trying to create an empty list and for some reason it is telling me it's invalid syntax? it also flags the next line with the same error, saying that while count<amount: is invalid. am i wrong for thinking this doesnt make sense? using vsc. thanks in advance.
my code looks like this.
list=[]
count=0
while count < amount :
s=int(input"enter a number:")
list.append(s)
count= count+1
i tried to use list={}, list=() even though i know those are wrong. it also flags lines like list4=[1,3] ??

amount is not defined. Define it with a number like 5 and try then.
You also need to make sure the variable list is called something else, it is a python-reserved word.
Lastly, make sure the input function has parenthesis () around it. e.x. input("enter number: ")

In python the indent is 4 spaces.
You need to change the variable name "list" because it is a built in name in python.
You need to put brackets after input.
amount = 5
numberList = []
count = 0
while count < amount:
s = int(input("enter a number:"))
numberList.append(s)
count += 1

I think the problem there is that you're using input() wrong, it should be:
int(input("Enter a number: "))
Also, I am assuming that you defined amount earlier in your code, otherwise you will need to in order for your code to work :D
I also saw a comment saying that list is a python reserved function: It is, however you can use it as a variable name and it will not return an error :)
Have a good day :D

Related

Python printing beginner

I just started with python. My teacher gave me an assignment and I'm stuck on a project where I have to make the numbers of characters appear when someone enters their name for input command input("what is your name") I don't think I have been taught this and google is giving me a hard time when trying to look for the command. This might be Childs play to most but can anyone throw me a tip/hint?
using print(len(myVariable)) should output the number of characteres that the string has. You should familiarize yourself with python methods.
Here are some resources:
https://docs.python.org/3/library/functions.html
https://www.w3schools.com/python/ref_func_len.asp
Printing the length of a variable is very easy with Python due to the many built-in functions you can perform on strings! In this case, you would use use len(). Read about other helpful string methods in python too in order to get a head start on your class!
inputtedName = input("What is your name? ")
nameLength = len(inputtedName)
print("Your name is " + str(nameLength) + " letters.")
print(f"Your name is {nameLength} letters.")
The first print statement uses something called string concatenation to create a readable sentence using variables. The second uses f strings to make using variables in your strings even easier!

How to get the length of a value from user input?

I'm working on an assignment:
My input is supposed to be a name, it could be anything.
The output is supposed to be the length of the name.
e.g.
Currently, I have:
print(input("What is your name? ")
print(len(input)
But the second half isn't correct.
If you need to DO something with the value, then you have to store it in a variable:
name = input("What is your name? ")
print(name)
print(len(name))
I think I located the problems in your code. This is what it should look like:
n = input("What is your name? ")
print((len(n))
I tested and switched things up a bit by adding a variable called "n" and giving it the input value. Then I wrote a changed into string version of the len of n... If that makes sense.
I put three brackets in the second line because the first one is for the print statement, the second one len, and the last one for the int.
Don't worry too much as it was an honest mistake! :)
PS. This is the better version of the code:
n = input("What is your name? ")
print("Your name has "+len(n)+" letters")
According to your question, your one line code can done in this way:
print(len(input("what is your name ?")))

Input a message inside a box

I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")

Running my python code in Gitbash

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]))

How to count the number of user input at stdin in python

Hi I apologize if this looks like homework, but I have been trying and failing to make this work, and I would really appreciate some expert help. I am trying to self-teach myself python.
I'm trying to solve problems in CodinGame and the very first one expects you to count the times input strings are passed to the program. The input string comes in two parts (eg. "Sina dumb"). I tried to use this:
count = int(sys.stdin.readline())
count = int(input())
count = int(raw_input()) #python2
But the program fails with:
ValueError: invalid literal for int() with base 10: 'Sina dumb\n'
depending on if I leave the newline in or not.
Please what am I doing wrong, and how can I make it better?
In python2.x or python 3.x
sys.stdin.readline() and input gives type str. So int("string") will produce error if string contains chars.
I think you need this(assuming)
import sys
input_var = input() # or raw_input() for python 2.x
# entering Sina dumb
>>>print(len(input_var.split()))
2
Update
If you want to count how much input you enter.Try this
import sys
from itertools import count
c = count(1)
while True:
input_var = input()
print ("you entered " + str(next(c)) + " inputs")
On one hand, in this case, python say you that you tried ton convert the String 'Sina dumb\n into integer that is not valid, and this is true. This probably triggered at the second line, int(input)
On the other hand, to solve your problem,one simple approach as each row you pass as input contains the end of line character \n you can for example get the input content, and split it at \n characters and count the size of the resulting list.
input() in python 3.x and raw_input()in python 2.x give a string. If a string contains anything but numbers it will give a ValueError.
you could try regular expression:
import re
line = input()
count = len(re.findall(r'\w+', line))
print (count)

Categories