Basic Input/Output in Python - python

I am using notepad++ to write code for python and have a variable that I need to add 1 to for my next question. I am new to coding and would like to know how to achieve this. I would also like to phrase the question so that the answer (variable plus 1) is placed between text. Below, in my next line I would like it to read (for instance if the number is 3) How often do the 4 of you visit?
I have tried different ways of framing my variable +1 within parentheses and quotation marks but at best, when run, it shows exactly what I wrote not the answer to the equation.
famnumber = input ("How many of your family members still live there?")
I would like the answer to appear within text as noted above if possible.
Here is some code:
famadd = float(famnumber) + (1)
print ("Do all (famadd) of you get together often?")

There are several ways to do this. Note that when you you get something from input, it's a string. So using famnumber += 1 won't work, as you can't add a number to a string. So we have to turn the numeral string into an actual number. You can use int() to convert the input text into an integer. Then to include the value in a new string for your next question, use %d ('d' for 'digit'). This makes more sense than using a float, since people don't report family members in fractions of whole numbers (likewise, you don't want to say something like 'How often do the 4.0 of your meet?').
famnumber = input("How many of your family members still live there? ")
new_number = int(famnumber) + 1
next_question = input("How often do the %d of you meet? " % new_number)
Other ways to accomplish the same thing is converting 'famnumber' itself from a string to an integer, then back into a string to join in the sentence. Personally I'd go with the previous method, but this should give you an idea of some of the other things you can do in Python:
famnumber = input("How many of your family members still live there? ")
famnumber = int(famnumber)
famnumber += 1
next_question = input("How often do the " + str(famnumber) + " of you meet? ")
Also, while Notepad++ is a great text editor, if you're planning on doing a lot of Python scripting and writing, you may want to consider instead using an IDE, such as PyCharm, or IDLE which is included in the Python package. Tools like this make it easier for yourself to read and run your code.

I think you are looking for this kind of code:
famnumber = input("How many of your family members still live there?")
incremented_number = int(famnumber) + 1
next_number = input("How often do you " + str(incremented_number) + "visit")
print(next_number)
In the second line simply cast the input to int and increment it by one.
In the third line put the variable where you want it to be shown surrounded by + signs. You have to cast it to a string by using str() because the return type itself is a string. You can verify the type of the variable next_number simply by adding this line print(type(next_number))

Related

Pycharm quotation issues

So, pretty new with coding in general and im running into an issue. My assignment this week is to run a quick program that takes a name, and age and spit out a quick prompt repeating the name and stating a birth year. the big problem is PyCharm is putting everything in quotations.
So, with my input
user_name = raw_input('Enter your name:')
user_age = int(input('Enter your age:'))
birth_year = (2022 - user_age)
print('Hello', user_name+'!' ' ' 'You were born in', birth_year)
I am getting the output
Enter your name:Ryan
Enter your age:27
('Hello', 'Ryan! You were born in', 1995)
Process finished with exit code 0
Is this just something PyCharm does? I would love to get rid of all the quotation marks, but I also don't know if im just being too picky about formatting. I appreciate any advice!
You are using a combination of , and + to concatenate strings and some (seemingly) random '. This should work:
print('Hello ' + user_name + '! You were born in ' + str(birth_year))
The problem with your implementation is that python turns your output into a tuple (because of the ,) with the values you are seeing in your output.
Well, for starters, it looks like you’re using python 2. This is generally a bad idea when you start, as python 3 is used much more. But to answer your question, you aren’t printing out one string. Instead, you are printing a string ‘Hello ‘ then a completely different string, then an integer. The best way to print multiple variables in the same string is to use the built-in f’’ command. Simply use print(f’Hello, {user_name}! You were born in {birth_year}.’). However, I’m not sure if this is compatible with python 2.

I received an error message that I don't quite understand

I am working on a program and I received an error message that said:
print("I will set a timer for " + shortesttime + "minutes")
TypeError: can only concatenate str (not "int") to str
I assumed it meant that I had to change the variable from an int to a string but when I tried it it didn't work. Afterwards I just thought that maybe I wasn't understanding the error message correctly.
Here's some code for context:
shortesttime = hwt.index(min(hwt))
smallesthwitem = (uhw[hwt.index(min(hwt))]) #it's finding the position of the smallest item in homeworktime and then, for example if the place of that was 2 it would find what's at the second place in uhw
print("So let's start with something easy. First you're going to do " + smallesthwitem)
print("I will set a timer for " + shortesttime + "minutes")
Sorry about the weird variable names
The error says that concatenating (with +) a string to an integer is not allowed. Other languages (BASIC comes to mind) let you do that. The best thing to do is to use a formatter. If you want a simple formatting, then all you need is:
print(f"I will set a timer for {shortesttime} minutes")
There's options in formatters to add commas for thousands and other stuff, but this is easier than mucking with type conversions. This format was introduced in python 3.6 (called f-strings). If you are between 3.0 and 3.5 use
print("I will set a timer for {} minutes".format(shortesttime))
Which is equivalent, just a bit longer and not as clear.
Always Remember : To join multiple strings, You perhaps have to strings only. For example, You can't concatenate int with str .
So to print it you have to convert it to a string which is known as str in python world.
On the 4th line change it to : print("I will set a timer for " + str(shortesttime) + "minutes")
One more way would be formatted string :
Like this, print(f"I will set a timer for {shortesttime} minutes"). Formatted strings automatically converts any datatype to string.
As #ferdbugs mentioned earlier, you can cast any value to a string type.
Your code should look somewhat like this
shortesttime = hwt.index(min(hwt))
smallesthwitem = (uhw[hwt.index(min(hwt))]) #it's finding the position of the smallest item in homeworktime and then, for example if the place of that was 2 it would find what's at the second place in uhw
print("So let's start with something easy. First you're going to do " + smallesthwitem)
print("I will set a timer for " + str(shortesttime) + "minutes")
Hope this helps! Do let me know in the comments if you still get the same error or a different error.
Try:
print("I will set a timer for " + str(shortesttime) + "minutes")
You can cast it to a string.

Python read strings from file, preserving variables to be printed

I am making a Python script that will choose a response at random from a list.
To fill this list I want to read strings from a file, the strings will look something like this:
"This number is " + str(num) + ", this is good"
"Oh no the number is " + str(num) +", this is good
Obviously these are read from the file as strings so if I printed one of them they would come out as you see them here and wont have the value for "num" substituted. Is there anyway to read these strings from a file while keeping the ability to substitute variables (like a raw format) like how it would work if my code did
list.append("This number is " + str(num) + ", this is good")
The reason I want to read from a file is because I will have many different strings and they may change so I would rather not hard code them into the program (keep in mind the example strings are very basic)
Thanks
You could use the format specification mini-language, and then call .format on your strings before displaying them.
strings.txt:
This number is {num} this is good
Oh no the number is {num} this is good
main.py:
import random
with open("strings.txt") as file:
possible_strings = file.read().split("\n")
number = 23
s = random.choice(possible_strings)
print(s.format(num=number))
Possible output:
This number is 23 this is good
Use something in your file to indicate a substitution is needed, and then make those substitutions.
For example, if you need to put in the value of num, your text could use {{num}} where the substitution is needed. Then use regex to find such substrings, and replace them with the desired values.

Function creation - "Undefined name" - Python

I'm writing some code that reads words from a text file and sorts them into a dictionary. It actually all runs fine, but for reference here it is:
def find_words(file_name, delimiter = " "):
"""
A function for finding the number of individual words, and the most popular words, in a given file.
The process will stop at any line in the file that starts with the word 'finish'.
If there is no finish point, the process will go to the end of the file.
Inputs: file_name: Name of file you want to read from, e.g. "mywords.txt"
delimiter: The way the words in the file are separated e.g. " " or ", "
: Delimiter will default to " " if left blank.
Output: Dictionary with all the words contained in the given file, and how many times each word appears.
"""
words = []
dictt = {}
with open(file_name, 'r') as wordfile:
for line in wordfile:
words = line.split(delimiter)
if words[0]=="finish":
break
# This next part is for filling the dictionary
# and correctly counting the amount of times each word appears.
for i in range(len(words)):
a = words[i]
if a=="\n" or a=="":
continue
elif dictt.has_key(a)==False:
dictt[words[i]] = 1
else:
dictt[words[i]] = int(dictt.get(a)) + 1
return dictt
The problem is that it only works if the arguments are given as string literals, e.g, this works:
test = find_words("hello.txt", " " )
But this doesn't:
test = find_words(hello.txt, )
The error message is undefined name 'hello'
I don't know how to alter the function arguments such that I can enter them without speech marks.
Thanks!
Simple, you define that name:
class hello:
txt = "hello.txt"
But joking aside, all the argument values in a function call are expressions. If you want to pass a string literally you'll have to make a string literal, using the quotes. Python is not a text preprocessor like m4 or cpp, and expects the entire program text to follow its syntax.
So it turns out I just misunderstood what was being asked. I've had it clarified by the course leader now.
As I am now fully aware, a function definition needs to be told when a string is being entered, hence the quote marks being required.
I admit full ignorance over my depth of understanding of how it all works - I thought you could pretty much put any assortment of letters and/or numbers in as an argument and then you can manipulate them within the function definition.
My ignorance may stem from the fact that I'm quite new to Python, having learned my coding basics on C++ where, if I remember correctly (it was well over a year ago), functions are defined with each argument being specifically set up as their type, e.g.
int max(int num1, int num2)
Whereas in Python you don't quite do it like that.
Thanks for the attempts at help (and ridicule!)
Problem is sorted now.

Python- ArcMap - Calculate Fields

I am python newbie and I am trying to count the number of words in a column (Name) in ArcMap by using
!NAME!.count(' ') +
1
but I run into problems with strings like :
First N' Infant Care Center "Baby World"
type.exceptions.Syntaxerror,
even if I use " ",same problem I encounter when I am using other methods like split, strip etc.
Try
len(!Name!.split(" "))
If that doesn't work...let us know which feature it fails on and maybe more sample data?
Try encoding the string, arc does funny things with their string encoding...
!NAME!.encode('ascii', 'ignore').count(' ') + 1
Python can not easily handle mixed double and single quotes, so it's best if you first remove them.
One way to do this is to add another field (say newName, calculate it to have the same values as "Name" field, by doing just !NAME!. I am assuming you don't want to alter the Name field.
Then within editing mode, use find and replace to replace all quotes " or ' in that new column with nothing (just don't type anything in the replace and run replace all).
Now if you use that same approach you used with this new column/field, the problem won't occur.
!newName!.count(' ') + 1

Categories

Resources