Python printing multiple lines? - python

So I am a beginner to Python (previous experience with Java), and I was creating a simple OOP program. Here is my class:
from Tools.scripts.treesync import raw_input
class Info:
def startGame(self):
name = raw_input('What is your name?\n')
age = raw_input("What is your age?\n")
color = raw_input("What is your favorite color\n")
print("Your name is %s, your age is %s, and your favorite color is %s" % (name, age, color))
return Info
class App:
def build(self):
game_app = Info()
game_app.startGame()
return game
if __name__ == "__main__":
obj = App()
game = Info()
obj.build()
This is the output:
Your name is Chris
, your age is 18
, Sand your favorite color is Red
I am confused as to why it is printing on 3 lines? Is there any way to print this onto a single line?

The raw_input you're importing is keeping the CRLF in the input you entered. Why not use the built-in input() function (you are using Python 3, right)?
>>> from Tools.scripts.treesync import raw_input
>>> raw_input("> ")
> abc
'abc\n'
>>> input("> ")
> abc
'abc'
Also, Python is not Java. No need to put everything in classes.

You are using raw_input, which includes a line ending to the string, you can just use input() to obtain the string without a line ending.

Related

How to perform three different operations and import the module to another python script?

My aim:
To create a python Modules with 3 functions:
Sample input1: bob
output:
Yes it is a palindrome
No. of vowels:1
Frequency of letters:b-2,o-1
=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
ch = input("Enter a character: ")
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
In a new file I am giving :
import test
def main():
while True:
word = input("enter a word")
test.isPalindrome(word))
test.count_the_vowels(word))
if __name__ == "__main__":
main()
If I call my module in another file, it automatically does all the functions. But I want to give input(name) in this new module and check the output for it.But this is asking input again since name is present before def function in the other file. How to overcome this?
I am new to coding.Please be as elaborate as possible.Thanks in advance.
If you're question is "how to ask for the name only once and pass it to both function", the answer is simple: in your main.py script (or test.py or however you named it), add this:
import yourmodule # where you defined your functions
def main():
while True:
word = input("enter a word (ctrl+C to quit) > ")
yourmodule.isPalindrome(word)
yourmodule.count_the_vowels(word)
# etc
if __name__ == "__main__":
main()
Now note that your assignment doesn't say you have to do this - it says:
Import the module in another python script and test the functions by passing appropriate inputs.
Here, "passing appropriate inputs" can also be understood as having a harcoded list of words and calling your functions with those names... IOW, a unit test.
After trying several times to explain in the comments here is a brief example. so make a file with your functions. then in your other file import your funcs file then ask user for name and pass it to the funcs. This is just an example of how to define functions in one file and then call them from another. you probably want to look at your funcs as they should probably return values rather then just print stuff otherwise your calling file wont be able to validate the function since it will receive nothing back.
MyFuncs.py
def hello(name):
print(f"hello {name}")
def goodbye(name):
print(f"goodbye {name}")
stackoverflow.py
import MyFuncs
name = input("Name: ")
MyFuncs.hello(name)
MyFuncs.goodbye(name)
**OUTPUT: **when running the stackoverflow.py script
Name: Chris
hello Chris
goodbye Chris

Why printing a string three times gives error 'cannot be intrepreted as an int'?

https://pastebin.com/ztix8Aue
def namex3():
ask = input("What is your name?")
name = ask
for i in range(name):
print(name * 3)
namex3()
I'm trying tob define a function called “namex3” that takes an argument called
“name” and prints “hello " {name} three times on the screen, however I am getting an error that it Cannot be interpreted as an integer, how would I fix this?
Continuing from the comments above, fixed:
def namex3():
ask = input("What is your name?")
for i in range(3):
print(ask)
namex3()
OUTPUT:
What is your name?TFX
TFX
TFX
TFX
Try this if you intend to use a function :
def namex3():
print(*["hello " + input("What is your name?")]*3, sep = "\n")
namex3()
You almost had it:
def namex3()
name = input("What is your name? ")
for i in range(3):
print("Hello", name)
namex3()
Notice that every indent level is 4 spaces which is the adviced style in Python.
You could even shorten it to
name = "some name"
print(name * 3)
Or (with newlines):
print("{}\n".format(name) * 3)
As OP asked for a function that will print "Hello {name}" three times, here it is:
def name_three_times():
name = input("What is your name?")
print(f'Hello {name}\n' * 3)
Note the use of f-strings: https://realpython.com/python-f-strings/
That's because you're attempting range('hello')
range() expects integer arguments, but you are passing 'hello', which is a string.

Struggling with Python syntax when trying to check if a string from an input is in a variable

I’m finding the Python syntax very confusing, mainly concerning variables. I’m trying to learn it using the Microsoft EDX course but I’m struggling when trying to check if a string from an input is in the variable.
Example 1: Check if a flavor is on the list
# menu variable with 3 flavors
def menu (flavor1, flavor2, flavor3):
flavors = 'cocoa, chocolate, vanilla'
return menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
#print the result
print ("It is", data in menu, "that the flavor is available")
Example 2: Print a message indicating name and price of a car
def car (name, price):
name = input(“Name of the car: “)
price = input (“Price of the car: “)
return (name, price)
print (name, “’s price is”, price)
Also, I would like to know what would be the disadvantage of doing something like this for the example 2:
name = input("name of the car: ")
price = input ("price of the car: ")
print (name,"is", price,"dollars")
Could someone please clarify this to me? Thank you very much!
i didnt understand what your trying to do in first example.
But i can partially understand what your trying to do in second example,
def car ():
name = input("Name of the car: ")
price = input ("Price of the car: ")
return name, price
name,price = car()
print ("{}\'s price is {}".format(name,price))
the above code is the one of the way to solve your problem,
python can return multiple variable
use format function in print statement for clean display.
You dont need function parameters for car. since your taking input from in car function and returning it to the main.
Hope it helps you understand.
Example 1
# menu variable with 3 flavors
def menu():
flavors = 'cocoa, chocolate, vanilla'
return flavors #return flavors instead of menu
# request data from the user flavorName = input('What flavor do your want? ')
data = input("What flavor do you want? ")
# print the result
print ("It is", data in menu(), "that the flavor is available") #menu is a function so invoke with menu () instead of menu
Example 2:
def car(): #no input required since you are getting the input below
name = input('Name of the car: ')
price = input('Price of the car: ')
return (name, price)
name, price = car() #call the function to return the values for name and price
print (name, "’s price is", price)
The below approach works and is faster as compared to calling the function although adding small stuff to form functions allows the program to be modularized, making it easier to debug and reprogram later as well as better understanding for a new programmer working on the piece of code.
name = input("name of the car: ")
price = input("price of the car: ")
print (name, "is", price, "dollars")
Just found how to print the result in the way the exercise required. I had difficulty explaining, but here it is an example showing:
def car(name,price):
name_entry = input("Name car: ")
price_entry = input("Price car: ")
return (name_entry,price_entry)
This is the way to print the input previously obtained
print (car(name_entry,price_entry))
Thank you very much for all the explanations!

Python: getting variable from user function [duplicate]

This question already has answers here:
Returning a value from function?
(2 answers)
Closed 4 years ago.
im trying to make a simple text game for a school project and also make the code somewhat clean therefore I started using functions and classes.
The problem is im stuck on trying to access a variable from a function that asks the user for their username.
Here is my code
def playername():
print("What is your name?")
playername = input()
how can I access the playername variable without running the whole function again so once I run it at the start and get the username I can use that same input username later on in the code?
You can define your function like this:
def get_playername():
playername = input('Whats is your name? ')
return playername
Then,use it:
name = get_playername()
store it as a variable outside of function. for example string playerName = playername() and add return playername to the end of the function "playername"
def playername():
print("What is your name?")
playername = input()
return playername
def main():
playerName = playername()
print(playerName)
main()
Firstly, it's a good idea to name your function and variables differently. So, I'd use something like "name" to store the name of the player.
You can print the question and store the value at the same step with the input() function
def playername():
name = input("Enter you name: ")
print("Hello {}".format(name))
return name
name = playername()
playername variable is limited (scoped) to playername function, it cannot be accessed from outside the function
You should return the playername value, so that the function caller can store and use this value
def playername():
print("What is your name?")
playername = input()
return playername
def main():
my_playername = playername()
# use my_playername as much as you like
...
main()
Returning values from a function is a basic programming skill. I strongly recommend that you work through class materials or a tutorial on the topic.
def get_player_name():
print("What is your name?")
name = input() # Do NOT give two program objects the same name.
return name
# Main Program
victim_name = get_player_name()

Having trouble in python 3.0 with this code

I've been having trouble with this little program, it skips over the if == "otc": part completely, I've tried stuff to fix it but I just can't get it to work.
print("Hello, what is your name?")
name = input()
if name == "OTC":
print("get out otc!")
elif():
print("Hello! " + name
If you want to check if input has otc you can convert it into uppercase and check but if you want case sensitivity don't use upper()
Modification:
name = input("Hello, what is your name?")
if name.upper() == "OTC":
print("get out otc!")
else:
print("Hello! " + name)
output:
Hello, what is your name?"otc"
get out otc!
Hello, what is your name?"barny"
Hello! barny
Changes in your code:
There is no need for print since the same thing can be done using input function
There is no need for elif since there is only one condition check so use else
elif is a statement and not a function so remove the ()

Categories